private LoadingCache<String, Entity> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<String, Entity>() {
public Entity load(String key) {
return getEntityFromDatabase(key);
}
}
);
public Entity getEntity(String key) {
try {
return cache.get(key);
} catch (ExecutionException e) {
// handle exception
}
return null;
}
public void updateEntities(List<Entity> entities) {
Connection connection = getConnection();
try {
PreparedStatement statement = connection.prepareStatement("UPDATE entity set value=? where id=?");
for (Entity entity : entities) {
statement.setString(1, entity.getValue());
statement.setInt(2, entity.getId());
statement.addBatch();
}
statement.executeBatch();
} catch (SQLException e) {
// handle exception
}
}
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
config.setUsername("username");
config.setPassword("password");
config.setMaximumPoolSize(10);
HikariDataSource dataSource = new HikariDataSource(config);
Connection connection = dataSource.getConnection();
@Entity
@Table(name = "entity")
public class Entity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String value;
// getters and setters
}
@Repository
public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao {
@Override
public Entity getEntityById(int id) {
return getHibernateTemplate().get(Entity.class, id);
}
@Override
public void saveEntity(Entity entity) {
getHibernateTemplate().save(entity);
}
}