Hibernate系列之基本配置

一、概述

  Hibernate是一个开放源码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使我们可以使用对象的编程思维来操作数据库。

二、配置准备

  IDE:Eclipse

  下载Jar包:

  

三、配置步骤

  1、创建新的Java项目

  

  2、建立用户库-hibernate,引入相应的jar包

  • 项目右键-build path->configue build path->add library
  • 选择user library,在其中新建library,命名为Hibernate
  • 在该library中加入Hibernate所需要的jar包

   

  3、引入mysql的驱动包

  4、在mysql中建立相应的数据库以及表

  5、建立Hibernate配置文件hibernate.cfg.xml

  这部分可以从参考文档中拷贝,然后修改对应的数据库连接。eg:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">281889</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property> -->

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <!--  <property name="current_session_context_class">thread</property> -->

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
        <mapping resource="com/test/demo/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

  6、建立一个类

  这个类表示我们想要存储在数据库的事件。这个类使用JavaBean标准命getter和setter方法以及字段。虽然这是推荐的设计,但它不是必需的。Hibernate也可以直接访问字段,访问器方法的好处是重构的鲁棒性。eg:

package com.test.demo;

public class Student
{
    private int id;
    private String name;
    private int age;
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    
}

  7、建立Student的映射文件Student.hbm.xml

  Hibernate需要知道怎样去加载和存储持久化类的对象。这正是Hibernate映射文件发挥作用的地方。映射文件告诉Hibernate它,应该访问数据库(database)里面的哪个表(table)及应该使用表里面的哪些字段(column)。这部分可以参考文档。

<?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="com.test.demo">

    <class name="Student">
        <id name="id"></id>
        
        <property name="name"></property>
        
        <property name="age"></property>
    </class>
</hibernate-mapping>

  8、将映射文件加入到Hibernate.cfg.xml文件中,参考文档

 <mapping resource="com/test/demo/Student.hbm.xml"/>

  9、写测试类StudentTest,对student对象进行直接的存储测试

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class StudentTest
{
    public static void main(String[] args)
    {
        Student s = new Student();
        s.setId(2);
        s.setName("s2");
        s.setAge(25);
        
        Configuration cfg=new Configuration();
        SessionFactory sf=cfg.configure().buildSessionFactory();
        Session session=sf.openSession();
        session.beginTransaction();
        session.save(s);
        
        //提交事物
        session.getTransaction().commit();
        
        session.close();
        sf.close();
    }
}

  执行上述测试程序,结果如下:

  

四、注释版本的配置步骤

  1、创建Teacher表,并创建相应字段

 

  2、在hibernate lib中加入annotation的jar包

  

  3、创建Teacher类,并参考文档生成相应的注解

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Teacher
{
    private int id;
    private String name;
    private String title;
    
    @Id
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getTitle()
    {
        return title;
    }
    public void setTitle(String title)
    {
        this.title = title;
    }
    
    
}

  4、在hibernate.cfg.xml文档中建立映射

<mapping class="com.test.demo.Teacher"/>

   5、写测试类TeacherTest,对Teacher对象进行存储测试

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class TeacherTest
{

    public static void main(String[] args)
    {
        Teacher t=new Teacher();
        
        t.setId(2);
        t.setName("t2");
        t.setTitle("初级");
        Configuration cfg=new AnnotationConfiguration();
        SessionFactory sf=cfg.configure().buildSessionFactory();
        Session session=sf.openSession();
        session.beginTransaction();
        session.save(t);
        //提交事物
        session.getTransaction().commit();
        session.close();
        sf.close();
    }
}

  运行上述程序,结果为:

  

五、配置细节

  1、配置hibernate.hbm2ddl.auto

 <property name="hbm2ddl.auto">update</property>

  这个属性标签中有四个参数可以写,分别是validate|update|create|create drop,对数据库中进行不同的操作。

  validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但会插入新值

  update:第一次加载hibernate时根据model类自动建立表的结构,以后加载hibernate时根据model类自动更新表结构

  create:每一次加载hibernate都会删除上一次生成的表,然后根据你的model类重新生成新表

  create drop:每次加载hibernate时根据model类生成表,但是sessionFactor一关闭,表就自动删除

  2、表名和类名不同,对表名进行配置

  在类定义之前加上@Table(name="表名")

@Entity
@Table(name="People")
public class Person
{
    private Long id;
    private int age;
    private String name;

  这里类名是Person,@Table注释内为People,运行后,数据库内表名为:

  

  3、字段名和属性名不同时

  在属性get方法方法前面加上@Column(name="字段名")

  public void setAge(int age)
    {
        this.age = age;
    }
    @Column(name="PersonName")
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }

  这里属性名是name,@Column注释为PeopleName,运行后该字段名为:

  

  

  4、设置字段不保存在数据库中

  在该属性的get方法前面加上@Transient注释

  5、映射日期和时间类型,指定时间精度

   Annotation:@Temporal(参数) 参数有3种 只显示时间,只显示日期,时间日期都显示

  //@Temporal(TemporalType.DATE)  只显示日期

  //@Temporal(TemporalType.TIME)  只显示时间

 //@Temporal(TemporalType.TIMESTAMP)  显示日期与时间

 

posted @ 2015-09-06 14:26  温布利往事  阅读(8692)  评论(3编辑  收藏  举报