Environmental Preparedness
OPENJPA Download: http://openjpa.apache.org/
Derby Download: http://db.apache.org/derby/
Case Source Download: Http://rcom10002.download.csdn.net/user/rcom10002/Java
Before learning case one and two, prepare the experimental environment first, prepare the data table:
CREATE TABLE AIRLINES (AIRLINE CHAR (2) Not NULL, Airline_full VARCHAR (), Basic_rate DOUBLE PRECISION, Distance_discoun T double PRECISION, Business_level_factor double PRECISION, Firstclass_level_factor double PRECISION, economy_seats Integer, business_seats integer, firstclass_seats integer)
Then prepare the Java to Datasheet mapping:
Import Javax.persistence.Column; Import javax.persistence.Entity; Import Javax.persistence.Id; Import javax.persistence.Table; @Entity @Table (name = "AIRLINES") public class Airline {@Id @Column (name = "Airline") String Airline; @Column (name = "AIR Line_full ") String airlinefull; @Column (name = "Basic_rate") double basicrate; @Column (name = "Distance_discount") double distancediscount; @Column (name = "Business_level_factor") double businesslevelfactor; @Column (name = "Firstclass_level_factor") double firstclasslevelfactor; @Column (name = "Economy_seats") int economyseats; @Column (name = "Business_seats") int businessseats; @Column (name = "Firstclass_seats") int firstclassseats; /** * @return The airline/public String Getairline () {return airline;}/** * @param airline * "Airline to set * * * p ublic void Setairline (String airline) {this.airline = airline;}/** * @return the Airlinefull/public String Getairlin Efull () {return airlinefull;}/** * @param airlinefull * the AirlinEfull to set */public void Setairlinefull (String airlinefull) {this.airlinefull = Airlinefull;}/** * @return the basic Rate */public double getbasicrate () {return basicrate;}/** * @param basicrate * The basicrate to set/public void SE Tbasicrate (double basicrate) {this.basicrate = basicrate;}/** * @return the Distancediscount * * Public double Getdistan Cediscount () {return distancediscount.}/** * @param distancediscount * The Distancediscount to set */public void SETDI Stancediscount (double distancediscount) {this.distancediscount = Distancediscount;}/** * @return the Businesslevelfact OR/* public double Getbusinesslevelfactor () {return businesslevelfactor;}/** * @param businesslevelfactor * the Busine Sslevelfactor to set */public void Setbusinesslevelfactor (double businesslevelfactor) {this.businesslevelfactor = Busin Esslevelfactor; }/** * @return the Firstclasslevelfactor */public double getfirstclasslevelfactor () {return firstclasslevelfactor;}/* * * @param Firstclasslevelfactor * The Firstclasslevelfactor to set */public void Setfirstclasslevelfactor (double firstclasslevelf Actor) {this.firstclasslevelfactor = firstclasslevelfactor}/** * @return the economyseats/public int geteconomyseat S () {return economyseats.}/** * @param economyseats * The economyseats to set */public void seteconomyseats (int econom Yseats) {this.economyseats = economyseats}/** * @return the businessseats/public int getbusinessseats () {return bu Sinessseats; /** * @param businessseats * The businessseats to set */public void setbusinessseats (int businessseats) {this.business seats = businessseats; }/** * @return the firstclassseats/public int getfirstclassseats () {return firstclassseats;}/** * @param firstclass Seats * The firstclassseats to set */public void setfirstclassseats (int firstclassseats) {this.firstclassseats = Firstcl Assseats; }/* * (NON-JAVADOC) * * @see Java.lang.object#hashcode ()/@Override public int hashcode () {finalint prime = 31; int result = 1; result = Prime * result + ((airline = null)? 0:airline.hashcode ()); result = Prime * result + ((Airlinefull = null)? 0:airlinefull.hashcode ()); Long temp; temp = double.doubletolongbits (basicrate); result = Prime * result + (int) (temp ^ (temp >>> 32)); temp = double.doubletolongbits (businesslevelfactor); result = Prime * result + (int) (temp ^ (temp >>> 32)); result = Prime * result + businessseats; temp = double.doubletolongbits (distancediscount); result = Prime * result + (int) (temp ^ (temp >>> 32)); result = Prime * result + economyseats; temp = double.doubletolongbits (firstclasslevelfactor); result = Prime * result + (int) (temp ^ (temp >>> 32)); result = Prime * result + firstclassseats; return result; }/* * (NON-JAVADOC) * * @see java.lang.object#equals (java.lang.Object)/@Override public boolean equals (Object obj) {i F (This = = obj) return true; if (obj = null) return false; if (GetClass ()!= OBJ.GEtclass ()) return false; Airline other = (Airline) obj; if (airline = = null) {if (other.airline!= null) return is false;} else if (!airline.equals (Other.airline)) return false; if (airlinefull = = null) {if (other.airlinefull!= null) return false;} else if (!airlinefull.equals (other.airlinefull)) return false; if (Double.doubletolongbits (basicrate)!= Double. Doubletolongbits (Other.basicrate)) return false; if (Double.doubletolongbits (businesslevelfactor)!= Double. Doubletolongbits (other.businesslevelfactor)) return False if (businessseats!= other.businessseats) return false; if (Double.doubletolongbits (distancediscount)!= Double. Doubletolongbits (Other.distancediscount)) return false; if (economyseats!= other.economyseats) return false; if (Double.doubletolongbits (firstclasslevelfactor)!= Double. Doubletolongbits (other.firstclasslevelfactor)) return False if (firstclassseats!= other.firstclassseats) return false; return true; }}
The
Prepares the persistence.xml in Meta-inf, configures two persistence units, one for case one use, and the other for case two.
<persistence xmlns= "http://java.sun.com/xml/ns/persistence" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "version=" 1.0 > <persistence-unit name= "openjpaexample" transaction-type= "RESOURCE_LOCAL" > <class>Airline</class> <properties> <property name= "OPENJPA. Connectionurl "value=" Jdbc:derby:jdbcdemodb;create=true "/> <property name=" OPENJPA. Connectiondrivername "value=" Org.apache.derby.jdbc.EmbeddedDriver "/> </properties> </persistence-unit > <!--<persistence-unit name= "openjpaspringexample" transaction-type= "JTA" >--> <persistence-unit Name= "Openjpaspringexample" transaction-type= "resource_local" > <class>Airline</class> < properties> <property name= "OPENJPA. Connectionurl "value=" Jdbc:derby:jdbcdemodb;create=true "/> <property name=" OPENJPA. Connectiondrivername "value=" Org.apache.derby.jdbc.EmbeddedDriver "/> </properties> </persistence-unit > </persistence> case a--OPENJPA used in Java applications
In this example, the focus is on how to get "entitymanagerfactory", because the OPENJPA is used in a JEE container environment, so the transaction type cannot take the Jta form, and we need to do transaction management manually. The specific example source code is as follows:
Import Java.io.BufferedReader; Import Java.io.InputStream; Import Java.io.InputStreamReader; Import Java.io.Reader; Import Java.io.StringWriter; Import Java.io.Writer; Import java.sql.Connection; Import Java.sql.DriverManager; Import Java.sql.ResultSet; Import java.sql.Statement; Import java.util.List; Import Javax.persistence.EntityManager; Import Javax.persistence.EntityManagerFactory; Import javax.persistence.Persistence; public class Openjpaexample {public static void main (string[] args) {String Driver = "Org.apache.derby.jdbc.EmbeddedDriv ER "; String Connectionurl = "Jdbc:derby:jdbcdemodb;create=true"; try {class.forname (driver);} catch (Java.lang.ClassNotFoundException e) {e.printstacktrace ();} Connection conn = null; Statement s = null; ResultSet rs = null; try {conn = drivermanager.getconnection (Connectionurl); rs = Conn.getmetadata (). gettables (NULL, NULL, "AIRLINES", New St Ring[] {"TABLE"}); if (Rs.next ()) {rs.close ();} else {s = conn.createstatement (); S.executeupdatE (Readsql ()); } catch (Throwable e) {e.printstacktrace ();} finally {try {if (rs!= null) {Rs.close ();} if (S!= null) {S.close ( ); } if (conn!= null) {Conn.close ();}} catch (Exception e) {e.printstacktrace ();}} Entitymanagerfactory factory = persistence.createentitymanagerfactory ("Openjpaexample", System.getproperties ()); Entitymanager em = Factory.createentitymanager (); Em.gettransaction (). Begin (); Airline Airline = null; Airline = new airline (); Airline.setairline ("CZ"); Airline.setairlinefull ("CZ12345"); Airline.setfirstclassseats (10); Airline.setbusinessseats (20); Airline.seteconomyseats (50); Em.persist (airline); Airline = new airline (); Airline.setairline ("MU"); Airline.setairlinefull ("MU54321"); Airline.setfirstclassseats (10); Airline.setbusinessseats (20); Airline.seteconomyseats (50); Em.persist (airline); @SuppressWarnings ("unchecked") list<airline> Airlines = em.createnativequery ("SELECT * From Airlines", Airline.class). Getresultlist (); for (Airline EachairLine:airlines) {System.out.println (Eachairline.getairline ()); System.out.println (Eachairline.getairlinefull ()); System.out.println (Eachairline.getfirstclassseats ()); System.out.println (Eachairline.getbusinessseats ()); System.out.println (Eachairline.geteconomyseats ()); System.out.println ("-----------------------------"); }//airline = Em.find (Airline.class, "MU"); Em.createnativequery ("DELETE from AIRLINES"). Executeupdate (); Em.gettransaction (). commit (); private static String Readsql () {InputStream stream = OpenJpaExample.class.getResourceAsStream ("/toursdb_schema.sql" ); return streamtostring.convertstreamtostring (stream); private static class Streamtostring {public static String convertstreamtostring (InputStream are) {if (is!= null) {Wri ter writer = new StringWriter (); char[] buffer = new char[1024]; try {Reader reader = new BufferedReader (new InputStreamReader (IS, UTF-8)); int n; while ((n = reader.read (buffer))!= -1) {writer.write (buffer, 0, n);}} catch (Exception E{E.printstacktrace ();} finally {try {is.close ();} catch (Exception e) {e.printstacktrace ();}} return Writer.tost Ring (); else {return "";}}}} case Two--get the OPENJPA programming interface from Spring
Similar to the above example, just here we change another way to get "entitymanagerfactory" from spring, which is configured as follows:
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id=" entitymanagerfactory "class=" Org.springframework.orm.jpa.LocalEntityManagerFactoryBean "> <property name=" persistenceunitname "value=" Openjpaspringexample "/> </bean> </beans>
The Java instance code is as follows:
Import Java.util.Date; Import java.util.List; Import Javax.persistence.EntityManager; Import Javax.persistence.EntityManagerFactory; Import Org.springframework.context.ApplicationContext; Import Org.springframework.context.support.ClassPathXmlApplicationContext; public class Openjpaspringexample {public static void main (string[] args) {ApplicationContext context = new Classpathxml ApplicationContext (new string[] {"Applicationcontext.xml"}); Entitymanagerfactory emf = (entitymanagerfactory) context.getbean ("Entitymanagerfactory"); Entitymanager em = Emf.createentitymanager (); Em.gettransaction (). Begin (); Remove all airlines Em.createnativequery (' DELETE from airlines '). Executeupdate (); Create a new airline airline airline = new airline (); Airline.setairline ("CZ"); Airline.setairlinefull ("CZ" + New Date (). GetTime ()); Airline.setfirstclassseats (10); Airline.setbusinessseats (20); Airline.seteconomyseats (50); Save the new airline em.persist (airline); Em.gettransaction (). commit (); @SuppressWarnings ("unchecked")//List all saved airlines list<airline> airlines = em.createnativequery ("SELECT * F" ROM AIRLINES ", Airline.class). Getresultlist (); for (Airline eachairline:airlines) {System.out.println (Eachairline.getairline ()); System.out.println (Eachairline.getairlinefull ()); }}