1. Persistence. xml configuration file:
<? XML version = "1.0" encoding = "UTF-8" ?> < Persistence Xmlns = Http://java.sun.com/xml/ns/persistence" Xmlns : Xsi = Http://www.w3.org/2001/XMLSchema-instance" Xsi : Schemalocation =Http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" Version = "1.0" > < Persistence - Unit Name = "Jpaonetomanypu" Transaction - Type = "Resource_local" > < Provider > Org. hibernate. EJB. hibernatepersistence </ Provider > < Properties > < Property Name = "Hibernate. dialect" Value = "Org. hibernate. dialect. mysql5dialect" /> < Property Name = "Hibernate. Connection. driver_class" Value = "Com. MySQL. JDBC. Driver" /> < Property Name = "Hibernate. Connection. url" Value = "JDBC: mysql: // localhost: 3306/JPA? Useunicode = true & amp; characterencoding = UTF-8" /> < Property Name = "Hibernate. Connection. username" Value = "Root" /> < Property Name = "Hibernate. max_fetch_depth" Value = "3" /> < Property Name = "Hibernate. hbm2ddl. Auto" Value = "Update" /> </ Properties > </ Persistence -Unit > </ Persistence >
2. Configuration entity:
Order entity:
ImportJava. util. hashset;
ImportJava. util. Set;
ImportJavax. Persistence. cascadetype;
ImportJavax. Persistence. column;
ImportJavax. Persistence. entity;
ImportJavax. Persistence. fetchtype;
ImportJavax. Persistence. ID;
ImportJavax. Persistence. oneto133;
ImportJavax. Persistence. Table;
@ Entity
@ Table (name ="Orders")
Public ClassOrder {
/**
* In a bidirectional one-to-multiple relationship, multiple parties are the maintenance end of the relationship.
* The maintenance end of The Link updates the foreign key field (record;
* The maintenance end of the link does not have the power to update the foreign key field (record.
*/
PrivateString orderid;
PrivateFloat amount = 0f;
PrivateSet <orderitem> items =NewHashset <orderitem> ();
@ ID// Assign values manually
@ Column (length = 12)
PublicString getorderid (){
ReturnOrderid;
}
Public VoidSetorderid (string orderid ){
This. Orderid = orderid;
}
@ Column (nullable = False )
Public Float getamount (){
Return Amount;
}
Public Void Setamount (float amount ){
This . Amount = amount;
}
Public Void Setitems (set <orderitem> items ){
This . Items = items;
}
/**
* Cascadetype. Refresh, cascadetype. persist, cascadetype. merge, cascadetype. Remove
* There are application conditions, that is, it is valid to call em. Refresh, Em. persist, Em. merge, Em. Remove.
* If query is used for update, deletion and addition are invalid.
*
* Refresh is the latest entity obtained from the database:
* Because the entity obtained in Em. Find may be different from the actual processing time,
* During these times, the entity may be updated to the database by other methods, but the EM cache has not changed,
* Therefore, you must use refresh to obtain the latest object.
*
* // Delayed loading must ensure that EM is on
// If tomany is used, loading is delayed by default.
// If it is toone, it is loaded immediately by default.
// Use mappedby to declare the maintenance end of the link. This indicates which attribute of the orderitem class maintains the link.
// In which class mappedby is displayed, the object indicates that the link is maintained.
*/
@ Onetosh (cascade = {cascadetype. Refresh, cascadetype. persist
, Cascadetype. merge, cascadetype. Remove}
, Fetch = fetchtype. Lazy
, Mappedby ="Order ")
Public Set <orderitem> getitems (){
Return Items;
}
// Establish link Maintenance
Public VoidAddorderitem (orderitem ){
Orderitem. setorder (This);// Set orderitem on the Link maintenance end to maintain the link
This. Items. Add (orderitem );
}
}
Orderitem entity:
Import Javax. Persistence. cascadetype; Import Javax. Persistence. column; Import Javax. Persistence. entity; Import Javax. Persistence. generatedvalue; Import Javax. Persistence. ID; Import Javax. Persistence. joincolumn; Import Javax. Persistence. manytoone; @ entity Public Class Orderitem { /*** In a bidirectional one-to-multiple relationship, multiple parties are the maintenance end of the link. * The maintenance end of the link is responsible for updating the foreign key field (record); * The maintenance end of the link is not authorized to update the foreign key field (record. */ Private Integer ID; Private String productname; Private Float pricefloat = 0f;Private Order order; Public Orderitem (){} Public Orderitem (string, Float F ){ This . Pricefloat = F; This . Productname = string ;} Public Void Setid (integer ID ){ This . ID = ID;} @ ID @ generatedvalue Public Integer GETID (){ Return ID ;} Public Void Setproductname (string productname ){ This . Productname = productname;} @ column (length = 40, nullable = False ) Public String getproductname (){ Return Productname ;} Public Void Setpricefloat (float pricefloat ){ This . Pricefloat = pricefloat;} @ column (nullable = False ) Public Float getpricefloat (){ Return Pricefloat ;}Public Void Setorder (order ){ This . Order = order ;} // Update the total price @ Manytoone (cascade = {cascadetype. merge, cascadetype. Refresh}, optional = False ) // Set the foreign key name @ Joincolumn (name =" Orderid ") Public Order getorder (){ Return Order ;}}
3. JUnit test:
Package JUnit. test; Import Javax. Persistence. entitymanager; Import Javax. Persistence. entitymanagerfactory; Import Javax. Persistence. persistence; Import Org. JUnit. beforeclass; Import Org. JUnit. test; Import Com. Persia. Bean. Order; Import Com. Persia. Bean. orderitem; Public Class Manytoonetest {@ beforeclass Public Static Void Setupbeforeclass ()Throws Exception {} // @ Test Public Void Save () {entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); // At this time, the database table has been created. If there is no table, it is likely that the object annotation has an error. Entitymanager em = FAC. createentitymanager (); em. gettransaction (). Begin (); Order order = New Order (); Order. setamount (34f); Order. setorderid (" 999 "); Order. addorderitem ( New Orderitem (" Football ", 90f); Order. addorderitem (New Orderitem (" Basketball ", 100f); em. persist (order); em. gettransaction (). Commit (); em. Close (); FAC. Close ();} // @ Test Public Void Getorder (){ // You do not need to enable the transaction for reading. Entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); Entitymanager em = FAC. createentitymanager (); order o = em. Find (Order. Class ," 999 "); // If no data exists, null is returned. System. Out. println (O. getorderid () +": "+ O. getamount (); em. Close (); FAC. Close ();} // @ Test Public Void Getorderitemsbyorder (){ // You do not need to enable the transaction for reading. Entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); Entitymanager em = FAC. createentitymanager (); order o = em. Find (Order. Class ," 999 "); // If no data exists, null is returned. System. Out. println (O. getorderid () +" : "+ O. getamount ()); For (Orderitem OTM: O. getitems () system. Out. println (OTM. getproductname () +" : "+ OTM. getpricefloat (); em. Close (); FAC. Close ();} // @ Test Public Void Getorderitems (){ // You do not need to enable the transaction for reading. Entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); Entitymanager em = FAC. createentitymanager (); orderitem OTM = em. Find (orderitem. Class , 1 ); // If no data exists, null is returned. System. Out. println (OTM. getproductname () +" : "+ OTM. getpricefloat (); system. Out. println ("Order ID: "+ OTM. getorder (). getorderid (); em. Close (); FAC. Close ();} // @ Test Public Void Updateorder () {entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); Entitymanager em = FAC. createentitymanager (); em. gettransaction (). Begin (); // Start the transaction Order order = em. Find (Order. Class ," 999 "); Order. setamount (1000f); em. Merge (order ); // Synchronize updates to the entity bean in the Free State to the database. Em. gettransaction (). Commit (); // Submit the transaction Em. Close (); FAC. Close ();} /// @ Test // cascade update Public Void Updateordercascade () {entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); Entitymanager em = FAC. createentitymanager (); em. gettransaction (). Begin (); // Start the transaction Order order = em. Find (Order. Class ," 999 "); Order. setamount (2000f ); For (Orderitem OTM: Order. getitems () {OTM. setpricefloat (300f);} em. Merge (order ); // Synchronize updates to the entity bean in the Free State to the database. Em. gettransaction (). Commit ();// Submit the transaction Em. Close (); FAC. Close () ;}@ Test // Cascading Deletion Public Void Deleteorder () {entitymanagerfactory FAC = persistence. createentitymanagerfactory (" Jpaonetomanypu "); Entitymanager em = FAC. createentitymanager (); em. gettransaction (). Begin (); // Start the transaction Order order = em. Find (Order. Class ," 999 "); Em. Remove (order); em. gettransaction (). Commit (); // Submit the transaction Em. Close (); FAC. Close ();}}