美文网首页Java
Hibernate CRUD 操作

Hibernate CRUD 操作

作者: 春泥村雨 | 来源:发表于2018-04-17 21:44 被阅读10次

    1、定义一个返回 sessionFactory 的公共类

    HibernateUtil.java

    package com.bjsxt.util;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil
    {
        private static SessionFactory sessionFactory;
        
        static
        {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }
        
        public static SessionFactory getSessionFactory()
        {
            return sessionFactory;
        }
    }
    

    2、CRUD 操作示例

    package com.bjsxt.dao.impl;
    
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    
    import com.bjsxt.dao.UserDao;
    import com.bjsxt.entity.User;
    import com.bjsxt.util.HibernateUtil;
    
    public class UserDaoImpl implements UserDao
    {
        //新增
        @Override
        public boolean save(User u)
        {
            try
            {
                SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
                Session session = sessionFactory.getCurrentSession();
                session.beginTransaction();
                session.save(u);
                session.getTransaction().commit();
                return true;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }
        }
        
        //基于条件查询
        @Override
        public boolean checkUserExistsWithName(String username)
        {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            Session session = sessionFactory.getCurrentSession();
            session.beginTransaction();
            long count = (long) session.createQuery("select count(*) from User u where u.username= :username")
                    .setString("username", username)
                    .uniqueResult(); // //当确定返回的实例只有一个或者null时用uniqueResult()方法
            session.getTransaction().commit();
            if (count > 0)
            {
                return true;
            }
            return false;
        }
        
        //查询所有
        @Override
        public void queryAll()
        {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            Session session = sessionFactory.getCurrentSession();
            session.beginTransaction();
            List list = session.createQuery("from User").list();
            for(int i=0;i<list.size();i++)
            {
                User user=(User)list.get(i);
                System.out.println(user.getId()+":"+user.getUsername());
            }
            session.getTransaction().commit();
            System.out.println(list);
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Hibernate CRUD 操作

        本文链接:https://www.haomeiwen.com/subject/jhxmkftx.html