欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳談jpa中表的@OneToMany等關(guān)聯(lián)關(guān)系

 更新時(shí)間:2021年12月06日 09:45:27   作者:xiaomisolo  
這篇文章主要介紹了詳談jpa中表的@OneToMany等關(guān)聯(lián)關(guān)系,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、@OneToOne關(guān)系映射

JPA使用@OneToOne來標(biāo)注一對一的關(guān)系。

  • 實(shí)體 People :用戶。
  • 實(shí)體 Address:家庭住址。

People 和 Address 是一對一的關(guān)系。

這里用兩種方式描述JPA的一對一關(guān)系。

一種是通過外鍵的方式(一個(gè)實(shí)體通過外鍵關(guān)聯(lián)到另一個(gè)實(shí)體的主鍵);

另外一種是通過一張關(guān)聯(lián)表來保存兩個(gè)實(shí)體一對一的關(guān)系。

1、通過外鍵的方式

  • people 表(id,name,sex,birthday,address_id
  • address 表(id,phone,zipcode,address)
People.java
 
@Entity
public class People {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;//id
 
    @Column(name = "name", nullable = true, length = 20)
    private String name;//姓名
 
    @Column(name = "sex", nullable = true, length = 1)
    private String sex;//性別
 
    @Column(name = "birthday", nullable = true)
    private Timestamp birthday;//出生日期
 
    @OneToOne(cascade=CascadeType.ALL)//People是關(guān)系的維護(hù)端,當(dāng)刪除 people,會級聯(lián)刪除 address
    @JoinColumn(name = "address_id", referencedColumnName = "id")//people中的address_id字段參考address表中的id字段
    private Address address;//地址 
}

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

Address.java
 
@Entity
public class Address {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;//id
 
    @Column(name = "phone", nullable = true, length = 11)
    private String phone;//手機(jī)
 
    @Column(name = "zipcode", nullable = true, length = 6)
    private String zipcode;//郵政編碼
 
    @Column(name = "address", nullable = true, length = 100)
    private String address;//地址
 
    //如果不需要根據(jù)Address級聯(lián)查詢People,可以注釋掉
//    @OneToOne(mappedBy = "address", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
//    private People people;
}

2、通過關(guān)聯(lián)表的方式來保存一對一的關(guān)系

  • people 表(id,name,sex,birthday)
  • address 表 (id,phone,zipcode,address)
  • people_address (people_idaddress_id)

只需要?jiǎng)?chuàng)建 People 和 Address 兩個(gè)實(shí)體

People.java
 
@Entity
public class People {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;//id
 
    @Column(name = "name", nullable = true, length = 20)
    private String name;//姓名
 
    @Column(name = "sex", nullable = true, length = 1)
    private String sex;//性別
 
    @Column(name = "birthday", nullable = true)
    private Timestamp birthday;//出生日期
 
    @OneToOne(cascade=CascadeType.ALL)//People是關(guān)系的維護(hù)端
    @JoinTable(name = "people_address",
            joinColumns = @JoinColumn(name="people_id"),
            inverseJoinColumns = @JoinColumn(name = "address_id"))//通過關(guān)聯(lián)表保存一對一的關(guān)系
    private Address address;//地址 
}

Address.java

不變

二、@OneToMany 和 @ManyToOne

  • 實(shí)體 Author:作者。
  • 實(shí)體 Article:文章。

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

JPA使用@OneToMany和@ManyToOne來標(biāo)識一對多的雙向關(guān)聯(lián)。一端(Author)使用@OneToMany,多端(Article)使用@ManyToOne。

在JPA規(guī)范中,一對多的雙向關(guān)系由多端(Article)來維護(hù)。就是說多端(Article)為關(guān)系維護(hù)端,負(fù)責(zé)關(guān)系的增刪改查。一端(Author)則為關(guān)系被維護(hù)端,不能維護(hù)關(guān)系。

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

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

Author.java
 
@Entity
public class Author { 
    @Id // 主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增長策略
    private Long id; //id
 
    @NotEmpty(message = "姓名不能為空")
    @Size(min=2, max=20)
    @Column(nullable = false, length = 20)
    private String name;//姓名
 
    @OneToMany(mappedBy = "author",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    //級聯(lián)保存、更新、刪除、刷新;延遲加載。當(dāng)刪除用戶,會級聯(lián)刪除該用戶的所有文章
    //擁有mappedBy注解的實(shí)體類為關(guān)系被維護(hù)端
     //mappedBy="author"中的author是Article中的author屬性
    private List<Article> articleList;//文章列表  
}
Article.java
 
@Entity
public class Article { 
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增長策略
    @Column(name = "id", nullable = false)
    private Long id;
 
    @NotEmpty(message = "標(biāo)題不能為空")
    @Size(min = 2, max = 50)
    @Column(nullable = false, length = 50) // 映射為字段,值不能為空
    private String title;
 
    @Lob  // 大對象,映射 MySQL 的 Long Text 類型
    @Basic(fetch = FetchType.LAZY) // 懶加載
    @NotEmpty(message = "內(nèi)容不能為空")
    @Size(min = 2)
    @Column(nullable = false) // 映射為字段,值不能為空
    private String content;//文章全文內(nèi)容 
 
    @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=false)//可選屬性optional=false,表示author不能為空。刪除文章,不影響用戶
    @JoinColumn(name="author_id")//設(shè)置在article表中的關(guān)聯(lián)字段(外鍵)
    private Author author;//所屬作者  
}

最終生成的表結(jié)構(gòu)

  • article 表(id,title,conten,author_id)
  • author 表(id,name)

三、多對多 @ManyToMany

  • 實(shí)體 User:用戶。
  • 實(shí)體 Authority:權(quán)限。

用戶和權(quán)限是多對多的關(guān)系。一個(gè)用戶可以有多個(gè)權(quán)限,一個(gè)權(quán)限也可以被很多用戶擁有。

JPA中使用@ManyToMany來注解多對多的關(guān)系,由一個(gè)關(guān)聯(lián)表來維護(hù)。這個(gè)關(guān)聯(lián)表的表名默認(rèn)是:主表名+下劃線+從表名。(主表是指關(guān)系維護(hù)端對應(yīng)的表,從表指關(guān)系被維護(hù)端對應(yīng)的表)。這個(gè)關(guān)聯(lián)表只有兩個(gè)外鍵字段,分別指向主表ID和從表ID。字段的名稱默認(rèn)為:主表名+下劃線+主表中的主鍵列名,從表名+下劃線+從表中的主鍵列名。

需要注意的:

1、多對多關(guān)系中一般不設(shè)置級聯(lián)保存、級聯(lián)刪除、級聯(lián)更新等操作。

2、可以隨意指定一方為關(guān)系維護(hù)端,在這個(gè)例子中,我指定 User 為關(guān)系維護(hù)端,所以生成的關(guān)聯(lián)表名稱為: user_authority,關(guān)聯(lián)表的字段為:user_id 和 authority_id。

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

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

5、如果 User 和 Authority 已經(jīng)綁定了多對多的關(guān)系,那么不能直接刪除 Authority,需要由 User 解除關(guān)系后,才能刪除 Authority。但是可以直接刪除 User,因?yàn)?User 是關(guān)系維護(hù)端,刪除 User 時(shí),會先解除 User 和 Authority 的關(guān)系,再刪除 Authority。

User.java
 
@Entity
public class User { 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
 
    @NotEmpty(message = "賬號不能為空")
    @Size(min=3, max=20)
    @Column(nullable = false, length = 20, unique = true)
    private String username; // 用戶賬號,用戶登錄時(shí)的唯一標(biāo)識
 
    @NotEmpty(message = "密碼不能為空")
    @Size(max=100)
    @Column(length = 100)
    private String password; // 登錄時(shí)密碼
 
    @ManyToMany
    @JoinTable(name = "user_authority",joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "authority_id"))
    //1、關(guān)系維護(hù)端,負(fù)責(zé)多對多關(guān)系的綁定和解除
    //2、@JoinTable注解的name屬性指定關(guān)聯(lián)表的名字,joinColumns指定外鍵的名字,關(guān)聯(lián)到關(guān)系維護(hù)端(User)
    //3、inverseJoinColumns指定外鍵的名字,要關(guān)聯(lián)的關(guān)系被維護(hù)端(Authority)
    //4、其實(shí)可以不使用@JoinTable注解,默認(rèn)生成的關(guān)聯(lián)表名稱為主表表名+下劃線+從表表名,
    //即表名為user_authority
    //關(guān)聯(lián)到主表的外鍵名:主表名+下劃線+主表中的主鍵列名,即user_id
    //關(guān)聯(lián)到從表的外鍵名:主表中用于關(guān)聯(lián)的屬性名+下劃線+從表的主鍵列名,即authority_id
    //主表就是關(guān)系維護(hù)端對應(yīng)的表,從表就是關(guān)系被維護(hù)端對應(yīng)的表
    private List<Authority> authorityList; 
}

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

Authority.java
 
@Entity
public class Authority {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
 
    @Column(nullable = false)
    private String name; //權(quán)限名
 
    @ManyToMany(mappedBy = "authorityList")
    private List<User> userList;
 
}

測試 添加

 
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest { 
 
    @Autowired
    private UserRepository userRepository;
 
    @Autowired
    private AuthorityRepository authorityRepository;
 
    @Test
    public void saveAuthority() {
        Authority authority = new Authority();
        authority.setId(1);
        authority.setName("ROLE_ADMIN");
        authorityRepository.save(authority);
    }
 
    @Test
    public void saveUser() {
        User user = new User();
        user.setUsername("admin");
        user.setPassword("123456");
        Authority authority = authorityRepository.findById(1).get();
        List<Authority> authorityList = new ArrayList<>();
        authorityList.add(authority);
        user.setAuthorList(authorityList);
        userRepository.save(user);
    } 
}

先運(yùn)行 saveAuthority 添加一條權(quán)限記錄,

然后運(yùn)行 saveUser 添加一條用戶記錄,與此同時(shí),user_authority 表中也自動(dòng)插入了一條記錄

測試 刪除刪除用戶

 
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest { 
 
    @Autowired
    private UserRepository userRepository;
 
    @Test
    public void deleteUser() {
        userRepository.deleteById(1L);
    } 
}

user 表中刪除一條記錄,同時(shí) user_authority 能夠級聯(lián)刪除一條記錄

再次更新

其中 @OneToMany 和 @ManyToOne 用得最多,這里再補(bǔ)充一下

關(guān)于級聯(lián),一定要注意,要在關(guān)系的維護(hù)端,即 One 端。

比如 作者和文章,作者是One,文章是Many;文章和評論,文章是One,評論是Many。

cascade = CascadeType.ALL 只能寫在 One 端,只有One端改變Many端,不準(zhǔn)Many端改變One端。

特別是刪除,因?yàn)?ALL 里包括更新,刪除。

如果刪除一條評論,就把文章刪了,那算誰的。所以,在使用的時(shí)候要小心。一定要在 One 端使用。

舉例

One 端

Spring Data JPA 之 一對一,一對多,多對多 關(guān)系映射

Many 端

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論