02 JPAUtil工具类

JPAUtil工具类

1、创建一个工具类

package com.mars.util;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/*
    解决实体管理器工厂的浪费资源和耗时问题
        通过静态代码块的形式,当程序第一次访问此工具时,创建一个公共的实体管理器工厂对象
    第一次访问getEntityManager时:经过静态代码块创建一个factory对象,再调用方法创建一个EntityManager对象
    第二次访问getEntityManager时:直接通过一个已经创建好的factory对象,创建EntityManager对象
 */
public class JpaUtils {
    private static EntityManagerFactory entityManagerFactory;
    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");
    }
    public static EntityManager getEntityManagerFactory() {
        return entityManagerFactory.createEntityManager();
    }
}

2、测试

package com.mars.test;
import com.mars.domain.Customer;
import com.mars.util.JpaUtils;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaTest {
    @Test
    public void testSave2() {
        //1、通过工具类获取entityManager
        EntityManager entityManager = JpaUtils.getEntityManagerFactory();
        //2、开启事物
        EntityTransaction entityTransaction = entityManager.getTransaction();
        entityTransaction.begin();
        //4、完成增删改查操作
        Customer customer = new Customer();
        customer.setCustName("xx2");
        customer.setCustIndustry("新科技");
        entityManager.persist(customer);
        //5、提交事物(回滚事务)
        entityTransaction.commit();
        //6、释放资源
        entityManager.close();
    }
}

日志打印

Hibernate: drop table if exists cst_customer
Hibernate: create table cst_customer (cust_id bigint not null auto_increment, cust_address varchar(255), cust_industry varchar(255), cust_level varchar(255), cust_name varchar(255), cust_phone varchar(255), cust_source varchar(255), primary key (cust_id))
Hibernate: insert into cst_customer (cust_address, cust_industry, cust_level, cust_name, cust_phone, cust_source) values (?, ?, ?, ?, ?, ?)
上一篇:sql必知必会(第五版)学习总结(三)--mysql的视图,存储过程,事务处理,游标,触发器总结


下一篇:实现Android语音识别服务接口 RecognitionService的方法