• Hibernate之CRUD操作


    package loaderman.b_crud;
    
    import loaderman.a_hello.Employee;
    
    import java.io.Serializable;
    import java.util.List;
    
    
    public interface IEmployeeDao {
    
        void save(Employee emp);
        void update(Employee emp);
        Employee findById(Serializable id);
        List<Employee> getAll();
        List<Employee> getAll(String employeeName);
        List<Employee> getAll(int index, int count);
        void delete(Serializable id);
        
    }
    package loaderman.b_crud;
    
    import org.hibernate.cfg.Configuration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    import org.junit.Test;
    public class App_ddl {
    
        // 自动建表
        @Test
        public void testCreate() throws Exception {
            // 创建配置管理类对象
            Configuration config = new Configuration();
            // 加载主配置文件
            config.configure();
    
            // 创建工具类对象
            SchemaExport export = new SchemaExport(config);
            // 建表
            // 第一个参数: 是否在控制台打印建表语句
            // 第二个参数: 是否执行脚本
            export.create(true, true);
        }
    }
    package loaderman.b_crud;
    
    import java.io.Serializable;
    import java.util.List;
    
    import loaderman.a_hello.Employee;
    import loaderman.utils.HibernateUtils;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    
    
    
    public class EmployeeDaoImpl implements IEmployeeDao{
    
        @Override
        public Employee findById(Serializable id) {
            Session session = null;
            Transaction tx = null;
            try {
                // 获取Session
                session = HibernateUtils.getSession();
                // 开启事务
                tx = session.beginTransaction();
                // 主键查询
                return (Employee) session.get(Employee.class, id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
        }
    
        @Override
        public List<Employee> getAll() {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtils.getSession();
                tx = session.beginTransaction();
                // HQL查询
                Query q = session.createQuery("from Employee");
                return q.list();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
        }
    
        @Override
        public List<Employee> getAll(String employeeName) {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtils.getSession();
                tx = session.beginTransaction();
                Query q =session.createQuery("from Employee where empName=?");
                // 注意:参数索引从0开始
                q.setParameter(0, employeeName);
                // 执行查询
                return q.list();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
        }
    
        @Override
        public List<Employee> getAll(int index, int count) {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtils.getSession();
                tx = session.beginTransaction();
                Query q = session.createQuery("from Employee");
                // 设置分页参数
                q.setFirstResult(index);  // 查询的其实行
                q.setMaxResults(count);      // 查询返回的行数
    
                List<Employee> list = q.list();
                return list;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
        }
    
        @Override
        public void save(Employee emp) {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtils.getSession();
                tx = session.beginTransaction();
                // 执行保存操作
                session.save(emp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
    
        }
    
        @Override
        public void update(Employee emp) {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtils.getSession();
                tx = session.beginTransaction();
                session.update(emp);
    
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
    
        }
    
        @Override
        public void delete(Serializable id) {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtils.getSession();
                tx = session.beginTransaction();
                // 先根据id查询对象,再判断删除
                Object obj = session.get(Employee.class, id);
                if (obj != null) {
                    session.delete(obj);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                tx.commit();
                session.close();
            }
        }
    }
    package loaderman.a_hello;
    
    import java.util.Date;
    
    public class Employee {
    
        private int empId;
        private String empName;
        private Date workDate;
        
        public int getEmpId() {
            return empId;
        }
        public void setEmpId(int empId) {
            this.empId = empId;
        }
        public String getEmpName() {
            return empName;
        }
        public void setEmpName(String empName) {
            this.empName = empName;
        }
        public Date getWorkDate() {
            return workDate;
        }
        public void setWorkDate(Date workDate) {
            this.workDate = workDate;
        }
        @Override
        public String toString() {
            return "Employee [empId=" + empId + ", empName=" + empName
                    + ", workDate=" + workDate + "]";
        }
        
    }
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping package="loaderman.a_hello">
        
        <class name="Employee" table="employee">
            
            <!-- 主键 ,映射-->
            <id name="empId" column="id">
                <generator class="native"/>
            </id>
            
            <!-- 非主键,映射 -->
            <property name="empName" column="empName"></property>
            <property name="workDate" column="workDate"></property>
            
        </class>
    
    </hibernate-mapping>
    package loaderman.utils;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtils {
    
        private static SessionFactory sf;
        static {
            // 加载主配置文件, 并创建Session的工厂
            sf = new Configuration().configure().buildSessionFactory();
        }
    
        // 创建Session对象
        public static Session getSession(){
            return sf.openSession();
        }
    }
  • 相关阅读:
    make -j 8参数的作用
    使用请求头认证来测试需要授权的 API 接口
    查看Linux系统的平均负载
    服务器负载均衡的基本功能和实现原理
    Oracle RAC学习笔记:基本概念及入门
    详解物化视图(汇总比较有用的资料)
    程序优化注意的一些点
    PR 审批界面增加显示项方法
    Most Common Solutions to FRM-41839 and .tmp Files Not Being Deleted
    APPCORE Routine APIs
  • 原文地址:https://www.cnblogs.com/loaderman/p/10036878.html
Copyright © 2020-2023  润新知