简体   繁体   English

持久的Java实体参考问题

[英]persisted java entity reference issue

I am working on a personal project, and i have a strange issue which i can't seem to solve, even after many hours of research and debugging, so obviously it must be somehting very simple i'm ignoring .... Anyway, the context is : JPA + PostgresSQL + Glassfish. 我正在做一个个人项目,即使经过许多小时的研究和调试,我也遇到了一个似乎无法解决的奇怪问题,因此很明显,这很简单,我就忽略了....无论如何,上下文是:JPA + PostgresSQL + Glassfish。 I have an entity (generated by netbeans), MvUser, with: 我有一个实体(由netbeans生成),MvUser,具有:

@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
@SequenceGenerator(name="mv_user_autoincrement_gen",sequenceName     ="mv_user_autoincrement",allocationSize=1)  
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="mv_user_autoincrement_gen") 
private Long id;

Then, i have an AbstractFacade with generics for all the boilerplate persistence code. 然后,对于所有样板持久性代码,我都有一个具有泛型的AbstractFacade。
Here i have a method which doesn't do much, just: 在这里,我有一个方法并不能做很多事情,只是:

@Override
public void create(T entity) {
    getEntityManager().persist(entity);
}

Now, let's say i call this in my service class: First i inject my facade: 现在,假设我在服务类中将此称为:首先,我注入我的外观:

@EJB
IMvUserFacade userFacade;

then i'll use it: 然后我将使用它:

@Override
public void saveUser(MvUser user)
{
    userFacade.create(user);
    // more business specific code follows
}  

I make a call to the service like this 我这样打电话给服务

MvUser = new MvUser();
... setters etc
mvUserService.saveUser(user);

Now, what is happening is that in the create method the object is persisted, i have the generated id and everything. 现在,正在发生的事情是,在create方法中该对象得以保留,我拥有生成的ID和所有内容。 Because on the whole chain i have object parameters, i'm presuming that at the saveUser level the same object will be found, but no, i am left with a detached entity. 因为在整个链上我都有对象参数,所以我假设在saveUser级别上将找到相同的对象,但是不,我剩下一个分离的实体。 What i'm doing wrong? 我做错了什么? Thanks. 谢谢。

If I understand you correctly, you want to search for the object you saved in create(). 如果我对您的理解正确,则想搜索保存在create()中的对象。 I think the object is not yet persisted to database, what you retrieve is the object from first-level cache, http://www.tutorialspoint.com/hibernate/hibernate_caching.htm , since you are still within transaction. 我认为该对象尚未持久保存到数据库中,您检索的是来自一级缓存http://www.tutorialspoint.com/hibernate/hibernate_caching.htm的对象,因为您仍在事务中。 If you try to retrieve the object as follow and the method saveUser() is not within transaction you will get the user object from database (but detached since outside transaction): 如果尝试按以下方式检索对象,并且方法saveUser()不在事务内,则将从数据库中获取用户对象(但由于在外部事务中已分离):

public void saveUser(MvUser user)
{
userFacade.create(user);
userFacade.get(userId);
// more business specific code follows
} 

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

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