JavaSE中Jpa的应用入门
一.JPa提供的用户接口
Persistence,EntityMangerFactory,EntityManager
二.配置.
1.添加Jar包
以hibernate作为Jpa的实现进行.
添加hibernate的jar包.
添加hibernate-entitymanager的jar包
2.配置persistence.xml文件
在src下新建文件夹META-INF
在MET-INF创建persistence.xml文件.配置如下:
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">
org.hibernate.ejb.HibernatePersistence
org.jenfer.jpa.entity.Emp
说明:persistence-unit是持久化单元的名字
< provider/>:JPA实现提供程序
持久化的类
实现厂商自定义的属性
这里是hibernate的自定属性.相关资料参考hibernate的配置
三.实体类的实现:
以下是是用Jpa的注解的POJO.
@Table,@Entity等请参考Jpa官方文档
@Table(name ="emp")
@Entity(name ="Emp")
publicclassEmp {
@Id
@Column(name ="emp_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
privateintempId;
@Column(name ="emp_name", length = 10)
privateStringempName;
privateStringemail;
/**
*Defaultconstructor
*/
publicEmp() {
}
publicintgetEmpId() {
returnempId;
}
publicvoidsetEmpId(intempId) {
this.empId= empId;
}
publicString getEmpName() {
returnempName;
}
publicvoidsetEmpName(String empName) {
this.empName= empName;
}
publicString getEmail() {
returnemail;
}
publicvoidsetEmail(String email) {
this.email= email;
}
}
四.测试类库的编写.用到Junit测试框架
publicclassEvnTest {
privatestaticEntityManagermanager;
@BeforeClass
public static void init() {
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("Emp");
manager = factory.createEntityManager();
}
@AfterClass
publicstaticvoiddestory(){
if(manager!=null){
manager.close();
}
}
@Test
@Ignore
publicvoidenvTest() {
Emp emp =newEmp();
emp.setEmail("wangwu@123.com");
emp.setEmpName("周星驰");
EntityTransaction tx =manager.getTransaction();
try{
tx.begin();
manager.persist(emp);
tx.commit();
}catch(Exception e) {
tx.rollback();
}
}
@Test@Ignore
publicvoidqueryTest() {
Emp emp=manager.find(Emp.class, 1);
System.out.println(emp.getEmpName());
}
@Test@Ignore
publicvoidupdateTest(){
Emp emp =newEmp();
emp.setEmail("jsj@123.com");
emp.setEmpName("周剑华");
emp.setEmpId(1);
EntityTransaction tx =manager.getTransaction();
try{
tx.begin();
manager.merge(emp);
tx.commit();
}