1. Configure 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. In the j2se environment, only the entitymanager managed by the application can be used and transactions can be manually controlled.
Public class testclient {public static void main (string [] ARGs) {entitymanagerfactory EMF = persistence. createentitymanagerfactory ("bookstorepu"); entitymanager em = EMF. createentitymanager (); try {// start em of the transaction. gettransaction (). begin ();/* entity operation * // transaction commit em. gettransaction (). commit ()} finally {em. close (); EMF. close ();}}
}
3. Add the jar package of the JPA implementer to the running class path.
---------------------------------------------------------------------------------------------------------------------------
Use JPA in a Web Environment
1. The persistent transaction type is resource_local.
2. We recommend that you use the JNDI method to configure the data source by using <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. manually control transactions in the Web environment.
4. Add the jar package of the JPA implementer to the running class path, or put it under the Tomcat Lib.