JavaSE使用JPA简单案例:
使用的JPA提供者是openjpa.
首先,新建一个普通的Java工程;
然后,导入openjpa所需要的jar包、数据库的驱动类、javaee.jar
(因为包含javax.persistence.*的API),见下图:
接着编写EntityBean:
package study.entity; import javax.persistence.Id; import java.io.Serializable; import javax.persistence.*; @SuppressWarnings("serial") @Entity public class Person implements Serializable{ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
然后是编写DAO吧,其实我更喜欢称为Service:
package study.service; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import study.entity.Person; public class PersonManagerImpl implements PersonManager { @Override public Person getPerson(int personId) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("helloworld"); EntityManager manager = emf.createEntityManager(); Person person = manager.find(Person.class, personId); manager.close(); emf.close(); return person; } @Override public void addPerson(Person person) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("helloworld"); EntityManager manager = emf.createEntityManager(); manager.getTransaction().begin(); manager.persist(person); manager.getTransaction().commit(); manager.close(); emf.close(); } }
在src下新建一个META-INF目录,在该目录中新建一个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="helloworld" transaction-type="RESOURCE_LOCAL"> <provider> org.apache.openjpa.persistence.PersistenceProviderImpl </provider> <class>study.entity.Person</class> <properties> <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost/firstjpa" /> <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver" /> <property name="openjpa.ConnectionUserName" value="root" /> <property name="openjpa.ConnectionPassword" value="XXXXXX" /> </properties> </persistence-unit> </persistence>
因为使用的是 JAVASE,所以直接将连接信息,写在了文件中。如果是用EJB容器,则可以使用JNDI的方式。
最后,在数据库中新建相应的数据库、数据库的表
(如果是Hibernate的话,可以不用见表,OpenJpa暂时不明了,还是新建吧。)
测试类 (打错了,少了个t,写成Tes了 ⊙﹏⊙b汗):
package study.test; import study.entity.Person; import study.service.PersonManager; import study.service.PersonManagerImpl; public class Tes { public static void main(String[] args) { PersonManager manager = new PersonManagerImpl(); Person person = new Person(); person.setName("xiaolongfeixiang"); manager.addPerson(person); Person person2 = manager.getPerson(1); System.out.println(person2.getName()); } }
运行结果: