Hibernate 学习笔记01 --HelloWorld

来源:互联网 发布:sqlserver排序规则 编辑:程序博客网 时间:2024/05/15 23:44

1、Hibernate简介

历史,和JPA的先后时间、Annotation的提出。

2、环境准备

n   下载hibernate,如果是3.5以的话,就不需要单独下载Annotation了,否则的话需要单独下载与hibernate版本相对应的Annotation版本。

u  此次实验使用的是hibernate-release-4.2.2.Final(里面包括Annotation);

u  slf4j版本:slf4j-1.6.1

n   下载slf4j,对应于hibernate中slf4j api的版本号。

3、第一个Hibernate程序(XML版本)——HelloWorld

步骤如下:

1.         建立新的Java项目,名为:hibernate_0100_HelloWorld;

2.         学习建立User-library-hibernate,并加入相应的jar包;

a)         项目右键→ build path→ configure build path→ addlibrary;

b)        选择User-library,在其中新建library,名为为hibernate;

c)         在该library中加入hibernate所需jar包。

1.         hibernate-release-4.2.2.Final/bin/required/中所以的包;

2.         hibernate-release-4.2.2.Final/lib/optional/ehcache/下的:slf4j-api-1.6.1.jar

3.         slf4j-1.6.1目录下的:slf4j-nop-1.6.1.jar

3.         引入Oracle的JDBC驱动包;

4.         在Oracle中建立对应的数据库表

create table student(id int primary key,name varchar2(20),age int);

create table teacher(id int primary key,name varchar2(20),title varchar2(10));

5.         建立hibernate配置文件hibernate.cfg.xml(默认名称,建议不要改)

<?xmlversion='1.0'encoding='utf-8'?>

<!DOCTYPEhibernate-configurationPUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

    <session-factory>

 

        <!-- Database connection settings -->

        <propertyname="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

        <propertyname="connection.url">jdbc:oracl:thin:@192.168.0.105:1521:daocn</property>

        <propertyname="connection.username">scott</property>

        <propertyname="connection.password">tiger</property>

 

        <!-- 连接池,暂时不需要 -->

        <!-- JDBC connection pool (use the built-in) -->

        <!-- <property name="connection.pool_size">1</property> -->

 

        <!-- SQL dialect -->

        <propertyname="dialect">org.hibernate.dialect.OracleDialect</property>

 

        <!-- Enable Hibernate's automatic session context management -->

        <!-- <property name="current_session_context_class">thread</property> -->

 

        <!-- 关闭二级缓存 -->

        <!-- Disable the second-level cache -->

        <propertyname="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

 

        <!-- 回显hibernate生成的SQL语句 -->

        <!-- Echo all executed SQL tostdout -->

        <propertyname="show_sql">true</property>

 

        <!-- Drop and re-create the database schema on startup -->

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

 

        <!-- 配置“对象-表”映射的配置文件的路径,使用/” -->

        <mappingresource="com/wolex/hibernate/model/Student.hbm.xml"/>

 

    </session-factory>

</hibernate-configuration>

6.         创建Student类,包名定义为:com.wolex.hibernate.model

package com.wolex.hibernate.model;

 

public class Student {

    private int id;

    private Stringname;

    private int age;

 

    public int getId() {

        returnid;

    }

 

    public void setId(int id) {

        this.id = id;

    }

 

    public String getName() {

        returnname;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public int getAge() {

        returnage;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

}

7.         建立Student映射文件Student.hbm.xml:

<?xmlversion="1.0"?>

<!DOCTYPEhibernate-mappingPUBLIC

        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 

<hibernate-mappingpackage="com.wolex.hibernate.model">

    <classname="Student">

        <idname="id"></id>

        <propertyname="name"></property>

        <propertyname="age"></property>

    </class>

 

</hibernate-mapping>

         有几点需要注意,如果类名与对象名不一样,则需要指定类名: <class name="Student",table=”student”>;<id…>指的是表的主键,同理,如果列名和类属性名不一样,则需要指定列名:<id name=”id”,column=”id”>。

8.         将映射文件加入到hibernate.cfg.xml中(见上面hibernate.cfg.xml文件)

9.         编写测试类,注意需要导入的包:

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import com.wolex.hibernate.model.Student;

 

public class StudentTest {

    @SuppressWarnings("deprecation")

    public static void main(String[] args) {

        Student stu = new Student();

        stu.setId(1);

        stu.setName("Theresa");

        stu.setAge(24);

        Configuration cfg = new Configuration();

        SessionFactory sf = cfg.configure().buildSessionFactory();

        Session session = sf.openSession();

        session.beginTransaction();

        session.save(stu);

        session.getTransaction().commit();

        session.close();

        sf.close();

    }

}

Hibernate: insert into Student (name, age, id) values (?, ?, ?)

         调用configure()方法时,返回的实际也是Configuration对象,但为什么我们还要多此一举使用这个方法而不能直接使用“new Configuration().buildSessionFactory()”呢?以下引自Java Persistence WithHibernate中的一段:

When newConfiguration() is called, Hibernate searches for a file named hibernate.properties in the root ofthe classpath. If it’s found, all hibernate.*properties areloaded and added to the Configurationobject.

When configure()is called,Hibernate searches for a file named hibernate.cfg.xml in the root of the classpath, and an exception is thrownif it can’t be found. You don’t have to call this method if you don’t have thisconfiguration file, of course.

 

See Also: Java Persistence With Hibernate.

 

由于Hibernate默认调用的是hibernate.properties文件后hibernate.cfg.xml文件(我们使用此文件),所以以后建议都使用默认的名字而不要去修改它。如果修改为其他名字,则需要在configure()中指定文件路径,如下:

SessionFactory sessionFactory = new Configuration()

.configure("/persistence/auction.cfg.xml")

.buildSessionFactory();

可以发现,在当前使用的hibernate版本中(4.2.2,Final),Configuration类中的buildSessionFactory()方法已经不再建议使用,此处可以使用@SuppressWarnings压制警告,而Hibernate 4中推荐的使用方法请继续往下阅读。

         我们先添加配置项,把Hibernate输出的SQL语句更好看些。在hibernate.cfg.xml中添加:

<property name="format_sql">true</property>

         编写测试类,使用Hibernate 4 推荐的方法创建工厂。

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

import org.hibernate.service.ServiceRegistry;

import org.hibernate.service.ServiceRegistryBuilder;

import com.wolex.hibernate.model.Student;

 

public class StudentTest {

    public static void main(String[] args) {

        Student stu = new Student();

        stu.setId(2);

        stu.setName("Charlene");

        stu.setAge(31);

       

        Configuration cfg = new Configuration();

        cfg.configure();

        ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();

        SessionFactory sf = cfg.buildSessionFactory(sr);

       

        Session session = sf.openSession();

        session.beginTransaction();

        session.save(stu);

        session.getTransaction().commit();

        session.close();

        sf.close();

    }

}

Hibernate:

    insert

    into

        Student

        (name, age, id)

    values

        (?, ?, ?)

         修改部分highlight表示。我们查询一下数据库表:

SQL> select * from student;

        ID NAME                        AGE

---------- -------------------- ----------

         1 Theresa                      24

         2 Charlene                     31

         可见,数据已经插入了。我们以后建议使用推荐的方法。

 

Seealso:HibernateORM 新特性之Service(Registry)

 

10.      (可选)建立辅助类,参考帮助文档,此辅助类属于Singleton设计模式,可以直接取得SessionFactory而不需要实例化Configuration类。

package org.hibernate.tutorial.util;

 

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

public class HibernateUtil {

 

    private static final SessionFactory sessionFactory = buildSessionFactory();

 

    private static SessionFactory buildSessionFactory() {

        try {

            // Create the SessionFactory from hibernate.cfg.xml

            return new Configuration().configure().buildSessionFactory();

        }

        catch (Throwable ex) {

            // Make sure you log the exception, as it might be swallowed

            System.err.println("Initial SessionFactory creation failed." + ex);

            throw new ExceptionInInitializerError(ex);

        }

    }

 

    public static SessionFactory getSessionFactory() {

        return sessionFactory;

    }

}

         至此,搭建步骤已经全部完成。

4、建立Annotation版本的HelloWorld

         使用Annotation十分简单,只需要以下几个步骤:

1.         建立于表对应的类;

2.         加入相应的包,在上面我们已经添加;

3.         在类中使用Annotation注释;

4.         在hibernate.cfg.xml中添加映射配置;

首先,创建Teacher类,此处只要注意每个Annotation需要导入的包:

package com.wolex.hibernate.model;

//注意导入的包

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Basic;

 

@Entity

public class Teacher {

    private int id;

    private Stringname;

    private Stringtitle;

 

    @Id

    public int getId() {

        returnid;

    }

 

    public void setId(int id) {

        this.id = id;

    }

 

    @Basic

    // @Basic可加可不加

    public String getName() {

        returnname;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public String getTitle() {

        returntitle;

    }

 

    public void setTitle(String title) {

        this.title = title;

    }

}

         添加映射配置到hibernate.cfg.xml文件中:

……

<mapping resource="com/wolex/hibernate/model/Student.hbm.xml"/>

<mappingclass="com.wolex.hibernate.model.Teacher"/>

……

         一定要注意区分使用hibernate时与使用Annotation时添加的映射配置的写法!

         编程TeacherTest测试类:

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;//deprecated

import org.hibernate.cfg.Configuration;

import com.wolex.hibernate.model.Teacher;

 

public class TeacherTest {

    @SuppressWarnings("deprecation")

    public static void main(String[] args) {

        Teacher tea = new Teacher();

        tea.setId(1);

        tea.setName("Theresa");

        tea.setTitle("中级");

 

        Configuration cfg = newAnnotationConfiguration();

        SessionFactory sf = cfg.configure().buildSessionFactory();

        Session session = sf.openSession();

        session.beginTransaction();

        session.save(tea);

        session.getTransaction().commit();

        session.close();

        sf.close();

    }

}

Hibernate: insert into Teacher (name, title, id) values (?, ?, ?)

         使用Annotation时候,实例化的对象是AnnotationConfiguration而不是Configuration。只要hibernate.cfg.xml文件中的<mapping/>配置里写的是“class=…”则表示使用Annotation;反之,如果使用的是“resource=…”则表示使用调用xml配置文件。

         但需要特别注意的是,在Hibernate4以后,AnnotationConfiguration类已经废弃,不建议使用了!这样一来用于取得会话工厂的辅助类就简单多了,不必考虑Annotation的情况。

         还有一点需要知道:@Basic注解。这个注解是默认自动添加的,除非你添加了@Transient注解。引入一段Hibernate Reference Documentation:

In theannotations world, every non static non transient property (field or methoddepending on the access type) of an entity is considered persistent, unless youannotate it as @Transient. Not having anannotation for your property is equivalent to the appropriate @Basic annotation.

 

 

 

0 0