How JPA (Hibernate) deal with transaction when fetching Object from database

I'm currently developping an application in java using Hibernate as a persistence manager and JPA as an abstraction of the persistence manage hibernate.

I'd like to know the impact of wrapping a result query around a transaction. I know the entity manager must stay open for lazily fetched field bug what about transaction in all this ?

Here is a code example with transaction activation/desactivation ability.

public List<Exportdata> get(Integer max, EntityManager em, Boolean withTransaction) {
    EntityTransaction tx = null;
    try {
        if (withTransaction) {
            tx = em.getTransaction();

        Query query = em.createQuery("from Exportdata");
        List<Exportdata> list = query.getResultList();

        if (withTransaction)

        return list;
    } catch (RuntimeException re) {
        if (withTransaction)
            if (tx != null && tx.isActive())

        throw re;

What is the difference between enabling or disabling withTransaction when this function is called ?

Thanks all, Fred

Asked by: Miller368 | Posted: 28-01-2022

Answer 1

There is no practical difference here, since you aren't changing any data. The query you execute will generate an SQL select. Transactions are there to allow you to apply ACID properties to a collection of inserts, updates, etc.

However, if you begin manipulating the objects in the list returned from this method, calling setters, etc. those changes will be propagated back to the database out-with a transaction on an ad-hoc basis. In other words you'll effectively be working with the db in auto-commit mode. This is unlikely to be what you want.

The important thing to understand is that the duration of a persistence context and a transaction can be managed separately. Often though you would want to manage them together.

Answered by: Lily708 | Posted: 01-03-2022

Similar questions

java - What's difference between primitive and wrapper class in JPA (Hibernate) column mappings?

For instance, there’s an integer column in a database table. Then in java model, it can be mapped both as primitive int and Integer. My question is what's difference between the int and Integer in this case? And performance concern? Thanks!

java - JPA (hibernate) onetomany relation

I am not sure what I am missing to make a bidirectional onetomany relationship (hibernate engine). A scaled down version of the domain model: class Person { @OneToMany(mappedBy="personFrom", cascade = CascadeType.PERSIST) public List&lt;Relationship&gt; relationships; } class Relationship { @ManyToOne public Person personFrom; @ManyToOne public Person personTo; } Some of the ob...

java - Can anyone tell why this JPA criteria query generates an invalid SQL statement when executed (Hibernate) and how to fix it?

I'm having a hard time constructing a criteria query to get the "permissions" attribute from the Role entity with id = 2. The permission attribute is of Set type, so I'm creating a join and selecting from it, but the query fails with invalid grammar exception reporting "Unknown column '2L' in 'where clause'" The criteria query that generates the error was built this way: EntityManager entityManager ...

Java: Objects relations with criteria (hibernate)

I have a problem with criteria and relation between objects. I present a simple scheme before: I have 2 objects: A is the parent B is the child with a link at parent. I know how to create a query to have B with A's restriction: Criteria criteria = this.getSession().createCriteria(B.class); criteria.add(Property.forName("").eq("test")); But my problem is the ne...

java - JPA (Hibernate) and custom table prefixes

Is it possible to override table names in JPA/Hibernate in order to add a common prefix for all project entities? For instance to be able to prefix all JBPM 5 tables by "JBPM5_" prefix. Example for the accepted answer: public class JBPM5NamingStrategy extends ImprovedNamingStrategy { public String classToTableName(String className) { return StringHelper.unqualify(className); } public ...

java - Is there a way to use JSR-303 (hibernate) annotations and modify the Message using {0} {1} syntax?

Is there a way to use JSR-303 (hibernate) annotations and modify the Message using {0} {1} syntax? It seem that using a Spring Validator gets you this: String args[] = {"mark", "is", "cool"}; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aboutYou", "aboutYou.required", args); So I can change the message. However, if I use annotations, I cannot use the message args. I understand that there are li...

java - Querying my JPA provider (Hibernate) for a collection of <Id,Name> of an entity

I have an entity which looks something like this: Id (PK) Name Other business properties and associations... I have the need for my DAL (JPA with hibernate as provider) to return a list of the entities which correlate to some constraints (or just return them all) but instead of returning the entities themselves I'd like to receive only the Id and the Name properties. I know this can be achieved ...

java - How can I tell if a Grails/GORM domain instance has been deleted in the current tx (Hibernate)?

I am looking for a "isDeleted()" test for Grails (GORM) instances: Project p = ... get persistent entity from somewhere ... p.delete() // done in some nested logic ... sometime later in the code prior to commit of the tx ... if (!p.isDeleted()) ... do some more stuff ... In my app the logic that may delete p is elsewhere and passing a flag back or something would be a pain.

java - JPA (Hibernate) Native Query for Prepared Statement SLOW

Having strange performance issue using Hibernate 3.3.2GA behind JPA (and the rest of the Hibernate packages included in JBoss 5.) I'm using Native Query, and assembling SQL into a prepared statement. EntityManager em = getEntityManager(MY_DS); final Query query = em.createNativeQuery(fullSql, entity.getClass()); The SQL has a lot of joins, but is actually very basic, with a single ...

java - Bean validation on JBoss seam and JPA (Hibernate)

I have created a custom constraint and only want that to be called at pre-persist moment. Also, I have created the validation group and set it in the persistence.xml file according to the specification. It seems that the validation is being called at the right time (pre-persist), passing by my custom constraint implementation and forth, however I'm getting the exception below when the validation is accomplished.

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)