开发者

Loading from one persistance unit and persisting in another

开发者 https://www.devze.com 2023-02-10 04:36 出处:网络
I have a problem with Hibernate/JPA, a problem when the magic behind the scene makes life difficult. What I would like to do is very trivial so there should be a solution for this but I just can\'t fi

I have a problem with Hibernate/JPA, a problem when the magic behind the scene makes life difficult. What I would like to do is very trivial so there should be a solution for this but I just can't find it.

So I would like to load some tables from one persistance unit (database) and store them into another persistance unit (another database). There is nothing funny going on here just load and persist.

In my first attempt I used persist to store the detached entities in a new persistance unit. It didn't work 开发者_如何学Goas they already have identifiers so I had to try something else.

So my second attempt is to used merge but this resulted in Hibernate doing one (at least) select per entity extra. Using the merge caused this to be extremely slow and in the end not usable for us.

So to my question, is there anyway of persisting detached entities in a new persistance unit without using merge? I already know that the tables are empty so I don't need hibernate to check it for me...


This should work.

Entity e = em1.load(id);
em1.detach(e);
e.setId(0); // or null
em2.persist(e);

You'll have to make setId visible to this code of course.

If you're trying to implement replication for everything, doing it in the actual databases is probably a better idea (i.e. use whatever cluster features your DBMS has).

Edit:

Another option would be to implement a (deep) copy constructor for your entities.

Entity e1 = em1.load(id);
Entity e2 = new Entity(e1);
em2.persist(e2);
0

精彩评论

暂无评论...
验证码 换一张
取 消