jap设置两个表中oneToMany/ManyToOne

多对一的关系我们通常在多的一方来维护。现在使用tbUser和tbRole来完成例子,一个人只能有一个角色。
在user表中我们使用ManyToOne注解来完成关系映射,JoinColumn来设置关联的外键在数据库中的名称。

@Entity
@Table(name = "tb_user")
@SequenceGenerator(name = "tb_user_sq",sequenceName = "tb_user_sqe")
public class TbUser extends BaseEntity{


    /**
     * 用户名
     */
    private String userName;
    /**
     * 登录名
     */
    private String loginName;
    /**
     * 登陆密码
     */
    private String passWord;
    /**
     * 手机号
     */
    private String telPhone;
    /**
     * 一个用户只有一个角色
     */
    private TbRole tbRole;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getTelPhone() {
        return telPhone;
    }

    public void setTelPhone(String telPhone) {
        this.telPhone = telPhone;
    }

    @Id
    @Override
    @GeneratedValue(generator = "tb_user_sq",strategy = GenerationType.SEQUENCE)
    public Long getId() {
        return this.id;
    }
    @ManyToOne(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "tb_role_id")
    public TbRole getTbRole() {
        return tbRole;
    }

    public void setTbRole(TbRole tbRole) {
        this.tbRole = tbRole;
    }
}

在role中我们如果想直接使用这个关系的话,同样添加一个外键字段,在外键字段上添加注解OneToMany(mappedBy = “tbRole”),mappdBy对应的是当前实体在外键实体中的字段名。

@Entity
@Table(name = "tb_role")
@SequenceGenerator(name = "tb_role_sq",sequenceName = "tb_role_sqe")
public class TbRole extends BaseEntity{


    @Override
    @Id
    @GeneratedValue(generator = "tb_role_sq",strategy = GenerationType.SEQUENCE)
    public Long getId() {
        return this.id;
    }

    private String roleName;

    private List tbUserList=new ArrayList<>();

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }
    @OneToMany(mappedBy = "tbRole")
    public List getTbUserList() {
        return tbUserList;
    }

    public void setTbUserList(List tbUserList) {
        this.tbUserList = tbUserList;
    }
}

你可能感兴趣的:(jpa)