@Autowired
private EntityManagerFactory entityManagerFactory;
@PersistenceContext
private EntityManager em;
public Session getSession() {
return entityManagerFactory.unwrap(SessionFactory.class).openSession();
}
/**
* 多条件查询
*
* @param t
*/
@Override
public List<Article> ListArticle(String account,String homePage) {
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
Root<Article> rt = criteriaQuery.from(Article.class);
//条件集合
List<Predicate> predicates = new ArrayList<Predicate>();
//添加条件
predicates.add(criteriaBuilder.equal(rt.get("account"),account));
if (Util.isNotEmpty(homePage)){
predicates.add(criteriaBuilder.equal(rt.get("homePage"),homePage));
}
//
criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
List<Article> list = getSession().createQuery(criteriaQuery).getResultList();
return list;
}
/**
* 创建信息
*
* @param t
*/
@Override
public void createObject(T t) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
//4.开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//新建
entityManager.persist(t);
//6.提交事务
transaction.commit();
//7.关闭 EntityManager
entityManager.close();
}
/**
* 修改信息
*
* @param t
*/
@Override
public void updateObject(T t) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
//4.开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//更新
entityManager.merge(t);
//6.提交事务
transaction.commit();
//7.关闭 EntityManager
entityManager.close();
}
/**
* 删除信息
*
* @param t
*/
@Override
public void deleteObject(T t) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
//4.开启事务
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
//删除
entityManager.remove(t);
//6.提交事务
transaction.commit();
//7.关闭 EntityManager
entityManager.close();
}