JDBC, JPA, Hibernate
Spring with JDBC
@Repository
class PersonJdbcDao {
@Autowired
JdbcTemplate template;
public List<Person> findAll() {
return template.query("select * from person",
new BeanPropertyRowMapper(Person.class));
}
}Spring with JPA EntityManager
@Transactional
@Repository
class SomeRepository {
@Autowired
EntityManager manager;
public SomeClass findById(Long id) {
return manager.find(SomeClass.class, id);
}
public void createAndUpdate(Course course) {
manager.persist(course); // entity is stored in db
course.setName("new name");
// even though I do not ask explicitly to merge
// the entity in db => entity is updated
// because the method is declared to be transactional
}
public void detachExample(Course course) {
manager.persist(course);
maanger.detach(course);
// entity is not tracked any more by manager
// => following update is not happening
course.setName("new name");
}
public void clearExample(Course course) {
manager.persist(course);
maanger.clear();
// no entity is tracked by manager
// => course is not updated
course.setName("new name");
}
public void refreshExample(Course course) {
manager.persist(course); // course has name "Bla"
course.setName("new name");
maanger.refresh(course);
// refresh loads current representation of course
// => course will have name "Bla" at this point
}
}Hibernate annotations
Working with dates
java.sql.Date vs java.util.Date vs java.time.LocalDate
Named queries
Native queries
Transactional
comment
javax @Transactional
manage transaction over single DB
spring @Transactional
(isolation=...)
manages transactions over several DBs (if you call many DBs in one method)
Spring Data JPA
Project setup for Spring, Hibernate and Kotlin
Great article which describes how to setup Hibernate properties for Kotlin case
Last updated
Was this helpful?