Using EcliplseLink JPA how can I disable all the relationship lookups when persisting an object?

蓝咒 提交于 2019-12-11 12:05:23

问题


When I persist an object with a foreign key, I see in the logs that eclipselink goes off and does a verification query, like this: I also see that eclipselink finds this object and binds it. I don't want it to do either of these things.

Basically I am trying to save object A, and A has a relationship with object B. When I go to insert a new A, all I have is the ID for B, not an instance of class B, and I am not interested in obtaining an instance of B in this case.

Something like this:

String b_id = "12345";
A a = new A();
B b = new B();
b.setId(b_id);
a.setB(b);


//begin tran
try {
    em.persist(a);
//commit
} catch (Exception e) {
    e.printStackTrace();
    //rollback
}

which causes this in the logs:

Execute query DoesExistQuery(referenceClass=B)
SELECT ID FROM B WHERE (ID = ?)
bind => [12345]

Now I want to insert A without Eclipselink going to verify if there exists a B with this Id, and I don't want it to bind this B to the field of A which is an instance of B.

I don't want Eclipselink adding this overhead to the insert, because the database is going to be doing this validation before the insert anyways, and I don't need an actual instance of B in this case.

Any reply is appreciated, thanks!


回答1:


This is normally the role of the EntityManager.getReference() method: it creates and returns a proxy to the entity having the given class and ID, without hitting the database:

A a = new A();
B b = em.getReference(B.class, bId);
a.setB(b);

I have no experience with EclipseLink though, so I don't know when exactly is this query executed.




回答2:


Using getReference is probably best. You could also customize your DoesExist policy on your descriptor (@ExistenceChecking(ASSUME_EXISTENCE)).




回答3:


The cascade annotation on A <-> B relation determines that extra call. Probably you have CascadeType.ALL and what you want is CascadeType.REFRESH and CascadeType.REMOVE only.



来源:https://stackoverflow.com/questions/9400930/using-ecliplselink-jpa-how-can-i-disable-all-the-relationship-lookups-when-persi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!