![](/img/trans.png)
[英]Spring JPA and JDBC Template - very slow select query execution with IN clause
[英]Spring JPA Hibernate : slow SELECT query
我遇到優化問題,無法弄清楚為什么查詢這么慢。
這是我的實體:
@Entity
@Table(name = "CLIENT")
public class Client {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "CLIENT_ID")
@SequenceGenerator(name = "ID_GENERATOR", sequenceName = "CLIENT_S", allocationSize = 1, initialValue = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_GENERATOR")
private Long id;
@Column(name="LOGIN")
private String login;
@Column(name="PASSWORD")
private String password;
還有DAO
@NoRepositoryBean
public interface ClientDao extends JpaRepository<Client, Long>, JpaSpecificationExecutor<Client> {
Client findByPasswordAndLogin(@Param("login") String customerLogin,@Param("password") String customerHashedPassword);
}
執行findByPasswordAndLogin方法時,大約需要200毫秒才能完成(通過Junit測試和JProfiler均可看到)。
在這里,Hibernate查詢:休眠:從CLIENT clientx0_中選擇clientx0_.CLIENT_ID作為CLIENT_ID1_4_,clientx0_.LOGIN作為LOGIN9_4_,clientx0_.PASSWORD作為PASSWORD10_4_,clientx0_.STATUT作為STATUT13_4_,其中clientx0_.PASSWORD =? 和clientx0_.LOGIN =?
當我在數據庫上手動執行SQL查詢時,只需要3毫秒:
select * from CLIENT where PASSWORD='xxxxx' and LOGIN='yyyyyyyy'
在我們的開發環境中,我們有4000個客戶。 年生產量超過一百萬。
這里的上下文:
任何想法 ?
我已經測試了不同類型的DAO(因為它太臟了,所以我不在這里發布代碼):
注意事項:
我可以使用:
但是:
因此:
帶有RowMapper的Spring JDBCTemplate似乎是提高特定情況下性能的最佳解決方案。 而且我們可以保證SQL查詢的安全性。 但是需要編寫特定的RowMapper才能將ResultSet轉換為Entity。
Spring JDBCTemplate的示例
@Repository
public class ClientJdbcTemplateDao {
private final Logger logger = LoggerFactory.getLogger(ClientJdbcTemplateDao.class);
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Client> find() {
List<Client> c = this.jdbcTemplate.query( "SELECT login FROM Client WHERE LOGIN='xxxx' AND PASSWORD='xxx'", new ClientRowMapper());
return c;
}
}
客戶端RowMapper的示例
public class ClientRowMapper implements RowMapper<Client> {
@Override
public Client mapRow(ResultSet arg0, int arg1) throws SQLException {
// HERE IMPLEMENTS THE CONVERTER
// Sample :
// String login = arg0.getString("LOGIN")
// Client client = new Client(login);
// return client;
}
}
也許可以更好,任何建議都是值得歡迎的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.