Environment: Spring Data jpa,hibernate or other JPA implementations are the same; Spring Boot
Scenario: User and role, one user to correspond to multiple role.
The first way, without an intermediate relational table, adds a user_id field directly to the role table
User:
Import Javax.persistence.*;import Javax.validation.constraints.notnull;import Java.util.hashset;import java.util.set;/** * Created by Zhangpeng on 16-6-15. */@Entity @table (name = "Users") public class User {@Id @GeneratedValue (strategy = generationtype.auto) Private lo NG ID; The user email @NotNull private String email; The user name @NotNull private String name; private String password; @OneToMany (Mappedby = "User", Cascade = {Cascadetype.all}, Fetch = Fetchtype.eager) Private set<role> roles = new Hashset<> (); Public set<role> GetRoles () {return roles; } public void Setroles (set<role> roles) {this.roles = roles; Public user () {} public user (long id) {this.id = ID; } public Long GetId () {return id; } public void SetId (long id) {this.id = ID; } public String Getemail () {return email; public void Setemail (String email){this.email = email; } public String GetName () {return name; } public void SetName (String name) {this.name = name; } public String GetPassword () {return password; } public void SetPassword (String password) {this.password = password; }}
Role:
Import javax.persistence.*;/** * Created by Zhangpeng on 16-6-17.*/@Entity @table (name="Roles") Public classRole {@Id @GeneratedValue (strategy=Generationtype.auto) Long ID; String RoleName; @ManyToOne @JoinColumn (Name="user_id") User user; PublicUser GetUser () {returnuser; } Public voidsetUser (user user) { This. user =user; } PublicLong getId () {returnID; } Public voidsetId (Long id) { This. ID =ID; } PublicString Getrolename () {returnRoleName; } Public voidsetrolename (String roleName) { This. RoleName =RoleName; }}
Be aware that Mappedby = "user" in the user class is the name of the user object held in role. @JoinColumn in Role (name = "user_id") is the name of the field that specifies the user identifier in the role table. Cascade = {Cascadetype.all} is used to set cascade operations, where all cascade operations are enabled. Fetch = Fetchtype.eager is used to set the load type. The default is lazy loading, if it is lazy loading, it means that the user's roles when you query out the user is not queried at the same time, but to access the user in the roles object is loaded. What I set up here is to load the roles when I query the user.
Second, the individual feels a little better, and the user and role do not hold each other's references, but generate intermediate tables:
User:
Import Javax.persistence.*;import Javax.validation.constraints.notnull;import Java.util.hashset;import java.util.set;/** * Created by Zhangpeng on 16-6-15. */@Entity @table (name = "Users") public class User {@Id @GeneratedValue (strategy = generationtype.auto) Private lo NG ID; The user email @NotNull private String email; The user name @NotNull private String name; private string password;//private string role; @OneToMany (cascade = {Cascadetype.all}, Fetch = Fetchtype.eager) Private set<role> roles = new hashset<> () ;//Public String Getrole () {//return role;//}////public void Setrole (String role) {//This.role = role;//} public set<role> GetRoles () {return roles; } public void Setroles (set<role> roles) {this.roles = roles; Public user () {} public user (long id) {this.id = ID; } public Long GetId () {return id; } public void SETID (Long id) {this.id = ID; } public String Getemail () {return email; } public void Setemail (String email) {this.email = email; } public String GetName () {return name; } public void SetName (String name) {this.name = name; } public String GetPassword () {return password; } public void SetPassword (String password) {this.password = password; }}
Role:
Import javax.persistence.*;/** * Created by Zhangpeng on 16-6-17. */@Entity @table (name = "Roles") public class Role { @Id @GeneratedValue (strategy = Generationtype.auto) Long ID; String rolename;// @ManyToOne// @JoinColumn (name = "user_id")// user user;//public user GetUser () {/ / return user;// }////public void SetUser (user user) {// This.user = user;// } Public Long getId () { return ID; } public void SetId (Long id) { this.id = ID; } Public String Getrolename () { return roleName; } public void Setrolename (String roleName) { this.rolename = RoleName; }}
That's all you can do.
Test:
Import Com.guduo.fenghui.dao.roledao;import Com.guduo.fenghui.dao.userdao;import com.guduo.fenghui.entity.Role; Import Com.guduo.fenghui.entity.user;import org.junit.assert;import Org.junit.test;import Org.junit.runner.RunWith ; Import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.boot.test.springapplicationconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import Org.springframework.test.context.web.WebAppConfiguration, @RunWith (Springjunit4classrunner.class) @ Springapplicationconfiguration (classes = application.class) @WebAppConfigurationpublic class Test {@Autowired Userda o Userdao; @Autowired Roledao Roledao; @Test public void Test () {User user = new User (); User.setemail ("[email protected]"); User.setname ("Zhangpeng"); User.setpassword ("123456"); for (int i = 0; I <= 2; i++) {Role role = new role (); Role.setrolename (i + "J");// Roledao.save (role);//Role.setuser (user); User.getroles (). Add (role); } userdao.save (user); user = Userdao.findbyname ("Zhangpeng"); Assert.assertequals (User.getroles (). Size (), 3); User.getroles (). Get (0). Setrolename ("ASDASD"); Userdao.save (user); user = Userdao.findbyname ("Zhangpeng"); Assert.assertequals ("ASDASD", User.getroles (). Get (0). Getrolename ()); Userdao.delete (User.getid ()); }}
In this section of the test code, cascading insertions, cascading queries, cascading updates, cascade deletions are embodied.
Two examples of JPA (Hibernate) @OneToMany