1.一对一的关系关联
需求:用户和角色一对一关联
packageimport javax.persistence.*;
@Entity
@Table(name = "t_user")
public class)
private)
private/***///JoinColumn:维护一个外键的作用
privatepublicreturnpublic voidthis.id =publicreturnpublic voidthis.name =publicreturnpublic voidthis.role = role;
}
}
packageimport javax.persistence.*;
@Entity
@Table(name = "t_role")
public class)
private)
private)
privatepublicreturnpublic voidthis.id =publicreturnpublic voidthis.name =publicreturnpublic voidthis.user = user;
}
}
/***/public void//创建角色
Role role =new);
//创建用户
User user =new);
//建立关系
//保存数据
/***/public voidlong)13);
System.out.println(user);
Role role = user.getRole();
System.out.println(role);
}
2.一对多关联关系
需求:从角色到用户的一对多关联关系
packageimport javax.persistence.*;
@Entity
@Table(name = "t_user")
public class)
private)
private)
privatepublicreturnpublic voidthis.id =publicreturnpublic voidthis.name =publicreturnpublic voidthis.role = role;
}
}
packageimport javax.persistence.*;
importimport)
public class)
private)
private)
private Set<User> userSet = new HashSet<>();
publicreturnpublic voidthis.id =publicreturnpublic voidthis.name =public Set<User>returnpublic void setUserSet(Set<User>this.userSet = userSet;
}
}
/***/public void//创建角色
Role role =new);
//创建用户
User user =new);
//建立关系
//保存数据
/***/public voidlong)13);
System.out.println(user);
Role role = user.getRole();
System.out.println(role);
}
3.多对多的关联关系
需求:用户和角色多对多关系
packageimport javax.persistence.*;
importimport)
public class)
private)
private//fetch = FetchType.EAGER:异步加载
//JoinTable 配置中间表信息
//joinColumns 建立当前表在中间表中的外键字段
@JoinTable(name = "t_user_role",joinColumns = @JoinColumn(name = "user_id")
,inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles =new HashSet<>();
publicreturnpublic voidthis.id =publicreturnpublic voidthis.name =public Set<Role>returnpublic void setRoles(Set<Role>this.roles = roles;
}
}
packageimport javax.persistence.*;
importimport)
public class)
private)
private)
private Set<User> users =new HashSet<>();
publicreturnpublic voidthis.id =publicreturnpublic voidthis.name =public Set<User>returnpublic void setUsers(Set<User>this.users = users;
}
}
/***/public void//创建角色
Role role =new);
//创建用户
User user1 =new);
User user2 =new);
//建立关系
//保存数据
/***/public voidlong)13);
System.out.println(user);
Set<Role> roles = user.getRoles();
System.out.println(roles);
}