關於JPA一對一,一對多(多對一),多對多的詳解


一、@OneToOne關系映射

JPA使用@OneToOne來標注一對一的關系。

實體 People :用戶。

實體 Address:家庭住址。

People 和 Address 是一對一的關系。

這里用兩種方式描述JPA的一對一關系。

一種是通過外鍵的方式(一個實體通過外鍵關聯到另一個實體的主鍵);

另外一種是通過一張關聯表來保存兩個實體一對一的關系。

 

1、通過外鍵的方式

people 表(id,name,sex,birthday,address_id)

address 表(id,phone,zipcode,address)

 

People.java

 
  1. @Entity
  2. public class People {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  5.     @Column(name = "id", nullable = false)
  6.     private Long id;//id
  7.     @Column(name = "name", nullable = true, length = 20)
  8.     private String name;//姓名
  9.     @Column(name = "sex", nullable = true, length = 1)
  10.     private String sex;//性別
  11.     @Column(name = "birthday", nullable = true)
  12.     private Timestamp birthday;//出生日期
  13.     @OneToOne(cascade=CascadeType.ALL)//People是關系的維護端,當刪除 people,會級聯刪除 address
  14.     @JoinColumn(name = "address_id", referencedColumnName = "id")//people中的address_id字段參考address表中的id字段
  15.     private Address address;//地址
  16. }

關聯的實體的主鍵一般是用來做外鍵的。但如果此時不想主鍵作為外鍵,則需要設置referencedColumnName屬性。當然這里關聯實體(Address)的主鍵 id 是用來做主鍵,所以這里第20行的 referencedColumnName = "id" 實際可以省略。

 

 

Address.java

 
  1. @Entity
  2. public class Address {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  5.     @Column(name = "id", nullable = false)
  6.     private Long id;//id
  7.     @Column(name = "phone", nullable = true, length = 11)
  8.     private String phone;//手機
  9.     @Column(name = "zipcode", nullable = true, length = 6)
  10.     private String zipcode;//郵政編碼
  11.     @Column(name = "address", nullable = true, length = 100)
  12.     private String address;//地址
  13.     //如果不需要根據Address級聯查詢People,可以注釋掉
  14. //    @OneToOne(mappedBy = "address", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
  15. //    private People people;
  16. }

 

2、通過關聯表的方式來保存一對一的關系。

people 表(id,name,sex,birthday)

address 表 (id,phone,zipcode,address)

people_address (people_id,address_id)

只需要創建 People 和 Address 兩個實體

 

People.java

 
  1. @Entity
  2. public class People {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  5.     @Column(name = "id", nullable = false)
  6.     private Long id;//id
  7.     @Column(name = "name", nullable = true, length = 20)
  8.     private String name;//姓名
  9.     @Column(name = "sex", nullable = true, length = 1)
  10.     private String sex;//性別
  11.     @Column(name = "birthday", nullable = true)
  12.     private Timestamp birthday;//出生日期
  13.     @OneToOne(cascade=CascadeType.ALL)//People是關系的維護端
  14.     @JoinTable(name = "people_address",
  15.             joinColumns = @JoinColumn(name="people_id"),
  16.             inverseJoinColumns = @JoinColumn(name = "address_id"))//通過關聯表保存一對一的關系
  17.     private Address address;//地址
  18. }

 

Address.java

不變

 

二、@OneToMany 和 @ManyToOne

實體 Author:作者。

實體 Article:文章。

Author 和 Article 是一對多關系(雙向)。那么在JPA中,如何表示一對多的雙向關聯呢?

JPA使用@OneToMany和@ManyToOne來標識一對多的雙向關聯。一端(Author)使用@OneToMany,多端(Article)使用@ManyToOne。

JPA規范中,一對多的雙向關系由多端(Article)來維護。就是說多端(Article)為關系維護端,負責關系的增刪改查。一端(Author)則為關系被維護端,不能維護關系。

一端(Author)使用@OneToMany注釋的mappedBy="author"屬性表明Author是關系被維護端。

多端(Article)使用@ManyToOne和@JoinColumn來注釋屬性 author,@ManyToOne表明Article是多端,@JoinColumn設置在article表中的關聯字段(外鍵)。

 

Author.java

 
  1. @Entity
  2. public class Author {
  3.     @Id // 主鍵
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增長策略
  5.     private Long id; //id
  6.     @NotEmpty(message = "姓名不能為空")
  7.     @Size(min=2, max=20)
  8.     @Column(nullable = false, length = 20)
  9.     private String name;//姓名
  10.     @OneToMany(mappedBy = "author",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
  11.     //級聯保存、更新、刪除、刷新;延遲加載。當刪除用戶,會級聯刪除該用戶的所有文章
  12.     //擁有mappedBy注解的實體類為關系被維護端
  13.      //mappedBy="author"中的author是Article中的author屬性
  14.     private List<Article> articleList;//文章列表
  15. }

 

Article.java

 
  1. @Entity
  2. public class Article {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增長策略
  5.     @Column(name = "id", nullable = false)
  6.     private Long id;
  7.     @NotEmpty(message = "標題不能為空")
  8.     @Size(min = 2, max = 50)
  9.     @Column(nullable = false, length = 50) // 映射為字段,值不能為空
  10.     private String title;
  11.     @Lob  // 大對象,映射 MySQL 的 Long Text 類型
  12.     @Basic(fetch = FetchType.LAZY) // 懶加載
  13.     @NotEmpty(message = "內容不能為空")
  14.     @Size(min = 2)
  15.     @Column(nullable = false) // 映射為字段,值不能為空
  16.     private String content;//文章全文內容
  17.     @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=false)//可選屬性optional=false,表示author不能為空。刪除文章,不影響用戶
  18.     @JoinColumn(name="author_id")//設置在article表中的關聯字段(外鍵)
  19.     private Author author;//所屬作者
  20. }

 

最終生成的表結構

article 表(id,title,conten,author_id)

author 表(id,name)

 

三、多對多 @ManyToMany

實體 User:用戶。

實體 Authority:權限。

用戶和權限是多對多的關系。一個用戶可以有多個權限,一個權限也可以被很多用戶擁有。

JPA中使用@ManyToMany來注解多對多的關系,由一個關聯表來維護。這個關聯表的表名默認是:主表名+下划線+從表名。(主表是指關系維護端對應的表,從表指關系被維護端對應的表)。這個關聯表只有兩個外鍵字段,分別指向主表ID和從表ID。字段的名稱默認為:主表名+下划線+主表中的主鍵列名,從表名+下划線+從表中的主鍵列名。

 

需要注意的:

1、多對多關系中一般不設置級聯保存、級聯刪除、級聯更新等操作。

2、可以隨意指定一方為關系維護端,在這個例子中,我指定 User 為關系維護端,所以生成的關聯表名稱為: user_authority,關聯表的字段為:user_id 和 authority_id。

3、多對多關系的綁定由關系維護端來完成,即由 User.setAuthorities(authorities) 來綁定多對多的關系。關系被維護端不能綁定關系,即Game不能綁定關系。

4、多對多關系的解除由關系維護端來完成,即由Player.getGames().remove(game)來解除多對多的關系。關系被維護端不能解除關系,即Game不能解除關系。

5、如果 User 和 Authority 已經綁定了多對多的關系,那么不能直接刪除 Authority,需要由 User 解除關系后,才能刪除 Authority。但是可以直接刪除 User,因為 User 是關系維護端,刪除 User 時,會先解除 User 和 Authority 的關系,再刪除 Authority。

 

User.java

 
  1. @Entity
  2. public class User {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  5.     private Long id;
  6.     @NotEmpty(message = "賬號不能為空")
  7.     @Size(min=3, max=20)
  8.     @Column(nullable = false, length = 20, unique = true)
  9.     private String username; // 用戶賬號,用戶登錄時的唯一標識
  10.     @NotEmpty(message = "密碼不能為空")
  11.     @Size(max=100)
  12.     @Column(length = 100)
  13.     private String password; // 登錄時密碼
  14.     @ManyToMany
  15.     @JoinTable(name = "user_authority",joinColumns = @JoinColumn(name = "user_id"),
  16.     inverseJoinColumns = @JoinColumn(name = "authority_id"))
  17.     //1、關系維護端,負責多對多關系的綁定和解除
  18.     //2、@JoinTable注解的name屬性指定關聯表的名字,joinColumns指定外鍵的名字,關聯到關系維護端(User)
  19.     //3、inverseJoinColumns指定外鍵的名字,要關聯的關系被維護端(Authority)
  20.     //4、其實可以不使用@JoinTable注解,默認生成的關聯表名稱為主表表名+下划線+從表表名,
  21.     //即表名為user_authority
  22.     //關聯到主表的外鍵名:主表名+下划線+主表中的主鍵列名,即user_id
  23.     //關聯到從表的外鍵名:主表中用於關聯的屬性名+下划線+從表的主鍵列名,即authority_id
  24.     //主表就是關系維護端對應的表,從表就是關系被維護端對應的表
  25.     private List<Authority> authorityList;
  26. }

注意:如注釋中所言,上面的第20-21行的@JoinTable可以省略,默認可以生成

 

Authority.java

 
  1. @Entity
  2. public class Authority {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  5.     private Integer id;
  6.     @Column(nullable = false)
  7.     private String name; //權限名
  8.     @ManyToMany(mappedBy = "authorityList")
  9.     private List<User> userList;
  10. }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM