hibernate基础之设置

来源:互联网 发布:tw域名注册 编辑:程序博客网 时间:2024/06/07 13:22

从今天起,我将陆续写关于hibernate的一些基础知识。一是为了将自己学到的知识做一个记录,二是希望顺便能帮助一些人吧。

开发环境

        hibernate-4.2.0.Final

        mysql版本:6.0


        hibernate 是一个 ORM 的框架,它的主要功能也是将我们的 javaBean 保存到数据库中。所以,我们至少需要有一个 java 类。然后需要一个配置文件,它的作用是让hibernate知道我们的 javaBean 和 数据库的 table 有什么关系,比如有一个 Student 类,想把它保存到数据库中的 StudentInfo 表中;想把 Student 类的 name属性保存到 StudentInfo 表中的 stuName 字段中等等,这些都需要一个配置文件来配置(当然,我使用的是 annotation 方式,直接就把配置写在 java 类中,就不需要这个配置文件)。最后,我们还需要一个全局的配置文件,配置全局的信息,比如使用的数据库、数据库的用户名和密码等等。

        新建一个 java project,在 src 下创建名为hibernate.cfg.xml 的全局配置文件。

全局配置文件

<?xml version='1.0' encoding='utf-8'?><!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>        <!--我使用的是 mysql 数据库-->        <!-- jdbc 驱动类-->        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <!--数据库连接的url            hibernatedemo 为数据库名称        -->        <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedemo?useUnicode=true&amp;characterEncoding=UTF-8</property>        <!--数据库用户名-->        <property name="connection.username">root</property>        <!--数据库密码-->              <property name="connection.password">123</property>        <!--数据库连接池,这个是hibernate的,但是真正开发中是不会使用它的            都会使用第三方的连接池c3p0等。我把这个连接池给注释了        -->        <!--        <property name="connection.pool_size">1</property>         -->        <!-- SQL 方言,每个数据库都是有差异的,使用的 SQL 也会不太一样,hibernate 根据方言生成不同的 SQL -->        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <!-- 这是 hibernate 获取 session 的一种方法,等后面用到的时候我再说,先注释        <property name="current_session_context_class">thread</property>         -->        <!-- hibernate的一个缓存,设置成不使用缓存  -->        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>        <!-- 显示 hibernate 的 sql,设置成显示 -->        <property name="show_sql">true</property>        <!--             hibernate自动执行 DDL            create:hibernate 每次都会帮生成 java 类所对应的 table            update:hibernate 每次看 java 类所对应的表有没有更新,如有更新就会更新 table        -->        <property name="hbm2ddl.auto">create</property>    </session-factory></hibernate-configuration>

java 类

package demo.model;import java.io.Serializable;import java.util.Date;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;@Entity@Table(name="studentinfo")public class Student implements Serializable {    private static final long serialVersionUID = 1L;    /**     * ID     */    private Integer id;        /**     * 学号     */    private String studentNo;        /**     * 姓名     */    private String name;        /**     * 生日     */    private Date brithday;    @Id    @GeneratedValue(strategy=GenerationType.AUTO)    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getStudentNo() {        return studentNo;    }    public void setStudentNo(String studentNo) {        this.studentNo = studentNo;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @Temporal(TemporalType.DATE)    public Date getBrithday() {        return brithday;    }    public void setBrithday(Date brithday) {        this.brithday = brithday;    }}

        将 Student 类将入到 全局配置文件中。在 <property name="hbm2ddl.auto">create</property> 下面加上

        <!-- 实体类映射 -->
        <mapping class="demo.model.Student"/>

类所对应的配置文件

        因为我使用的是 annotation (注解) 的方式,所以也就不需要这个配置文件了。

Hibernate 辅助类

package demo.utils;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {    private static SessionFactory sessionFactory = null;        private HibernateUtil() {}        @SuppressWarnings("deprecation")    public static SessionFactory getSessionFactory() {        if(sessionFactory==null) {            sessionFactory = new Configuration().configure().buildSessionFactory();        }        return sessionFactory;    }}

StudentTest 测试类

package demo.test;import java.util.Date;import org.hibernate.Session;import demo.model.Student;import demo.utils.HibernateUtil;public class StudentTest {    public static void main(String[] args) {        testSave();    }        public static void testSave() {        Student student = new Student();        student.setName("小强");        student.setStudentNo("001");        student.setBrithday(new Date());        Session session = HibernateUtil.getSessionFactory().openSession();    //打开 session        try {            session.beginTransaction();    //开启 事务            session.save(student);    //保存实体            session.getTransaction().commit();    //提交事务        } catch (Exception e) {            session.getTransaction().rollback();    //事务回滚            System.out.println(e);        } finally {            session.close();    //关闭 session        }    }}

Hibernate相关jar

        1、将下载的 hibernate 压缩包解压,然后将 lib \ required 文件夹下的 jar 加入到项目中

        2、将 project \ etc 文件夹下的 log4j.properties 文件加入到 src 下

        3、将 mysql-jdbc 驱动包加入到项目中。下载

运行测试类

        运行 StudentTest 的 main 方法。

        控制抬信息:

        ........

        Hibernate: drop table if exists studentinfo
        Hibernate: create table studentinfo (id integer not null auto_increment, brithday date, name varchar(255), studentNo varchar(255), primary key (id))
                2013-6-2 14:50:08 org.hibernate.tool.hbm2ddl.SchemaExport execute
        INFO: HHH000230: Schema export complete
        Hibernate: insert into studentinfo (brithday, name, studentNo) values (?, ?, ?)

        Hibernate 帮我们生成了创建表 studentinfo 的 sql,并插入了数据。

        查看数据库: SELECT * FROM studentinfo

       

        OK,hibernate 的第一个小例子运行成功。


原创粉丝点击