Junior — Middle
What methods have you used to improve the efficiency of database interactions in your projects?
sobes.tech AI
Answer from AI
To improve the efficiency of interacting with the database in Java projects, I used the following methods:
- Caching: implementing cache (e.g., with Ehcache or Redis) to reduce the number of database requests.
- Query optimization: writing efficient SQL queries, using indexes, avoiding redundant JOINs.
- Batch processing: executing multiple insert/update operations in a single request.
- Using ORM with lazy loading: for example, Hibernate with fetch type settings to load data only when necessary.
- Connection pool: using connection pools (HikariCP, C3P0) to reduce connection setup costs.
Example of batch processing with JDBC:
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
conn.setAutoCommit(false);
for (User user : users) {
ps.setString(1, user.getName());
ps.setString(2, user.getEmail());
ps.addBatch();
}
ps.executeBatch();
conn.commit();
}