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
- @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)
- String name Private; // Name
- @Column(name = "sex", nullable = true, length = 1)
- String Sex Private; // Sex
- @Column(name = "birthday", nullable = true)
- Timestamp Birthday Private; // Date of Birth
- @OneToOne (Cascade = CascadeType.ALL) // People are maintenance side of the relationship, when deleting people, will cascade delete address
- @JoinColumn (name = "address_id", the referencedColumnName = "id") // people in address_id address field in the reference table id field
- Address address Private; // address
- }
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
- @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)
- String Phone Private; // phone
- @Column(name = "zipcode", nullable = true, length = 6)
- String zipcode Private; // zip code
- @Column(name = "address", nullable = true, length = 100)
- String address Private; // address
- // If you do not inquire People According Address cascade, can comment
- // @OneToOne(mappedBy = "address", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
- // private People people;
- }
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
- @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)
- String name Private; // Name
- @Column(name = "sex", nullable = true, length = 1)
- String Sex Private; // Sex
- @Column(name = "birthday", nullable = true)
- Timestamp Birthday Private; // Date of Birth
- @OneToOne (Cascade = CascadeType.ALL) // People are maintenance side of the relationship
- @JoinTable(name = "people_address",
- joinColumns = @JoinColumn(name="people_id"),
- = inverseJoinColumns @JoinColumn (name = "address_id")) // save the relationship by one to one association table
- Address address Private; // address
- }
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
- @Entity
- public class Author {
- @Id // primary key
- @GeneratedValue (at Strategy = GenerationType.IDENTITY) // self-growth strategy
- private Long id; //id
- The @NotEmpty (the Message = "Name can not be empty")
- @Size(min=2, max=20)
- @Column(nullable = false, length = 20)
- String name Private; // Name
- @OneToMany(mappedBy = "author",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
- // cascading save, update, delete, refresh; lazy loading. When you delete a user, that user will cascade delete all articles
- Annotated entity classes // mappedBy have to end the relationship is maintained
- // mappedBy = "author" in author is author of properties Article
- List Private <Article This article was> articleList; // list of articles
- }
Article.java
- @Entity
- public class Article {
- @Id
- @GeneratedValue (at Strategy = GenerationType.IDENTITY) // self-growth strategy
- @Column(name = "id", nullable = false)
- private Long id;
- The @NotEmpty (the Message = "Title can not be empty")
- @Size(min = 2, max = 50)
- The @Column (= Nullable to false, length = 50) // mapped to fields, values can not be empty
- private String title;
- @Lob // large objects, mapping MySQL types of Long Text
- The @basic (FETCH = FetchType.LAZY) // lazy loading
- The @NotEmpty (the Message = "can not be empty")
- @Size(min = 2)
- The @Column (= Nullable to false) // mapped to fields, values can not be empty
- String Content Private; // text of the article content
- 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
- @JoinColumn (name = "the author_id") // article table provided in the associated field (foreign key)
- Author author Private; // belongs author
- }
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
- @Entity
- public class User {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
- The @NotEmpty (the Message = "account can not be blank")
- @Size(min=3, max=20)
- @Column(nullable = false, length = 20, unique = true)
- String username Private; // user account that uniquely identifies when the user logs on
- The @NotEmpty (the Message = "password can not be blank")
- @Size(max=100)
- @Column(length = 100)
- private String password; // When Password
- @ManyToMany
- @JoinTable(name = "user_authority",joinColumns = @JoinColumn(name = "user_id"),
- inverseJoinColumns = @JoinColumn(name = "authority_id"))
- // 1, relationship maintenance end, many relationships and is responsible for binding to lift
- // 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)
- // 3, inverseJoinColumns specify the name of the foreign key relationships are maintained to be associated end (Authority)
- // 4, in fact, can not use @JoinTable annotation, the default name generated based association table name + underscore + exemplar exemplar from the name,
- // table that is named user_authority
- // 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
- // 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
- // 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
- private List<Authority> authorityList;
- }
Note: As stated in the comment, lines 20-21 @JoinTable above may be omitted, the default may be generated
Authority.java
- @Entity
- public class Authority {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- @Column(nullable = false)
- String name Private; // name rights
- @ManyToMany(mappedBy = "authorityList")
- private List<User> userList;
- }
Add test
- @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);
- }
- }
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
- @SpringBootTest
- @RunWith(SpringRunner.class)
- public class UserRepositoryTest {
- @Autowired
- private UserRepository userRepository;
- @Test
- public void deleteUser() {
- userRepository.deleteById(1L);
- }
- }
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
Many 端