Hibernate基础教程

Hibernate第一餐

1、在eclipse中安装JBoss Tools插件

2、导入相应的包

  1. lib\required文件夹下的包
  2. log4j.jar
  3. 数据库驱动

3、创建hibernate的配置文件

在src目录下创建hibernate.cfg.xml文件,在这个文件中完成数据库基本信息的配置,这些配置信息可以在project\etc下的hibernate.properties文件中找到(可以拷贝project\etc目录下的同名文件进行修改)

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>
        <!-- 配置数据库方言,用来确定要连接的数据库 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 配置数据库驱动 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 配置数据库连接地址 -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8</property>
        <!-- 配置数据库连接用户名 -->
        <property name="hibernate.connection.username">root</property>
        <!-- 配置数据库连接密码 -->
        <property name="hibernate.connection.password">123</property>

        <!-- 自动显示相应的SQL语句 -->
        <property name="show_sql">true</property>
        <!-- 第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构 -->
        <!-- hbm2ddl:hibernate mapping to database define language -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 加入实体类的映射文件 -->
        <mapping resource="cap/model/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

4、创建实体类

User.java

package cap.model;

import java.util.Date;

public class User {
    private int id;
    private String userName;
    private String password;
    private Date birthday;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "id=" + id + ", userName=" + userName + ", password="
                + password + ", birthday=" + birthday;
    }

}

5、在实体类所在的包中创建相应的hbm文件

hbm文件用来指定实体类和数据库表的映射关系,可以在project文件夹下搜索“hbm”,然后随便拷贝一个hbm文件进行修改,例如:Account.hbm.xml

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cap.model">
    <class name="User" table="t_user">
        <id name="id">
            <generator class="native" />    <!-- 自动递增,Oracle中使用“sequence”,MySQL中使用“increment”,“native”同时兼容Oracle和MySQL -->
        </id>
        <property name="userName" type="string"/>
        <property name="password"/>
        <property name="birthday"/>
    </class>
</hibernate-mapping>

6、将hbm文件加载到hibernate.cfg.xml文件中

7、测试

Test.java

package cap.test;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import cap.model.User;

public class Test {

    @org.junit.Test
    public void test01() {
        //创建SessionFactory(SessionFactory是线程安全的)
        Configuration cfg = new Configuration().configure(); //创建Configuration对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).buildServiceRegistry();
        SessionFactory factory=cfg.buildSessionFactory(serviceRegistry);
        //创建Session
        Session session=null;

        try {
            session=factory.openSession();
            //通过Session进行数据库操作
            session.beginTransaction(); //开启事务

            User user=new User();
            user.setUserName("土豪");
            user.setPassword("123456");
            user.setBirthday(new Date());

            session.save(user);
            session.getTransaction().commit(); //提交事务
        } catch (HibernateException e) {
            e.printStackTrace();
            if(session!=null) session.getTransaction().rollback(); //事务回滚 
        } finally {
            if(session!=null) session.close();
        }
    }
}

8、结果

自动在数据库中创建t_user表并插入数据
Hibernate基础教程_第1张图片

在控制台输出相应的SQL语句
这里写图片描述

注意:在实际开发中,不会用hibernate自动生成数据库表,而是通过PD设计

Hibernate实现简单的CRUD

HibernateUtil.java

package cap.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
    private static final SessionFactory FACTORY=bulidSessionFactory();

    private static SessionFactory bulidSessionFactory() {
        Configuration cfg = new Configuration().configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).buildServiceRegistry();
        return cfg.buildSessionFactory(serviceRegistry);
    }

    public static SessionFactory getFactory() {
        return FACTORY;
    }

    public static Session openSession() {
        return FACTORY.openSession();
    }

    public static void close(Session session){
        if(session!=null){
            session.close();
        }
    }
}

TestCRUD.java

package cap.test;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.junit.Test;

import cap.model.User;
import cap.util.HibernateUtil;

public class TestCRUD {
/* * Hibernate的增(Create)删(Delete)改(Update)查(Retrieve) */
    @Test
    public void testAdd(){
        Session session=null;
        try {
            session=HibernateUtil.openSession();
            session.beginTransaction();

            User user=new User();
            user.setUserName("张洲铭");
            user.setPassword("325436");
            user.setBirthday(new Date());
            session.save(user);

            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            if(session!=null) session.getTransaction().rollback();
        } finally {
            HibernateUtil.close(session);
        }
    }

    @Test
    public void testLoad(){
        Session session=null;
        try {
            session=HibernateUtil.openSession();
            User user=(User) session.load(User.class, 2);
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.close(session);
        }
    }

    @Test
    public void testUpdate(){
        Session session=null;
        try {
            session=HibernateUtil.openSession();
            session.beginTransaction();

            User user=(User) session.load(User.class, 2);
            user.setUserName("胡杰");
            session.update(user);

            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            if(session!=null) session.getTransaction().rollback();
        } finally {
            HibernateUtil.close(session);
        }
    }

    @Test
    public void testDelete(){
        Session session=null;
        try {
            session=HibernateUtil.openSession();
            session.beginTransaction();

            User user=new User();
            user.setId(2);
            session.delete(user);

            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            if(session!=null) session.getTransaction().rollback();
        } finally {
            HibernateUtil.close(session);
        }
    }

    @Test
    public void testList(){
        Session session=null;
        try {
            session=HibernateUtil.openSession();
            @SuppressWarnings("unchecked")
            List<User> users=session.createQuery("from User").list();
            for(User user:users){
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.close(session);
        }
    }

    @Test
    public void testPager(){
        Session session=null;
        try {
            session=HibernateUtil.openSession();
            @SuppressWarnings("unchecked")
            List<User> users=session.createQuery("from User").setFirstResult(0).setMaxResults(3).list();
            for(User user:users){
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HibernateUtil.close(session);
        }
    }
}

你可能感兴趣的:(Hibernate)