三、JPA增删改查常用方法

前言:创建EntityManager对象,需要先创建创建EntityManagerFactory对象

方式一:直接通过persistenceUnitName创建

1 String persistenceUnitName = "Jpa-1";
2 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);

方式二:通过persistenceUnitName和properties一起创建

1 String persistenceUnitName = "Jpa-1";
2 Map<String, Object> properties = new HashMap<String, Object>();
3 properties.put("hibernate.show_sql", false);
4 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, properties);

 

2.创建一个测试增删改查的JPA项目

 

 1 package com.jtfr.jpa.test;
 2 
 3 import javax.persistence.EntityManager;
 4 import javax.persistence.EntityManagerFactory;
 5 import javax.persistence.EntityTransaction;
 6 import javax.persistence.Persistence;
 7 
 8 import org.junit.After;
 9 import org.junit.Before;
10 import org.junit.Test;
11 
12 public class JpaTest {
13     
14     private EntityManagerFactory entityManagerFactory;
15     private EntityManager entityManager;
16     private EntityTransaction transaction;
17 
18     @Before
19     public void create(){
20         entityManagerFactory = Persistence.createEntityManagerFactory("Jpa-1");
21         entityManager = entityManagerFactory.createEntityManager();
22         transaction = entityManager.getTransaction();
23         transaction.begin();
24     }
25 
26     @Test
27     public void testFind(){
28         System.out.println("没问题");
29     }
30     
31     @After
32     public void end(){
33         transaction.commit();
34         entityManager.close();
35         entityManagerFactory.close();
36     }
37 }

3.常用增删改查方法解释

 find方法

 

猜你喜欢

转载自www.cnblogs.com/jtfr/p/10376315.html
0条评论
添加一条新回复