简体   繁体   English

JPA EclipseLink添加/更新实体

[英]JPA EclipseLink Adding/Updating entities

I'm a bit confused with the way JPA handle adding/updating entities. 我对JPA处理添加/更新实体的方式有些困惑。

ATM, i have this piece of code: 自动取款机,我有这段代码:

AltContact c = new AltContact("test");
save(c)
System.out.println("ENTITY: " + contains(c));
c.setEnterpriseName("test2");
save(c);
System.out.println("ENTITY: " + contains(c));

The save method is a simple method on the server side of my application requesting a merge on the EntityManager: save方法是我的应用程序服务器端请求在EntityManager上进行合并的一种简单方法:

public void save (Object e) {
    em.merge(e);
    em.flush();
}

Where em is an instance of EntityManager . 其中emEntityManager

contains is once again a method on server side that will ask the entity manager if a given entity exist in the current persistent context. contains再次是服务器端的一种方法,该方法将询问实体管理器当前当前持久上下文中是否存在给定实体。

The code above create two rows in my table, the first one with the value "test" and the other one with the value "test2", which is not what i want. 上面的代码在我的表中创建了两行,第一行的值为“ test”,另一行的值为“ test2”,这不是我想要的。

I want to create a new row with the value "test" and then, right after the creation of the row, update it and set his value to "test2". 我想用值“ test”创建一个新行,然后在创建该行后立即对其进行更新,并将其值设置为“ test2”。 I printed out the return of contains after both call to save , false was returned the two times. 我在两次调用save之后都打印了包含的返回,两次都返回了false

I guess the problem come from the fact that my entity is not part of the persistent context after the first call to save so when i call save again, the entity manager consider it's a new entity and create a new row. 我猜问题出在以下事实:我的实体在第一次调用save之后不属于持久上下文,因此当我再次调用save时,实体管理器认为它是一个新实体,并创建了一个新行。

How can achieve this updating process? 如何实现此更新过程?

A few things. 一些东西。 First why do you need to use merge() are you serializing the instance, and why? 首先,为什么要使用merge()序列化实例,为什么? If you just edit the object returned from the persistence context, then you don't need to do any merging or saving. 如果仅编辑从持久性上下文返回的对象,则无需进行任何合并或保存。

If you need to edit the object as serialized, or detached, then for a new object you need to return the Id of the object from your save, this is what will link the detached object with the managed one. 如果需要将对象编辑为序列化或分离的,则对于新对象,需要从保存中返回对象的ID,这将链接分离的对象与托管对象。 Ideally you would execute a find() to get the object before you edit it. 理想情况下,您将在执行编辑之前执行find()以获取对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM