Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I auto-detach SqlResultSetMapping Entity from EntityManager?

I'm using a @SqlResultSetMapping for an @Entity that is purely read-only (and has no backing table in the database). I'm loading tens of thousands of these into memory, so I need to detach the entities from the EntityManager to avoid Hibernate's dirty entity checking when I do work later.

Is there a way to annotate the Entity, or the SqlResultSetMapping, so that the entities are never added to the EntityManager?

Non-persisted entity:

@SqlResultSetMapping(name = "fooMapping", entities = @EntityResult(entityClass = Foo.class))
@Entity
public class Foo {
    @Id
    public Long row_id;
    public String name;
}

Native query:

String sql = "SELECT id AS row_id, friendlyName AS name FROM SomeTable"; 
Query q = JPA.em().createNativeQuery(sql, "fooMapping");
List<Foo> fooList = q.getResultList();

Current solution:

for (Foo f : fooList) {
    JPA.em().detach(f); // 100x improvement for subsequent DB work
}

// subsequent database work
like image 852
Chris Betti Avatar asked Jan 26 '26 03:01

Chris Betti


1 Answers

One way to avoid dirty checking is to indicate to hibernate that the query is fetching read-only entities. You can do this in JPA by using query hints

q.setHint("org.hibernate.readOnly",true);

From hibernate doc:

org.hibernate.readOnly : Entities retrieved by this query will be loaded in a read-only mode where Hibernate will never dirty-check them or make changes persistent ( eg. new Boolean(true) ), default to false

like image 98
ben75 Avatar answered Jan 28 '26 17:01

ben75



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!