在J2SE环境中使用JPA
1.配置persistence.xml
<?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="BookStorePU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/jpademo"/> <property name="hiberante.cnnection.username" value="root"/> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence>
2.在J2SE环境中只能使用应用托管的EntityManager并且手工控制事务。public class TestClient{ public static void main(String[] args){ EntityManagerFactory emf=Persistence.createEntityManagerFactory("BookStorePU"); EntityManager em=emf.createEntityManager(); try{ //事务的开始 em.getTransaction().begin(); /*实体操作*/ //事务的提交 em.getTransaction().commit() }finally{ em.close(); emf.close(); } }
}
3.将JPA实现者的jar包添加到运行类路径中。
---------------------------------------------------------------------------------------------------------------------------
在web环境下使用JPA
1.持久化事务类型为RESOURCE_LOCAL
2.配置数据源建议采用JNDI方式,通过<non-jta-data-source>
<?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="BookStorePU" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <non-jta-data-source>java:comp/env/jdbc/jpademo</non-jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence>
3.在web环境中手工控制事务。
4.将JPA实现者的jar包添加到运行类路径中,也可以放到tomcat的lib下面。
浙公网安备 33010602011771号