Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 更新多对多关系中的实体_Java_Hibernate_Jpa - Fatal编程技术网

Java 更新多对多关系中的实体

Java 更新多对多关系中的实体,java,hibernate,jpa,Java,Hibernate,Jpa,我有一个Spring项目,它使用JPA和Hibernate以及MySQL数据库。数据库包括三个表:用户、角色和多对多联接表UserRoles。 下面是表的相应类 ApplicationUser.java @Entity @Table(name = "APPLICATION_USER") public class ApplicationUser extends ExtAuditInfo { public static final Long SYSTEM_USERID = 1000L; @Id

我有一个Spring项目,它使用JPA和Hibernate以及MySQL数据库。数据库包括三个表:用户、角色和多对多联接表UserRoles。 下面是表的相应类

ApplicationUser.java

@Entity
@Table(name = "APPLICATION_USER")
public class ApplicationUser extends ExtAuditInfo {

public static final Long SYSTEM_USERID = 1000L;


@Id
@Column(name = "APPLICATION_USER_ID")
private long applicationUserId;

@Column(name = "LOGIN_NAME")
private String loginName;

@Column(name = "LAST_NAME")
private String lastName;

@Column(name = "FIRST_NAME")
private String firstName;

@Column(name = "MIDDLE_NAME")
private String middleName;

@OneToMany(mappedBy = "id.applicationUser", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<UserRole> roles =new ArrayList<>();

//get and set methods
UserRoleID.java

@Entity
@Table(name = "ROLE")
@NamedQueries({
@NamedQuery(name = "Role.getRoleById", query = "select r from Role r where r.roleId =:roleId"))}
public class Role extends AuditInfo {

@Id
@Column(name="ROLE_ID")
private long roleId;

@Column(name="ACTIVE_FLAG")
private String activeFlag;

@Column(name="ROLE_NAME")
private String roleName;

@OneToMany(mappedBy = "id.role", fetch = FetchType.LAZY)
private List<UserRole> users = new ArrayList<>();

//get and set methods
@Entity
@AssociationOverrides({
        @AssociationOverride(name = "id.applicationUser",
                joinColumns = @JoinColumn(name = "APPLICATION_USER_ID")),
        @AssociationOverride(name = "id.role",
                joinColumns = @JoinColumn(name = "ROLE_ID")) })
@Table(name = "USER_ROLE")
public class UserRole extends ExtAuditInfo implements Serializable{
    @EmbeddedId
    private UserRoleID id = new UserRoleID();

    @Column(name="USER_ROLE_VER")
    private long userRoleVer;

    public UserRole(){
    }

    @Transient
    public ApplicationUser getApplicationUser() {
        return this.id.getApplicationUser();
    }

    public void setApplicationUser(ApplicationUser applicationUser) {
        this.id.setApplicationUser(applicationUser);
    }

    public long getUserRoleVer() {
        return this.userRoleVer;
    }

    public void setUserRoleVer(long userRoleVer) {
        this.userRoleVer = userRoleVer;
    }

    @Transient
    public Role getRole() { return this.id.getRole(); }

    public void setRole(Role role) { this.id.setRole(role); }
}
@Embeddable
public class UserRoleID implements Serializable {

    @ManyToOne(cascade = CascadeType.ALL)
    private ApplicationUser applicationUser;

    @ManyToOne(cascade = CascadeType.ALL)
    private Role role;

    private static final long serialVersionUID = 1L;

    public UserRoleID() {
    }

    public ApplicationUser getApplicationUser() {
        return this.applicationUser;
    }

    public void setApplicationUser(ApplicationUser applicationUser) {
        this.applicationUser = applicationUser;
    }

    public Role getRole() {
        return this.role;
    }

    public void setRole(Role role) {
        this.role = role;
    }
}
现在,当我使用viewer角色创建一个示例用户时,记录被插入到Application\u user和user\u role表中,但是当我尝试更新用户的角色时,它将向用户添加一个新角色,而不是更新现有角色

这就是我正在做的

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateRole(ApplicationUser appUser, long roleId){
        EntityManager em=getEntityManager();
        TypedQuery<Role> query = em.createNamedQuery("Role.getRoleById", Role.class);
        query.setParameter("roleId",roleId);
        Role r = query.getSingleResult();
        UserRole userRole= appUser.getRole().get(0);
        userRole.setRole(r);
        em.merge(userRole);
        em.flush();
        em.detach(userRole);
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void updateRole(ApplicationUser appUser,长角色ID){
EntityManager em=getEntityManager();
TypedQuery query=em.createNamedQuery(“Role.getRoleById”,Role.class);
setParameter(“roleId”,roleId);
角色r=query.getSingleResult();
UserRole UserRole=appUser.getRole().get(0);
userRole.setRole(r);
em.merge(userRole);
em.flush();
em.detach(userRole);
}

您知道如何更新现有角色而不是在用户角色表中创建新角色吗?

您正在将新角色分配给用户,因此在用户角色表中添加新记录,并删除旧的用户角色条目。这是正确的行为。 所以这不是你所谓的“更新用户角色”

更新:
当出现多对多关系时,应手动删除角色

appUser.getRoles().remove(userRole);
em.remove(userRole);
UserRole newUserRole = new UserRole();
newUserRole.setRole(r);
appUser.getRoles().add(newUserRole);

未删除旧角色,用户_角色表现在具有这两条记录。在多对多关系中,您应该手动删除角色。