Spring entry --- JPA learning notes, --- jpa learning notes
Spring, which has been used for a period of time, is now only in a usable state and does not know much about anything deeper. So I decided to start learning Spring in depth.
This document mainly records JPA learning. Before learning JPA, you need to understand some ORM concepts.
ORM concept:
Object/Relation Mapping (ORM) is a technology designed to solve the mismatch between object-oriented and relational data (paradigm mismatch ). In short, ORM uses metadata describing the ing between objects and databases to automatically persist objects in the program to the database. In essence, data is converted from one form to another. (Personal considerations: but it seems like there is additional overhead compared with the general method? To be resolved)
Paradigm mismatch:
ORM features:
The general ORM framework includes the following four functions:
Ing occurrence:
Object-link ing generally occurs in the following situations:
The above are some concepts of JPA. Next we will discuss JPA.
JPA functions:
JPA (Java persistence API) is mainly used to process persistent operations in Java. Standardize ORM features and functions. APIS for ing object models to relational models, performing CRUD operations on objects, an object query language, and standard APIs for retrieving data through object graphs are defined respectively.
JPA benefits :??? They are not easy to use and cannot be compared. Use it for a while before commenting
Using JPA:
Define object:
Object definition: an object corresponds to a record with a primary key on the Database End, so this object is called an object.
The following code defines the simplest object class:
Import javax. persistence. entity; import javax. persistence. generatedValue; import javax. persistence. id; import javax. persistence. table;/***** <p> ClassName: User. java <p> * <p> user Entity class <p> * @ author linzj * @ createTime March 17, 2016 1:08:35 */@ Entity @ Table (name = "user ") public class User {@ Id @ GeneratedValue private Long id ;}
JPA provides java annotations for ing. You can find that these annotations are all in the javax. persistence package. The @ Entity annotation above defines the User class as the persistence type and has a corresponding table. @ Table annotation specifies the Table name. If not specified, the class name is used by default.
@ Id indicates the primary key attribute. If the primary key Column name does not match the attribute name, you can use @ Column to specify the corresponding primary key Column name. For example, adding @ Column (name = "uid") corresponds to the uid list. The application is not responsible for generating primary key values, but is allocated by the JPA vendor (such as Hibernate) during New Record insertion ). The @ GenerateValue annotation tells JPA that the application will not be responsible for allocating primary key values, but will be handled by the JPA supplier.
Property ing to column:
For more intuitive understanding. I first created a User table:
mysql> create table user( -> id int(5) not null primary key auto_increment, -> username varchar(60) not null, -> passwd varchar(60) not null);Query OK, 0 rows affected (0.14 sec)mysql> describe user;+----------+-------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+----------+-------------+------+-----+---------+----------------+| id | int(5) | NO | PRI | NULL | auto_increment || username | varchar(60) | NO | | NULL | || passwd | varchar(60) | NO | | NULL | |+----------+-------------+------+-----+---------+----------------+
Next, we can add the corresponding attributes to the User object class and map the attributes to the corresponding columns in the above user table:
/***** <P> ClassName: User. java <p> * <p> user Entity class <p> * @ author linzj * @ createTime March 17, 2016 1:08:35 */@ Entity @ Table (name = "user ") public class User {@ Id @ GeneratedValue private Long id; private String username; @ Column (name = "passwd") private String password; @ Transient private String others ;}
Because the table does not have the password field, we must specify the ing column name, that is, specifying the password ing to passwd. We also found that the object class has an attribute others that is not in the table. Note that this others attribute has been annotated as @ Transient. Therefore, the others attribute will be ignored by JPA and will not be mapped.
Create association between objects:
Database Association types include:
- One-to-one (1:1)
- Multiple-to-one (M: 1)
- One-to-many (1: M)
- Many-to-many (M: M)
One-to-one association:
/***** <P> ClassName: User. java <p> * user entity class, which identifies one-to-one association using the @ OneToOne annotation, * @ JoinColumn the annotation adds that the User and Adress objects specify the * foreign key relationship between tables. The column in the user Table references the address Table * <p> * @ author linzj * @ createTime March 17, 2016 1:08:35 */@ Entity @ Table (name = "user ") public class User {@ Id @ GeneratedValue private Long id; private String username; @ Column (name = "passwd") private String password; @ OneToOne @ JoinColumn (name = "adress_id ") // Add the foreign key private Adress adress;}/***** <p> ClassName: Adress. java <p> * <p> address entity class <p> * @ author linzj * @ createTime March 17, 2016 1:52:30 */@ Entitypublic class Adress {//... pass}
Many-to-one:
/***** <P> ClassName: Employe. java <p> * indicates the employee entity class, which uses the @ ManyToOne annotation and @ JoinColumn to specify the foreign key relationship between the two tables, * optional = false: The Association is required by Employe. That is, Employe cannot exist independently. * <P> * @ author linzj * @ createTime March 17, 2016 1:55:11 */@ Entitypublic class Employe {//... pass @ ManyToOne (optional = false) @ JoinColumn (name = "company_id") private Company;} @ Entitypublic class company {//... pass}
Many-to-one:
/***** <P> ClassName: Student. java <p> * Student Entity class, @ onetoworkflow annotation creates a one-to-many relationship between students and books, * specifies the foreign key with @ JoinColumn, the difference is that this foreign key Column exists in the Book object. * <P> * @ author linzj * @ createTime March 17, 2016 2:01:23 */@ Entitypublic class Student {//... pass @ onetovel @ JoinColumn (name = "student_id") private Set <Book> books = new HashSet <Book> () ;}@ Entitypublic class Book {//... pass}
Many to many:
/***** <P> ClassName: Product. java <p> * product entity class, @ ManyToMany creates many-to-many associations. * Note that @ JoinTable is used instead of @ JoinColumn, * Because multiple instances on one side can be associated with multiple instances on the other side. Therefore, the associated data pointing to another table cannot be saved in another column. * An associated table must be provided here, which contains the primary key column reference of each table. * In this example, the joined table is product_catalog, joinColumns and inverseJoinColumns specify the column names in the * product_catalog table, joinColumns specifies the reference of the primary key of the Product table, and inverseJoinColumns * specifies the reference of the primary. * <P> * @ author linzj * @ createTime March 17, 2016 2:07:47 */@ Entitypublic class Product {@ Id @ GeneratedValue private Long id; @ ManyToMany (cascade = CascadeType. ALL) @ JoinTable (name = "product_catalog", joinColumns = @ JoinColumn (name = "product_id"), inverseJoinColumns = @ JoinColumn (name = "catalog_id ")) private Set <Catalog> catalog = new HashSet <Catalog> (); public Long getId () {return id;} public void setId (Long id) {this. id = id;} public Set <Catalog> getCatalog () {return catalog;} public void setCatalog (Set <Catalog> catalog) {this. catalog = catalog ;}@ Entitypublic class Catalog {@ Id @ GeneratedValue private Long id;}/** corresponding table: mysql> describe product_catalog; + ------------ + ------ + ----- + --------- + ------- + | Field | Type | Null | Key | Default | Extra | + ------------ + ---------- + ------ + ----- + --------- + ------- + | product_id | bigint (20) | NO | PRI | NULL | catalog_id | bigint (20) | NO | PRI | NULL | + ------------ + ------ + ----- + --------- + ------- + 2 rows in set (0.01 sec) mysql> select * from product_catalog; + ------------ + | product_id | catalog_id | + ------------ + | 1 | 1 | 1 | 2 | + ------------ + ---------- + 2 rows in set (0.00 sec) mysql> select * from product; + ---- + | id | + ---- + | 1 | + ---- + 1 row in set (0.00 sec) mysql> select * from catalog; + ---- + | id | + ---- + | 1 | 2 | + ---- + */
Association direction:
There are only two kinds of correlations: unidirectional and bidirectional.
In one-way Association, you can only associate the source object with the target object. Two-way association can be performed from the associated source object to the target object, or from the target object to the source object.
In the following code, we only modify the above Adress object class to form a bidirectional Association. In the Adress entity class code, we added @ OneToOne (mappedBy = "adress") and added the mappedBy attribute. Through this attribute, JPA can recognize this attribute, to manage the associations between two entities. One side of the mappedBy attribute can be viewed as a mirror or read-only. It does not affect the data in the database. The code below demonstrates that after the following object classes are used for persistence operations, the Adress table of the database does not have a column of user fields.
@ Entity @ Table (name = "user") public class User {@ Id @ GeneratedValue private Long id; private String username; @ Column (name = "passwd") private String password; @ OneToOne @ JoinColumn (name = "adress_id") // Add a foreign key private Adress adress; public Long getId () {return id;} public void setId (Long id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public Adress getAdress () {return adress;} public void setAdress (Adress adress) {this. adress = adress; }}@ Entitypublic class Adress {@ Id @ GeneratedValue private Long id; @ OneToOne (mappedBy = "adress") private User user; public Long getId () {return id;} public void setId (Long id) {this. id = id;} public User getUser () {return user;} public void setUser (User user) {this. user = user ;}}
Put the above Code on my GITHUB
We also provide some blogs about JPA:
Http://www.cnblogs.com/holbrook/archive/2012/12/30/2839842.html
Http://www.cnblogs.com/chenying99/p/3143516.html
The above is my learning of JPA. The next article describes how to configure and use JPA.