简体   繁体   English

Hibernate:使用带有连接表的双向多对一映射持久化实体 - org.hibernate.PropertyValueException

[英]Hibernate: persist entity with bidirectional many-to-one mapping with join table - org.hibernate.PropertyValueException

Hello i am trying to persist one of my entities "Role" which has a many-to-one relation via a join table to my other entity "User".您好,我正在尝试保留我的一个实体“角色”,它通过连接表与我的另一个实体“用户”具有多对一的关系。 However every time i try to insert role without any users attached i get the following error: org.hibernate.PropertyValueException: not-null property references a null or transient value.然而,每次我尝试在没有附加任何用户的情况下插入角色时,我都会收到以下错误:org.hibernate.PropertyValueException:not-null 属性引用空值或瞬态值。 My Role entity mapping to User:我的角色实体映射到用户:

@ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH,
            CascadeType.DETACH })
    @JoinTable(name = "t_UserRoles", joinColumns = {
            @JoinColumn(name = "cUserRolesRoleId", referencedColumnName = "cRoleId") }, inverseJoinColumns = {
                    @JoinColumn(name = "cUserRolesUserId", referencedColumnName = "cUserId") })
    private User user;

And my User to Role:我的用户角色:

@OneToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH })
    @JoinTable(name = "t_UserRoles", joinColumns = {
            @JoinColumn(name = "cUserRolesUserId", referencedColumnName = "cUserId") }, inverseJoinColumns = {
                    @JoinColumn(name = "cUserRolesRoleId", referencedColumnName = "cRoleId") })
    private Set<Role> roles;

the code that throws the exception:引发异常的代码:

...
Role newRole = new Role();
            newRole.setRoleName(roleName);
            roleAfterSave = manager.merge(newRole);
            manager.getTransaction().commit();

The goal is to be able to save the Role without the need to create User instance as well.目标是能够在不需要创建用户实例的情况下保存角色。 Things i have already tried:我已经尝试过的事情:

@ManyToOne(optional = true,... @ManyToOne(可选=真,...

@JoinColumn(name = "cUserRolesRoleId", referencedColumnName = "cRoleId",nullable = true) @JoinColumn(name = "cUserRolesRoleId", referencedColumnName = "cRoleId",nullable = true)

Tell me if you need any more of the code!如果您需要更多代码,请告诉我! Thanks for the help in advance!我在这里先向您的帮助表示感谢!

First of all, is there any reason to have a join table at one-to-many relationship?首先,有没有理由在一对多关系中有一个连接表?

I think, either, there should be a "Role definition" table, where role types are defined, but then the Role entity shouldn't be related to concrete user.我认为,或者,应该有一个“角色定义”表,其中定义了角色类型,但是角色实体不应该与具体用户相关。 The relationship should be rather many-to-many.这种关系应该是多对多的。 For me, that makes more sense.对我来说,这更有意义。

Or the Role entity is really related to user, but then I would leave out a join table.或者 Role 实体确实与用户相关,但是我会省略连接表。

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

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