zoukankan      html  css  js  c++  java
  • Spring Date Jpa 增删改查

     @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();
    }
     
  • 相关阅读:
    MVC4中EasyUI Tree异步加载JSON数据生成树
    Linq语法
    委托的多种写法
    centos7安装Hive2.3.0
    ApacheKylin笔记
    把普通的JavaProject变成MavenProject
    eclipse 手动/自动安装插件
    我的JdbcUtils类
    Druid 连接池 JDBCUtils 工具类的使用
    Maven下载cxf所需要的jar包
  • 原文地址:https://www.cnblogs.com/CompetitiveHeart/p/11635164.html
Copyright © 2011-2022 走看看