Hibernate HelloWorld案例

搭建一个Hibernate环境,开发步骤:

1. 下载源码

         版本:hibernate-distribution-3.6.0.Final

2. 引入jar文件

         hibernate3.jar核心  +  required 必须引入的(6个) +  jpa 目录  + 数据库驱动包

3. 写对象以及对象的映射

         Employee.java            对象

         Employee.hbm.xml        对象的映射 (映射文件)

4. src/hibernate.cfg.xml  主配置文件

         -数据库连接配置

         加载所用的映射(*.hbm.xml)

5. App.java  测试


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 + "]";
    }
    
}

Employee.hbm.xml

<?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>

src/hibernate.cfg.xml 

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <!-- 通常,一个session-factory节点代表一个数据库 -->
    <session-factory>
    
        <!-- 1. 数据库连接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hib_demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <!-- 
            数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        
        <!-- 2. 其他相关配置 -->
        <!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 2.2 格式化sql -->
        <property name="hibernate.format_sql">true</property>
        <!-- 2.3 自动建表  -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 3. 加载所有映射     -->
        <mapping resource="loaderman/a_hello/Employee.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

测试:

package loaderman.a_hello;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App {

    @Test
    public void testHello() throws Exception {
        // 对象
        Employee emp =new Employee();
//        Employee emp = new Employee();
        emp.setEmpName("班长");
        emp.setWorkDate(new Date());

        // 获取加载配置文件的管理类对象
        Configuration config = new Configuration();
        config.configure();  // 默认加载src/hibenrate.cfg.xml文件
        // 创建session的工厂对象
        SessionFactory sf = config.buildSessionFactory();
        // 创建session (代表一个会话,与数据库连接的会话)
        Session session = sf.openSession();
        // 开启事务
        Transaction tx = session.beginTransaction();
        //保存-数据库
        session.save(emp);
        // 提交事务
        tx.commit();
        // 关闭
        session.close();
        sf.close();
    }
}

 

package loaderman.a_hello;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App2 {

    private static SessionFactory sf;
    static  {
        /*
        //1. 创建配置管理类对象
        Configuration config = new Configuration();
        // 加载配置文件  (默认加载src/hibernate.cfg.xml)
        config.configure();
        //2. 根据加载的配置管理类对象,创建SessionFactory对象
        sf = config.buildSessionFactory();
        */

        // 创建sf对象
        sf = new Configuration().configure().buildSessionFactory();
    }

    //1. 保存对象
    @Test
    public void testSave() throws Exception {
        // 对象
        Employee emp = new Employee();
        emp.setEmpName("张三123");
        emp.setWorkDate(new Date());

        //根据session的工厂,创建session对象
        Session session = sf.openSession();
        // 开启事务
        Transaction tx = session.beginTransaction();
        //-----执行操作-----
        session.save(emp);

        // 提交事务/ 关闭
        tx.commit();
        session.close();
    }


    //更新
    @Test
    public void testUpdate() throws Exception {
        // 对象
        Employee emp = new Employee();
        emp.setEmpId(1);
        emp.setEmpName("张三3");

        // 创建session
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        //-------执行操作-------
        // 没有设置主键,执行保存;有设置主键,执行更新操作; 如果设置主键不存在报错!
        session.saveOrUpdate(emp);

        tx.commit();
        session.close();
    }
}
package loaderman.a_hello;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

public class App3 {

    private static SessionFactory sf;
    static  {

        // 创建sf对象
        sf = new Configuration().configure().buildSessionFactory();
    }

    //HQL查询  【适合有数据库基础的】
    @Test
    public void testQuery() throws Exception {

        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        // 主键查询
        //Employee emp = (Employee) session.get(Employee.class, 1);

        // HQL查询,查询全部
        Query q = session.createQuery("from Employee where empId=1 or empId=2");
        List<Employee> list = q.list();

        System.out.println(list);

        tx.commit();
        session.close();
    }


    //QBC查询  , query by criteria  完全面向对象的查询
    @Test
    public void testQBC() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(Employee.class);
        // 条件
        criteria.add(Restrictions.eq("empId", 1));
        // 查询全部
        List<Employee> list = criteria.list();

        System.out.println(list);

        tx.commit();
        session.close();
    }

    //sQL
    @Test
    public void testSQL() throws Exception {
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        // 把每一行记录封装为对象数组,再添加到list集合
//        SQLQuery sqlQuery = session.createSQLQuery("select * from employee");
        // 把每一行记录封装为 指定的对象类型
        SQLQuery sqlQuery = session.createSQLQuery("select * from employee").addEntity(Employee.class);
        List list = sqlQuery.list();

        System.out.println(list);

        tx.commit();
        session.close();
    }
}

 

posted on 2018-11-29 10:39  LoaderMan  阅读(129)  评论(0编辑  收藏  举报

导航