OpenJPA超简单入门

环境准备

OpenJPA下载:http://openjpa.apache.org/

Derby下载:http://db.apache.org/derby/

案例源码下载:http://rcom10002.download.csdn.net/user/rcom10002/Java

在学习案例一和二之前,先准备好实验环境,首先准备数据表:

CREATE TABLE AIRLINES ( AIRLINE CHAR(2) NOT NULL , AIRLINE_FULL VARCHAR(24), BASIC_RATE DOUBLE PRECISION, DISTANCE_DISCOUNT DOUBLE PRECISION, BUSINESS_LEVEL_FACTOR DOUBLE PRECISION, FIRSTCLASS_LEVEL_FACTOR DOUBLE PRECISION, ECONOMY_SEATS INTEGER, BUSINESS_SEATS INTEGER, FIRSTCLASS_SEATS INTEGER )

然后准备好Java到数据表的映射:

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 = "AIRLINE_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 * the airline to set */ public void setAirline(String airline) { this.airline = airline; } /** * @return the airlineFull */ public String getAirlineFull() { return airlineFull; } /** * @param airlineFull * the airlineFull to set */ public void setAirlineFull(String airlineFull) { this.airlineFull = airlineFull; } /** * @return the basicRate */ public double getBasicRate() { return basicRate; } /** * @param basicRate * the basicRate to set */ public void setBasicRate(double basicRate) { this.basicRate = basicRate; } /** * @return the distanceDiscount */ public double getDistanceDiscount() { return distanceDiscount; } /** * @param distanceDiscount * the distanceDiscount to set */ public void setDistanceDiscount(double distanceDiscount) { this.distanceDiscount = distanceDiscount; } /** * @return the businessLevelFactor */ public double getBusinessLevelFactor() { return businessLevelFactor; } /** * @param businessLevelFactor * the businessLevelFactor to set */ public void setBusinessLevelFactor(double businessLevelFactor) { this.businessLevelFactor = businessLevelFactor; } /** * @return the firstclassLevelFactor */ public double getFirstclassLevelFactor() { return firstclassLevelFactor; } /** * @param firstclassLevelFactor * the firstclassLevelFactor to set */ public void setFirstclassLevelFactor(double firstclassLevelFactor) { this.firstclassLevelFactor = firstclassLevelFactor; } /** * @return the economySeats */ public int getEconomySeats() { return economySeats; } /** * @param economySeats * the economySeats to set */ public void setEconomySeats(int economySeats) { this.economySeats = economySeats; } /** * @return the businessSeats */ public int getBusinessSeats() { return businessSeats; } /** * @param businessSeats * the businessSeats to set */ public void setBusinessSeats(int businessSeats) { this.businessSeats = businessSeats; } /** * @return the firstclassSeats */ public int getFirstclassSeats() { return firstclassSeats; } /** * @param firstclassSeats * the firstclassSeats to set */ public void setFirstclassSeats(int firstclassSeats) { this.firstclassSeats = firstclassSeats; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int 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) { if (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 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; } }

在META-INF中准备persistence.xml,配置两个持久化单元,一个给案例一使用,另一个给案例二使用。

<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>

案例一 —— OpenJPA在Java应用程序中使用

在这个例子中,重点是如何获取“EntityManagerFactory”,由于是在非JEE容器环境中使用OpenJPA,所以事务类型无法采用JTA形式,我们需要手工进行事务管理。具体的例子源码如下:

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.EmbeddedDriver"; 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 String[] {"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 is) { if (is != null) { Writer 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.toString(); } else { return ""; } } } }

案例二——从Spring中获取OpenJPA编程接口

与上面的例子类似,只是在这里我们改换另一种从Spring中获取“EntityManagerFactory”的方法,Spring的配置如下:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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>

Java实例代码如下:

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 ClassPathXmlApplicationContext( 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 * FROM AIRLINES", Airline.class).getResultList(); for (Airline eachAirline : airlines) { System.out.println(eachAirline.getAirline()); System.out.println(eachAirline.getAirlineFull()); } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值