Sobes.tech
Senior

How do you work with databases? Hibernate/JPA — how do you use it?

sobes.tech AI

Answer from AI

When working with a database through Hibernate/JPA, I usually:

  • Use Entity classes to map database tables.
  • Apply JPA annotations (@Entity, @Table, @Id, etc.) to define the mapping.
  • Manage sessions via EntityManager or SessionFactory.
  • Use transactions to ensure atomicity of operations, typically through @Transactional.
  • Write JPQL or Criteria API for complex queries to stay within ORM.
  • Optimize data loading with LAZY/EAGER fetch strategies.
  • Carefully monitor N+1 problems and apply fetch joins or batch fetching.
  • For complex or specific queries, I may use native SQL.

Example of usage:

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    // getters and setters
}

// In the service
@Transactional
public User getUser(Long id) {
    return entityManager.find(User.class, id);
}