Hibernate
01 / 02

Entities, Sessions & Relationships

Entities, Sessions & Relationships

Entities

@Entity
@Table(name = "authors")
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Post> posts = new ArrayList<>();
}

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @ManyToOne(fetch = FetchType.EAGER)  // @ManyToOne defaults to EAGER
    @JoinColumn(name = "author_id")
    private Author author;
}

Session Lifecycle & Dirty Checking

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
try {
    Author author = session.get(Author.class, 1L);  // null if not found
    author.setName("Updated Name");  // no explicit update() call needed —
                                       // Hibernate detects the change (dirty
                                       // checking) and generates the UPDATE at flush

    Post post = new Post();
    post.setTitle("Hello World");
    post.setAuthor(author);
    session.persist(post);

    tx.commit();
} catch (Exception e) {
    tx.rollback();
    throw e;
} finally {
    session.close();
}

HQL & Criteria API

// HQL — references Java class/property names, not raw table/column names
List<Author> adults = session
    .createQuery("FROM Author a WHERE a.age > :minAge", Author.class)
    .setParameter("minAge", 18)
    .getResultList();

// Criteria API — type-safe, catches property-name typos at compile time
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Author> query = cb.createQuery(Author.class);
Root<Author> root = query.from(Author.class);
query.select(root).where(cb.greaterThan(root.get("age"), 18));
List<Author> result = session.createQuery(query).getResultList();

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free