简体   繁体   English

尝试使用@ManyToOne映射来持久化实体

[英]Trying to persist an entity with @ManyToOne mapping

I'm trying to persist a User that has a mapping @ManyToOne with UserStatus 我正在尝试坚持使用UserStatus映射@ManyToOne的用户

but when I do the code below, the hibernate throws PropertyValueException 但是当我执行下面的代码时,hibernate会抛出PropertyValueException

user.setStatus(new UserStatus(1));
em.persist(user); // ou session.saveAndUpdate(user);

to work I have to do this way: 工作我必须这样做:

user.setStatus(em.getReference(UserStatus.class, 1));
em.persist(user); // ou session.saveAndUpdate(user);

I know the first way is possible, but what I don't know is whether I need to configure or call another method (I've already tried saveAndUpdate from Session and still the same) 我知道第一种方式是可能的,但我不知道的是我是否需要配置或调用另一种方法(我已经尝试过Session中的saveAndUpdate并且仍然相同)

Does anyone have any idea? 有人有什么主意吗?

The error message is: 错误消息是:

not-null property references a null or transient value

the mapping 映射

@ManyToOne(optional = false)
@JoinColumn(name = "user_status_id", nullable = false)
public UserStatus getStatus() {
    return status;
}

This error means " you are referencing a null (not persisted) object " and you have to choice: remove nullable or set @Cascade so UserStatus will per persisted when you do em.persist(user) 此错误意味着“ 您正在引用一个null(非持久化)对象 ”,您必须选择:删除nullable或设置@Cascade这样当您执行em.persist(user)时, UserStatus将持续存在

@ManyToOne(optional = false)
@JoinColumn(name = "user_status_id", nullable = false)
@Cascade(cascade=CascadeType.ALL)
public UserStatus getStatus() {
    return status;
}

EDIT: After various test, using getReference() is the right way to proceed because new UserStatus(1) go for error and should be substituted as getReference(UserStatus.class,ID) to return a proxied instance of UserStatus. 编辑:经过各种测试后,使用getReference()是正确的方法,因为new UserStatus(1)会出错并应该替换为getReference(UserStatus.class,ID)以返回UserStatus的代理实例。 Proxied object doesn't hit on database, so SELECT is avoided and the only field setted on UserStatus proxy is the ID, necessary to resolve @ManyToOne relation! Proxied对象没有命中数据库,因此避免使用SELECT,并且在UserStatus代理上设置的唯一字段是解析@ManyToOne关系所必需的ID!

Some useful answer: When to use EntityManager.find() vs EntityManager.getReference() 一些有用的答案: 何时使用EntityManager.find()vs EntityManager.getReference()
What is the difference between EntityManager.find() and EntityManger.getReference()? EntityManager.find()和EntityManger.getReference()之间有什么区别?

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

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