Spring如何管理映射表(多对多) [英] Spring how to manage a mapping table (Many to Many)

查看:107
本文介绍了Spring如何管理映射表(多对多)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,用户可以拥有一个或多个角色,为此我决定创建一个映射(中间)表,所以我以 User 结束, 角色 UserRole 像这样:



在这个应用程序中,用户确定何时可以访问前端中某些视图或操作的角色。我唯一需要的是检索用户的角色并添加/删除它们。 JPA Tools创建了他跟随我的EJB(简化版):

USER

  / ** 
* usuario数据库表的持久类。
*
* /
@Entity
@NamedQuery(name =Usuario.findAll,query =SELECT u FROM Usuario u)
public class Usuario implements可串行化{

private static final long serialVersionUID = 1L;

private int idUsuario;

私人列表< RolUsuario> rolUsuarios;

public Usuario(){
}


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getIdUsuario(){
return this.idUsuario;
}

public void setIdUsuario(int idUsuario){
this.idUsuario = idUsuario;
}


//与RolUsuario双向多对一关联
@OneToMany(mappedBy =usuario)
public List< RolUsuario> getRolUsuarios(){
返回this.rolUsuarios;
}

public void setRolUsuarios(List< RolUsuario> rolUsuarios){
this.rolUsuarios = rolUsuarios;
}

public RolUsuario addRolUsuario(RolUsuario rolUsuario){
getRolUsuarios()。add(rolUsuario);
rolUsuario.setUsuario(this);

返回rolUsuario;
}

public RolUsuario removeRolUsuario(RolUsuario rolUsuario){
getRolUsuarios()。remove(rolUsuario);
rolUsuario.setUsuario(null);

返回rolUsuario;
}

}

USER_ROLE

  / ** 
* rol_usuario数据库表的持久类。
*
* /
@Entity
@Table(name =rol_usuario)
@NamedQuery(name =RolUsuario.findAll,query =SELECT r FROM RolUsuario r)
public class RolUsuario实现Serializable {
private static final long serialVersionUID = 1L;
private int idRol_Usuario;
private Usuario usuario;
私人滚动;

public RolUsuario(){
}


@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getIdRol_Usuario(){
return this.idRol_Usuario;
}

public void setIdRol_Usuario(int idRol_Usuario){
this.idRol_Usuario = idRol_Usuario;
}


//双向多对一关联到Usuario
@ManyToOne(fetch = FetchType.LAZY)
public Usuario getUsuario (){
返回this.usuario;
}

public void setUsuario(Usuario usuario){
this.usuario = usuario;
}


//双向多对一关联到Rol
@ManyToOne(fetch = FetchType.LAZY)
public Rol getRol (){
return this.rol;
}

public void setRol(Rol rol){
this.rol = rol;
}

}

在我的项目中,我使用EJB为前端创建POJO。当我要求给定用户的完整角色列表时,我应该如何去做:


  1. 使用CrudRepository创建一个UserRole存储库, metod,如
    List< RolUsuario> findByUsuario(Usuario user);

  2. UserRole 列表返回给我的 User Service ,然后遍历
    列表,将每个角色提取到 UserPOJO


  3. 发送至前端。




  4. 或者有什么方法可以马上开始在表 UserRole 其中用户中列出了 Roles (Id?)=东西?



    这对我来说很难描述。我的应用程序只关心用户的角色,而不是映射表实体,所以botton行是,我必须得到他们,但我不知道从哪里开始。



    任何指针都是非常有用的。



    编辑:

    或者我可以......


    1. 为用户新增角色创建UserRole。

    2. 将UserRole添加到用户列表中。

    3. 为了获得用户的角色,请使用UserRolelist。


    解决方案

    用户和角色的架构不常用。我建议你从用户角色创建 @ManyToMany 关联。如果您需要将连接表映射到实体(不太可能),则可以稍后执行。请使用英文标识符和Java命名约定( idRol_Usuario )。它会帮助你和其他人。

      @Entity 
    @Table
    public class User {

    @Id
    @GeneratedValue
    私人长时间pid;

    @ManyToMany(fetch = FetchType.LAZY)
    private List< Role>角色;



    @Entity
    @Table
    公共类角色{

    @Id
    私有Long pid ;

    @Column
    私人字符串名称;

    $ b $ / code>

    您可以使用 Set< Role> ; too

      @ManyToMany(fetch = FetchType.LAZY)
    private Set< Role> ;角色;


    I am developing an app where the user can have one or more roles, for this I decided to created a mapping (intermediate) table, so I ended with User, Role and UserRole like this:

    In this app the role(s) a user has determines wheneaver he can access certain views or actions in the frontend. The only thing I need is to retrive the roles a user has and add/delete them. JPA Tools created he following EJB for me (simplified):

    USER

    /**
     * The persistent class for the usuario database table.
     * 
     */
    @Entity
    @NamedQuery(name="Usuario.findAll", query="SELECT u FROM Usuario u")
    public class Usuario implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        private int idUsuario;
    
        private List<RolUsuario> rolUsuarios;
    
        public Usuario() {
        }
    
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        public int getIdUsuario() {
            return this.idUsuario;
        }
    
        public void setIdUsuario(int idUsuario) {
            this.idUsuario = idUsuario;
        }
    
    
        //bi-directional many-to-one association to RolUsuario
        @OneToMany(mappedBy="usuario")
        public List<RolUsuario> getRolUsuarios() {
            return this.rolUsuarios;
        }
    
        public void setRolUsuarios(List<RolUsuario> rolUsuarios) {
            this.rolUsuarios = rolUsuarios;
        }
    
        public RolUsuario addRolUsuario(RolUsuario rolUsuario) {
            getRolUsuarios().add(rolUsuario);
            rolUsuario.setUsuario(this);
    
            return rolUsuario;
        }
    
        public RolUsuario removeRolUsuario(RolUsuario rolUsuario) {
            getRolUsuarios().remove(rolUsuario);
            rolUsuario.setUsuario(null);
    
            return rolUsuario;
        }
    
    }
    

    USER_ROLE

    /**
     * The persistent class for the rol_usuario database table.
     * 
     */
    @Entity
    @Table(name="rol_usuario")
    @NamedQuery(name="RolUsuario.findAll", query="SELECT r FROM RolUsuario r")
    public class RolUsuario implements Serializable {
        private static final long serialVersionUID = 1L;
        private int idRol_Usuario;
        private Usuario usuario;
        private Rol rol;
    
        public RolUsuario() {
        }
    
    
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        public int getIdRol_Usuario() {
            return this.idRol_Usuario;
        }
    
        public void setIdRol_Usuario(int idRol_Usuario) {
            this.idRol_Usuario = idRol_Usuario;
        }
    
    
        //bi-directional many-to-one association to Usuario
        @ManyToOne(fetch=FetchType.LAZY)
        public Usuario getUsuario() {
            return this.usuario;
        }
    
        public void setUsuario(Usuario usuario) {
            this.usuario = usuario;
        }
    
    
        //bi-directional many-to-one association to Rol
        @ManyToOne(fetch=FetchType.LAZY)
        public Rol getRol() {
            return this.rol;
        }
    
        public void setRol(Rol rol) {
            this.rol = rol;
        }
    
    }
    

    In my project I am using the EJB to create POJO for the frontend. When I ask for the full list of roles for a given user how should I go about doing this:

    1. Create a UserRole repository using CrudRepository with a metod like List<RolUsuario> findByUsuario(Usuario user);
    2. Return the list of UserRole to my User Service and go over the the list extracting each Role into a UserPOJO

    3. Send to frontend.

    Or is there any way to just get right off the bat a list of Roles in table UserRole where User(Id?) = something?

    This is hard to describe for me. My app only cares for the roles of a user, not the mapping table entity, so the botton line is that somehow I have to get them but I don't know where to start.

    Any pointers would be extremely useful.

    Edit:

    Or I could...

    1. Create UserRole for new role addition to a user.
    2. Adding UserRole to the List inside User.
    3. To get the roles of a user get the UserRolelist instead.

    解决方案

    Your schema for User and Role is not commonly used. I advice to you make a @ManyToMany association from a user to roles. If you will need to map a join table to the entity (unlikely) you can do it later. And, please, use English identifiers and Java naming convention (idRol_Usuario). It will help you and others.

    @Entity
    @Table
    public class User {
    
        @Id
        @GeneratedValue
        private Long pid;
    
        @ManyToMany(fetch = FetchType.LAZY)
        private List<Role> roles;
    
    }
    
    @Entity
    @Table
    public class Role {
    
        @Id
        private Long pid;
    
        @Column
        private String name;
    
    }
    

    You can use Set<Role> too

    @ManyToMany(fetch = FetchType.LAZY)
    private Set<Role> roles;
    

    这篇关于Spring如何管理映射表(多对多)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆