jap中的EntityManager类定义

package com.dada.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class EntityManagerHelper {

	// 实体化私有静态实体管理器emf
	private static final EntityManagerFactory emf;
	// 实体化私有静态本地线程变量threadLocal
	private static final ThreadLocal threadLocal;

	// 给两个变量赋予初始值
	static {
		emf = Persistence.createEntityManagerFactory("rightsmanagement3PU");
		threadLocal = new ThreadLocal();
	}

	// 获取实体管理器方法
	public static EntityManager getEntityManager() {
		EntityManager manager = threadLocal.get();
		if (manager == null || !manager.isOpen()) {
			manager = emf.createEntityManager();
			threadLocal.set(manager);
		}
		return manager;
	}

	// 关闭实体管理器
	public static void closeEntity() {
		EntityManager em = threadLocal.get();
		threadLocal.set(null);
		if (em != null)
			em.close();
	}

	// 开始事务的方法
	public static void beginTransaction() {
		if(getEntityManager().getTransaction().isActive()){
			getEntityManager().getTransaction().commit();
		}
		getEntityManager().getTransaction().begin();
	}

	// 提交事务的方法
	public static void commit() {
		if(getEntityManager().getTransaction().isActive()) {
			getEntityManager().getTransaction().commit();
		}
	}

	// 回滚事务的方法
	public static void rollBack() {
		getEntityManager().getTransaction().rollback();
	}

	// 生成查找的方法
	public static Query createQuery(String sql) {
		return getEntityManager().createQuery(sql);
	}
}

你可能感兴趣的:(jap中的EntityManager类定义)