JPA-to-many, many-to-use

A, @ OneToOne relational mapping

JPA use @OneToOne to mark the one to one relationship.

Entity People: users.

Entity Address: home address.

People and Address is one to one relationship.

Here are described two ways JPA -one relationships.

One is through the foreign key (primary key of an entity associated with another entity through a foreign key);

Another is to hold one to one relationship between the two entities through an association table.

 

1, by way of a foreign key

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.     String name Private; // Name
  9.     @Column(name = "sex", nullable = true, length = 1)
  10.     String Sex Private; // Sex
  11.     @Column(name = "birthday", nullable = true)
  12.     Timestamp Birthday Private; // Date of Birth
  13.     @OneToOne (Cascade = CascadeType.ALL) // People are maintenance side of the relationship, when deleting people, will cascade delete address
  14.     @JoinColumn (name =  "address_id", the referencedColumnName =  "id") // people in address_id address field in the reference table id field
  15.     Address address Private; // address
  16. }

Entity's primary key is generally used for the associated foreign key. At this time, if the primary key as a foreign key do not want, you need to set referencedColumnName properties. Of course, here associated entity (Address) primary key id is used as a primary key, so referencedColumnName = where the first row 20 is  "id" may actually be omitted.

 

 

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.     String Phone Private; // phone
  9.     @Column(name = "zipcode", nullable = true, length = 6)
  10.     String zipcode Private; // zip code
  11.     @Column(name = "address", nullable = true, length = 100)
  12.     String address Private; // address
  13.     // If you do not inquire People According Address cascade, can comment
  14. //    @OneToOne(mappedBy = "address", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
  15. //    private People people;
  16. }

 

2, to hold one to one relationship through the associated table.

people 表(id,name,sex,birthday)

address 表 (id,phone,zipcode,address)

people_address (people_id,address_id)

People only need to create two entities and 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.     String name Private; // Name
  9.     @Column(name = "sex", nullable = true, length = 1)
  10.     String Sex Private; // Sex
  11.     @Column(name = "birthday", nullable = true)
  12.     Timestamp Birthday Private; // Date of Birth
  13.     @OneToOne (Cascade = CascadeType.ALL) // People are maintenance side of the relationship
  14.     @JoinTable(name = "people_address",
  15.             joinColumns = @JoinColumn(name="people_id"),
  16.             = inverseJoinColumns  @JoinColumn (name =  "address_id")) // save the relationship by one to one association table
  17.     Address address Private; // address
  18. }

 

Address.java

constant

 

Two, @ OneToMany and @ManyToOne

Entity Author: Author.

Entities Article: article.

Author and Article are many relationship (two-way). Then the JPA , the bidirectional association represents how many do?

JPA use @OneToMany and @ManyToOne to identify many of the bidirectional association. One end (the Author) using @OneToMany, multiterminal (Article This article was) used @ManyToOne.

In the JPA specification, two-way-to-many relationship is maintained by many-fold (Article). That is many-fold (Article) for the maintenance of the relationship end, responsible for relations CRUD. One end (the Author) was end relationship is maintained, the relationship can not be maintained.

One end (Author) @OneToMany annotated using mappedBy = "author" attribute indicates that the relationship is maintained Author end.

Multiport (Article) @JoinColumn and annotated using @ManyToOne properties author, @ ManyToOne Article show a multiport, @ JoinColumn set associated field (foreign key) in the article table.

 

Author.java

 
  1. @Entity
  2. public class Author {
  3.     @Id  // primary key
  4.     @GeneratedValue (at Strategy = GenerationType.IDENTITY)  // self-growth strategy
  5.     private Long id; //id
  6.     The @NotEmpty (the Message =  "Name can not be empty")
  7.     @Size(min=2, max=20)
  8.     @Column(nullable = false, length = 20)
  9.     String name Private; // Name
  10.     @OneToMany(mappedBy = "author",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
  11.     // cascading save, update, delete, refresh; lazy loading. When you delete a user, that user will cascade delete all articles
  12.     Annotated entity classes // mappedBy have to end the relationship is maintained
  13.      // mappedBy = "author" in author is author of properties Article
  14.     List Private <Article This article was> articleList; // list of articles
  15. }

 

Article.java

 
  1. @Entity
  2. public class Article {
  3.     @Id
  4.     @GeneratedValue (at Strategy = GenerationType.IDENTITY)  // self-growth strategy
  5.     @Column(name = "id", nullable = false)
  6.     private Long id;
  7.     The @NotEmpty (the Message =  "Title can not be empty")
  8.     @Size(min = 2, max = 50)
  9.     The @Column (= Nullable  to false, length =  50)  // mapped to fields, values can not be empty
  10.     private String title;
  11.     @Lob   // large objects, mapping MySQL types of Long Text
  12.     The @basic (FETCH = FetchType.LAZY)  // lazy loading
  13.     The @NotEmpty (the Message =  "can not be empty")
  14.     @Size(min = 2)
  15.     The @Column (= Nullable  to false)  // mapped to fields, values can not be empty
  16.     String Content Private; // text of the article content
  17.     The @ManyToOne (Cascade CascadeType.MERGE = {,} CascadeType.REFRESH, = optional to false) // optional attribute optional = false, indicates author can not be empty. Delete posts, without affecting the user
  18.     @JoinColumn (name = "the author_id") // article table provided in the associated field (foreign key)
  19.     Author author Private; // belongs author
  20. }

 

Finally generated table structure

article 表(id,title,conten,author_id)

author 表(id,name)

 

Third, many-@ManyToMany

Entity User: the user.

Entity Authority: authority.

Users and permissions are many relationship. A user can have multiple permissions, permission may also have a lot of users.

JPA is used to annotate @ManyToMany many relationship, maintained by an association table. The association table table name default: the main table name + underscore + from the table name. (Primary table refers to the relationship table corresponding to the end of the maintenance, from the table refers to the relationship table corresponding to the end of maintenance). This association table has only two foreign key field, pointing to the main table and the ID table ID. Name field defaults to: the main table name + underscore + primary key column names in the primary table, from the table name + underscore + from the primary key column names in the table.

 

It should be noted:

1, generally do not set many relationships cascading save, delete cascade, cascading updates and other operations.

2, you can specify one of the casual relationship maintenance for the end, in this example, I specify User to maintain relationships end, so as to generate the association table name: field user_authority, the associated table is: user_id and authority_id.

3, by binding many relationship relationship maintenance terminal to complete, i.e., to bind many relationship by User.setAuthorities (authorities). Relationship can not be maintained end binding relationship that Game is not binding relationship.

4, released by the many relationships end relationship maintenance is done, i.e. to release many relationship by Player.getGames (). Remove (game). Relationships are maintained end can not lift the relationship, that relationship can not be lifted Game.

5, and if the User Authority has been bound-many relationship, you can not delete Authority, the need to lift the relationship between the User, you can delete Authority. User can delete it directly, because the User is the relationship between the maintenance end, when you delete User, User will first lift the relationship and the Authority, and then delete Authority.

 

User.java

 
  1. @Entity
  2. public class User {
  3.     @Id
  4.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  5.     private Long id;
  6.     The @NotEmpty (the Message =  "account can not be blank")
  7.     @Size(min=3, max=20)
  8.     @Column(nullable = false, length = 20, unique = true)
  9.     String username Private;  // user account that uniquely identifies when the user logs on
  10.     The @NotEmpty (the Message =  "password can not be blank")
  11.     @Size(max=100)
  12.     @Column(length = 100)
  13.     private String password;  // When Password
  14.     @ManyToMany
  15.     @JoinTable(name = "user_authority",joinColumns = @JoinColumn(name = "user_id"),
  16.     inverseJoinColumns = @JoinColumn(name = "authority_id"))
  17.     // 1, relationship maintenance end, many relationships and is responsible for binding to lift
  18.     // 2, @ JoinTable annotation name attribute specifies the name of the associated table, joinColumns specify the name of the foreign key, related to relationship maintenance terminal (User)
  19.     // 3, inverseJoinColumns specify the name of the foreign key relationships are maintained to be associated end (Authority)
  20.     // 4, in fact, can not use @JoinTable annotation, the default name generated based association table name + underscore + exemplar exemplar from the name,
  21.     // table that is named user_authority
  22.     // associated foreign key to the main table name: the name of the primary table underlined + + primary table primary key column names, i.e. user_id
  23.     // linked to the foreign key table name: the name of the attribute for the associated primary table from + + underlined primary key column name of the table, i.e. authority_id
  24.     // end of main table is maintained corresponding to the relationship table, the relationship is maintained from the end of the table corresponding to the table
  25.     private List<Authority> authorityList;
  26. }

Note: As stated in the comment, lines 20-21 @JoinTable above may be omitted, the default may be generated

 

Authority.java

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

 

Add test

 
  1. @SpringBootTest
  2. @RunWith(SpringRunner.class)
  3. public class UserRepositoryTest {
  4.     @Autowired
  5.     private UserRepository userRepository;
  6.     @Autowired
  7.     private AuthorityRepository authorityRepository;
  8.     @Test
  9.     public void saveAuthority() {
  10.         Authority authority = new Authority();
  11.         authority.setId(1);
  12.         authority.setName("ROLE_ADMIN");
  13.         authorityRepository.save(authority);
  14.     }
  15.     @Test
  16.     public void saveUser() {
  17.         User user = new User();
  18.         user.setUsername("admin");
  19.         user.setPassword("123456");
  20.         Authority authority = authorityRepository.findById(1).get();
  21.         List<Authority> authorityList = new ArrayList<>();
  22.         authorityList.add(authority);
  23.         user.setAuthorList(authorityList);
  24.         userRepository.save(user);
  25.     }
  26. }

Permission to run saveAuthority add a record,

Then add a user record saveUser run, at the same time, user_authority table automatically inserts a row

 

Delete test

delete users

 
  1. @SpringBootTest
  2. @RunWith(SpringRunner.class)
  3. public class UserRepositoryTest {
  4.     @Autowired
  5.     private UserRepository userRepository;
  6.     @Test
  7.     public void deleteUser() {
  8.         userRepository.deleteById(1L);
  9.     }
  10. }

user to delete a record in the table, while user_authority can cascade to delete a record

 

 

Reference: http: //www.cnblogs.com/luxh/archive/2012/05/30/2527123.html

 

 

Updated again

Which @OneToMany and @ManyToOne most used and would add here

 

About Cascade, we must note that in the end to maintain the relationship, that One end.

Such as author and article, the author is One, the article is the Many; articles and reviews, the article is One, comments are Many.

cascade = CascadeType.ALL One can only write in the end, only change Many One end of the end, are not allowed to alter Many One end side.

In particular deleted because ALL included in the update, delete.

If you delete a comment, just put the article deleted, and that the operator who. So, be careful when in use. One end must be used.

For example

One end

 

Spring Data JPA one-of-many, many-to-relational mapping

 

Many 端

Guess you like

Origin www.cnblogs.com/fengli9998/p/12023514.html