Using JPA + SpringData to operate databases is as simple as that, jpaspringdata

Source: Internet
Author: User

Using JPA + SpringData to operate databases is as simple as that, jpaspringdata
Original podcast. If you need to reprint it, please indicate the source. Original address: http://www.cnblogs.com/crawl/p/7704914.html -----------------------------------------------------------------------------------------------------------------------------------------------------------

A large number of code examples are provided in the notes. It should be noted that most of the code examples are the code I typed and tested. If you have any shortcomings, please correct me ~

All the comments in this blog only represent the opinions of the bloggers themselves, if you have doubts or need to share the information tools in this series, please contact qingqing_crawl@163.com

Certificate -----------------------------------------------------------------------------------------------------------------------------------------------------------

This article introduces common APIs of JPA and mappings in JPA. In the previous article, we talked about the close relationship between JPA and Hibernate, especially the API and ing relationships. For details, refer to LZ's blog Hibernate Study Notes-1 and Hibernate Study Notes-2, similar to Hibernate, LZ also points out.

4. JPA APIs

1.Persistence: UsedGet the instance of EntiryManagerFactory

1) Common method: Persistence.CreateEntityManagerFactory (persistenceUnitName)Method

1 String persistenceUnitName = "jpa-1";        2 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);

2.EntiryManagerFactory: Common Methods

1)Get EntiryManager

1 // create EntityManager, similar to SessionFactory2 EntityManager entityManager = entityManagerFactory. createEntityManager () of Hibernate ();

2) close () method, close itself, this method is not demonstrated

3.EntityManagerCommon APIs

1)Find () methodSimilar to the get () method of the Session in Hibernate,The SQL statement is sent when the find method is executed.

1 // similar to the get method of the Session in Hibernate 2 @ Test3 public void testFind () {4 Customer customer = entityManager. find (Customer. class, 1); 5 6 System. out. println ("--------------------------------------"); 7 8 System. out. println (customer); 9}

The result is displayed as follows: view the position of the horizontal line to prove the conclusion.

 1 Hibernate:  2     select 3         customer0_.id as id1_2_0_, 4         customer0_.age as age2_2_0_, 5         customer0_.birth as birth3_2_0_, 6         customer0_.createTime as createTi4_2_0_, 7         customer0_.email as email5_2_0_, 8         customer0_.LAST_NAME as LAST_NAM6_2_0_  9     from10         JPA_CUSTOMER customer0_ 11     where12         customer0_.id=?13 ----------------------------------------14 Customer [id=1, lastName=AA, email=aa@163.com, age=21, birth=2015-10-22, createTime=2017-10-11 22:39:13.0]

2)GetReference ()Method, similar to the load () method of the Hibernate Session

1 // equivalent to the Session load method in Hibernate. If the query object is not used, a proxy object is returned, the SQL statement query is sent only when it is actually used. 2 // a lazy loading error may occur. 3 @ Test 4 public void testGetReference () {5 Customer customer = entityManager. getReference (Customer. class, 1); 6 System. out. println (customer. getClass (). getName (); 7 8 System. out. println ("-------------------------------------"); 9 10 // transaction. commit (); 11 // entityManager. close (); 12 13 System. out. println (customer); 14}

The result is: a proxy object is printed, and the horizontal line is printed before the SQL.

com.software.jpa.helloworld.Customer_$$_javassist_1---------------------------------------Hibernate:     select        customer0_.id as id1_2_0_,        customer0_.age as age2_2_0_,        customer0_.birth as birth3_2_0_,        customer0_.createTime as createTi4_2_0_,        customer0_.email as email5_2_0_,        customer0_.LAST_NAME as LAST_NAM6_2_0_     from        JPA_CUSTOMER customer0_     where        customer0_.id=?Customer [id=1, lastName=AA, email=aa@163.com, age=21, birth=2015-10-22, createTime=2017-10-11 22:39:13.0]

3)Persistence ()Method, similar to the save () method of Hibernate, which is different from the save () method of Hibernate.It cannot insert an object with the id attribute

1 // similar to the save method of Hibernate, so that the object changes from a temporary state to a persistent object. 2 // The Difference Between the save method of Hibernate and the save method is that if the id attribute exists, the system will not execute the insert operation and throw an exception 3 @ Test 4 public void testPersistence () {5 Customer customer = new Customer (); 6 customer. setLastName ("BB"); 7 customer. setEmail ("bb@163.com"); 8 customer. setBirth (new Date (); 9 customer. setCreateTime (new Date (); 10 customer. setAge (21); 11 12 // customer. setId (100); 13 14 entityManager. persist (customer); 15 16 System. out. println (customer. getId (); 17 18}

4)Remove ()Method,Similar to the delete method of Session in HibernateBut it cannot delete the free object (only id). An exception is thrown when the Row 5 or 6 is executed, because the customer object in the five rows is a free object.

1 // similar to the delete method of the Hibernate Session, delete the records corresponding to the object from the database. 2 // Note: This method can only remove persistent objects, the delete method of Hibernate can remove the free object 3 @ Test 4 public void testRemove () {5 // Customer customer = new Customer (); 6 // customer. setId (2); 7 8 Customer customer = entityManager. find (Customer. class, 2); 9 10 entityManager. remove (customer); 11 12}

5)Merge ()Method, similar to the saveOrUpdate () method of the Session in Hibernate

① A temporary object (without id) is passed in: a new object will be created, the properties of the temporary object will be copied to the new object, and then the new object will be persistently operated, row 13 executes the merge () method, passes in a temporary object, and returns a new object. The results of row 15 and Row 16 show that the new object has an id, the input object has an id, indicating that the new object is inserted into the database.

1 // 1. if a temporary object is input (no Id) 2 // a new object is created, and the properties of the temporary object are copied to the new object, then perform the persistence operation on the new object 3 // so the new object contains id, and the previous temporary object does not have id 4 @ Test 5 public void testMerge1 () {6 Customer customer = new Customer (); 7 customer. setAge (23); 8 customer. setBirth (new Date (); 9 customer. setCreateTime (new Date (); 10 customer. setEmail ("cc@126.com"); 11 customer. setLastName ("CC"); 12 13 Customer customer2 = entityManager. merge (customer); 14 15 System. out. println ("customer's id:" + customer. getId (); // null16 System. out. println ("customer's id:" + customer2.getId (); // 217}

② Passed in is a free object (with ID): If this object is not in the EntityManager cache and there is no corresponding record in the database, JPA will create a new object, copy the attributes of the current free object to the new object and perform the insert operation on the newly created object. The table corresponding to the LZ database does not have the id 100 customer, A new object is returned in row 15. According to the returned results, the new object is inserted.

1 // 2. if the input is a free object, that is, the input object has OID 2 // if the object does not exist in the EntityManager cache, there is no corresponding record in the database, JPA will create a new object. 3 // copy the attributes of the current free object to the new object and perform the insert operation 4 @ Test 5 public void testMerge2 () on the newly created object () {6 Customer customer = new Customer (); 7 customer. setAge (23); 8 customer. setBirth (new Date (); 9 customer. setCreateTime (new Date (); 10 customer. setEmail ("dd@126.com"); 11 customer. setLastName ("DD"); 12 13 customer. setId (100); 14 15 Customer customer2 = entityManager. merge (customer); 16 17 System. out. println ("customer's id:" + customer. getId (); // 10018 System. out. println ("customer's id:" + customer2.getId (); // 319}

③ The input is a free object, that is, the input object has an OID and is not in the cache, but the database has a corresponding object: JPA queries the corresponding records, then, return the object corresponding to the record, copy the attributes of the current free object to the queried object, and perform the update operation on the queried object.

1 // 3. if the input is a free object, that is, the input object has OID 2 // if the object is not in the EntityManager cache, there is a corresponding record in the database, JPA will query the corresponding record, then return the object corresponding to the record. 3 // copy the attributes of the current free object to the queried object and perform the update operation on the queried object. 4 @ Test 5 public void testMerge3 () {6 Customer customer = new Customer (); 7 customer. setAge (23); 8 customer. setBirth (new Date (); 9 customer. setCreateTime (new Date (); 10 customer. setEmail ("ff@126.com"); 11 customer. setLastName ("FF"); 12 13 customer. setId (3); 14 15 Customer customer2 = entityManager. merge (customer); 16 17 System. out. println (customer = customer2); // false18}

④ The input is a free object, that is, the input object has an OID, And the EntityManager cache has a corresponding object: JPA will copy the attribute of the current free object to the object in the queried EntityManager cache, update objects in the EntityManager Cache

1 // 4. if the input is a free object, that is, the input object has OID 2 // if there is a corresponding object in the EntityManager cache, JPA copies the attributes of the current free object to the objects in the queried EntityManager cache. 3 // update the objects in the EntityManager cache 4 @ Test 5 public void testMerge4 () {6 Customer customer = new Customer (); 7 customer. setAge (23); 8 customer. setBirth (new Date (); 9 customer. setCreateTime (new Date (); 10 customer. setEmail ("dd@126.com"); 11 customer. setLastName ("DD"); 12 13 customer. setId (3); 14 Customer customer2 = entityManager. find (Customer. class, 3); 15 16 entityManager. merge (customer); 17 18 System. out. println (customer = customer2); // false19}

4.EntityTransaction: Transactions in JPA

Common API: begin () commit () rollback () code is no longer demonstrated

V. mappings in JPA

1. ingOne-way, multiple-to-oneOrder: Customer n: 1,OrderThere is the Customer attribute, but the Customer does not have the Order attribute.(One-way, one-to-one, different from one-way, one-to-many)

1) Create an Order object class, annotate annotations, generate data tables, map multiple-to-one associations using @ ManyToOne, and use @ JoinColumn to annotate Foreign keys

1 package com. software. jpa. helloworld; 2 3 import javax. persistence. column; 4 import javax. persistence. entity; 5 import javax. persistence. fetchType; 6 import javax. persistence. generatedValue; 7 import javax. persistence. id; 8 import javax. persistence. joinColumn; 9 import javax. persistence. manyToOne; 10 import javax. persistence. table; 11 12 @ Table (name = "JPA_ORDERS") 13 @ Entity14 public class Order {15 16 private Integer id; 17 18 private String orderName; 19 20 @ GeneratedValue21 @ Id22 public Integer getId () {23 return id; 24} 25 26 public void setId (Integer id) {27 this. id = id; 28} 29 30 @ Column (name = "ORDER_NAME") 31 public String getOrderName () {32 return orderName; 33} 34 35 public void setOrderName (String orderName) {36 this. orderName = orderName; 37} 38 39 private Customer customer; 40 41/** 42 * ing the relationship between a single N-1 (Customer and Order, Order has the Customer attribute, but the Customer does not have the Order attribute) 43 * use @ ManyToOne to map multiple-to-one associations 44 * use @ JoinColumn to map Foreign keys 45 * use @ ManyToOne's fetch attribute to modify the loading policy of default Association attributes 46 */47 @ JoinColumn (name = "CUSTOMER_ID ") 48 @ ManyToOne (fetch = FetchType. LAZY) 49 public Customer getCustomer () {50 return customer; 51} 52 53 public void setCustomer (Customer customer) {54 this. customer = customer; 55} 56 57}

2) one-way, multiple-to-oneSave (persist):Save multiple-to-one times. We recommend that you save one end first.And then save the n end, so there will be no additional UPDATE statement

3)Get operation (find):By default, the left Outer Join method is used to obtain objects at one end of n and objects at one end of associated 1., You can use@ ManyToOne: fetch attributeComeModify the loading policy of the default Association attribute

4)Delete operation (remove): The End of 1 cannot be deleted directly because of foreign key constraints.

 

5) Modification Operation:

2. ingUnidirectional 1-nAssociationCustomer: Order1: N,There are Set attributes of Order in Customer, and Order does not have the attributes of Customer.

1)Add the Set attribute of Order to Customer and map the 1-n relationship., Regenerate the data table

2)Save operation (persist):There will always be more UPDATE statements, and the n end will not insert foreign key columns at the time of insertion.

3)Query operation (find):Lazy loading is used by default.

 

4)Delete operation (remove): By default, if one end of 1 is deleted, the foreign key at the end of n is left blank and then deleted, you can modify the default deletion policy (CascadeType. REMOVE indicates cascade deletion)

 

3.Ing two-way multi-to-one Association(Note: bidirectional multiple to one bidirectional one-to-multiple)

1) entity:"Customer" has the Set attribute of Order, and "Order" has the attribute of "Customer". Note that the foreign key columns mapped to the two entities must be consistent and both are mermer_id.

 

2)Save operation (persist):

 

 

4.Ing two-way one-to-one Association

1) entity:Manager and Department, one Department has one Manager, one Manager manages one Department

2) create a Manager class and a Department class,The Manager class has Department references and the Department has Manager references.,Department to maintain the association relationship (in fact, both sides of the two-way 1-1 can maintain the association relationship), Use@ OneToOneComeIng 1-1 associations. Add necessary annotations to generate data tables.

3)Save operation:

4)Query operation:

5.Ing bidirectional many-to-many associations

1) entity:Item and Category. One product Category has multiple items, and one product corresponds to multiple categories..Both parties contain the Set of the other party.Create object classes, Add corresponding annotations, and generate data tables.

2)Save operation:

3)Query operations:

 

Bytes ----------------------------------------------------------------------------------------------------------------

Related Links: Using JPA + SpringData to operate databases can be as simple as ever-learn more about JPA-1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.