Violet_82 89 Posting Whiz in Training

Hi all,
I have an application which saves data (books details like book title, author and location) to a mySql db and performs CRUD operations.
I thought I'd use hibernate to take care of the ORM side of things and everything was OK when it came to create a record, but for RUD operations I had an issue.
If I'm a user, I'm likely to be willing to find a book by its author, title or location, certainly not by its ID and yet as far as I can see, hibernate uses IDs for these kind of operations.
I dug a bit further and eventually resorted to Criteria objects which apparently allow you do perform operations creating your own criteria, see below for the update functionality:

 public void update() {
        // code to modify a book
        Session session = sessionFactory.openSession();
        String searchTerm = "Jack";
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Book.class);
        Book uniqueResult = (Book) criteria.add(Restrictions.eq("author", searchTerm)).uniqueResult();
        uniqueResult.setTitle("Amended plus one");
        session.update(uniqueResult);
        session.getTransaction().commit();
        session.close();        
    }

The problem is that criteria have been deprecated and I can't find a good alternative to that, which now makes me question my choice to use hibernate in the first place. What do you guys think? I wouldn't mind using hibernate but I find hard to believe that to find a record I have to use an ID and not the author, title or whatever else, unless of course you can get the ID of the record from the searchTerm like author etc but I couldn't find a way, all the examples online relied on an ID to be passed on to the query, which I find very odd.
If you fancy looking at the application, it can be found here https://github.com/Antobbo/book-storage/tree/master/src/main/java/com/test (it's not a big project, lol)

Dani AI

Generated

A few practical notes for (and anyone hitting the same trap).

Hibernate does not force lookups by the numeric PK — queries can use any mapped property (author, title, location, etc.). The old org.hibernate.Criteria API is legacy and no longer recommended; Hibernate points users toward JPA CriteriaQuery/CriteriaBuilder or plain HQL/JPQL instead. (docs.hibernate.org)

Simple, robust patterns that avoid the deprecated API:

  • Read-modify-commit (preferred when a single row is being changed): fetch the entity by property, modify its fields inside the same transaction, then commit — Hibernate’s automatic dirty-checking flushes the change (no explicit session.update() required for a managed instance). Example pattern:
Book book = session.createQuery("from Book b where b.author = :a", Book.class)
                   .setParameter("a", "Jack")
                   .getResultList().stream().findFirst().orElse(null);
if (book != null) {
    book.setTitle("Amended plus one");
    // commit transaction -> Hibernate will flush the update
}

Use the typed createQuery(...) form or a JPA CriteriaQuery for dynamic queries. (docs.hibernate.org)

  • Bulk updates (single-round-trip) are supported via HQL update ... but they operate directly at the DB level and do not synchronize in-memory entities in the persistence context; clear or evict affected entities afterward to avoid stale state. Example:
int count = session.createQuery(
    "update Book b set b.title = :title where b.author = :a")
    .setParameter("title", "Amended plus one")
    .setParameter("a", "Jack")
    .executeUpdate();
session.clear(); // avoid stale persistent state

Bulk-DML caveats documented in Hibernate docs. (docs.redhat.com)

Consider mapping a unique business key with @NaturalId (ISBN or similar) for fast lookups by a stable natural identifier; Hibernate exposes session.bySimpleNaturalId(...).load(...) for this use. Index frequently-searched columns at the DB level and pick getResultList/getSingleResult appropriately to avoid non-unique-result errors. (docs.hibernate.org)

These options keep code simple, avoid deprecated APIs, and let searches/updates be written against domain properties instead of forcing numeric IDs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.