hibernate入门实例

来源:互联网 发布:显示温度的软件 编辑:程序博客网 时间:2024/06/10 02:40

 

1. 环境配置

1.1 hiberante环境配置

hibernate可实现面向对象的数据存储。hibernate的官网:http://hibernate.org/ 官网上选择hibernate ORM,可以下载最新的hibernate,还有配套的document教程 http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/ 。下载到的hibernate文件夹中有document文档(hibernate\documentation\manual\en-US\html_single)。发现hibernate4.3.1的文件夹中的文档和网站上提供的答案不太一样,官网的文档更详细一些,还附有toturial的源代码。

打开eclipse->windows->preferences->java->build path->user libraries,点击new,新建一个library,可取名为hibernate。点击Add JARs,选择hibernate->lib->required中的所有jar文件,另外还需要加上数据库的connector文件。因为使用的是mysql,所以我这里用到的mysql-connector-java的jar文件。这个jar文件从哪里得到呢?安装mysql服务器产生的文件夹里面是没有jar文件的。我们需要另下载一个MySQL的JDBC jar包。可以从mysql的官网上下载:http://dev.mysql.com/downloads/connector/j/ 下载后得到一个msi文件,双击及可安装。安装后,默认会产生文件夹C:\Program Files (x86)\MySQL\MySQL Connector J ,这里就有一个mysql-connector-java-x.x.x-bin.jar包了。

1.2 mysql数据库配置

安装mysql服务器,设置root的密码为root。启动mysql服务器,新建数据库hibernate,并新建表student。

?
1
2
3
4
5
# mysql -uroot -proot
> createdatabase hiberante;
> use hibernate;
> createtable student(id int primary key, name varchar(20), age int);
> quit;

2. 实例代码

新建一个java工程,假设取名为HibernateHelloWorld。在src下新那一个package,可取名为com.sun.hibernate.model

2.1 类代码

新建一个简单的类,放在com.sun.hibernate.model包下。内容如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.sun.hibernate.model;
 
public class Student {
    privateint id;
    privateString name;
    privateint age;
 
    publicint getId() {
        returnid;
    }
    publicvoid setId(intid) {
        this.id = id;
    }
    publicString getName() {
        returnname;
    }
    publicvoid setName(String name) {
        this.name = name;
    }
    publicint getAge() {
        returnage;
    }
    publicvoid setAge(intage) {
        this.age = age;
    }
 
}

2.2 配置hibernate配置文件

hibernate\projec\etc中的hiberante.cfg.xml可以作为hibernate的配置文档,或者可使用hibernate\documentation\manual\en-US\html_single\index.html作为模板。在src文件夹下新建一个文件,并命名为hibernate.cfg.xml。(不可命名为其他文件名)最基础的配置文件可参考如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?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>
     
    <!-- 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">root</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>
         
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
         
    <!-- Enable Hibernate's automatic session context management -->
    <!--<property name="current_session_context_class">thread</property>-->
         
    <!-- Drop and re-create the database schema on startup -->
    <!-- <property name="hbm2ddl.auto">create</property> -->
         
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
     
    <mapping resource="com/sun/hibernate/model/Student.hbm.xml"/>
         
    </session-factory>
</hibernate-configuration>

mapping resource处的值可根据包名和类名做修改。若类名为Student,则此处的类配置文件必为:Student.hbm.xml。

2.3 类mapping文件

新建一个文件,命名为Student.hbm.xml,放在com.sun.hibernate.model包下。内容如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 
<hibernate-mappingpackage="com.sun.hibernate.model">
    <classname="Student">
        <id name="id"></id>
        <property name="name"></property>
        <property name="age"></property>
    </class>
</hibernate-mapping>

注意文件开始处的配置,此处与hibernate.cfg.xml不一样。如果配置的与hiberante.cfg.xml一样,运行时会提示错误:“文档根元素 "hibernate-mapping" 必须匹配 DOCTYPE 根 "hibernate-configuration"  ”

2.4 StudentTest测试类

新增Student.java的junit测试类StudentTest.java,放在com.sun.hibernate.model包下代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.sun.hibernate.model;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class StudentTest {
 
    publicstatic void main(String[] args){
        Student s =new Student();
        s.setId(1);
        s.setName("s1");
        s.setAge(1);
         
        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();    
    }
}

2.5. 运行结果

运行StudentTest.java这个类,虽然提示输入成功。去数据库查询后,可发现数据已存储到student数据表中。虽然myeclipse会提示buildSessionFactory()这个函数被deprecated,但实际上程序还是可以运行成功的。

3. 使用annotation

因为使用annotation比较方便,使用annotation就可以不用写XXX.hbm.xml文件了。

3.1 新建类

敲@后应该出现提示的,如果没有出现,在Window->Preferences->Java->Editor->Content Assist,在Auto activation triggers forJava中增加@即可。Teacher.java类与Student类内容基本相同,以@开头的内容为annotation。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.sun.hibernate.model;
 
import javax.persistence.Entity;
import javax.persistence.Id;
 
<span style="color: rgb(0, 0, 0);">@Entity</span>
public class Teacher {
     
    <span style="color: rgb(0, 0, 0);">@Id</span>
    publicint getId() {
        returnid;
    }
    publicvoid setId(intid) {
        this.id = id;
    }
    publicString getName() {
        returnname;
    }
    publicvoid setName(String name) {
        this.name = name;
    }
    publicint getAge() {
        returnage;
    }
    publicvoid setAge(intage) {
        this.age = age;
    }
    publicint getTitle() {
        returntitle;
    }
    publicvoid setTitle(String title) {
        this.title = title;
    }
     
    privateint id;
    privateString name;
    privateint age;
    privateString title;
     
}

3.2 更新hibernate.cfg.xml

在原hibernate.cfg.xml文件的mapping以下标红内容。

?
1
2
3
<mapping resource="com/sun/hibernate/model/Student.hbm.xml"/>
<span style="color: rgb(255, 0, 0);"><mappingclass="com.sun.hiberante.model.Teacher"/>
</span>

4.3 新建TeacherTest.java类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
 
public class TeacherTest {
 
    publicstatic void main(String[] args){
        Teacher t =new Teacher();
        t.setId(1);
        t.setName("t1");
        t.setAge(1);
        t.setTitle("middel");
         
        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();
    }
 
}

 3.3 运行

在数据库中新建teacher数据表:

?
1
2
3
4
# mysql -uroot -proot
> use hibernate;
> create table teacher(idint primary key, name varchar(20), ageint, title varchar(20));
> quit;

运行TeacherTest.java这个类,虽然提示输入成功。去数据库查询后,可发现数据已存储到teacher数据表中。

分类: java

//StudentTest.java

package com.sun.hibernate.model;

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(2);

        

        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();    

    }

}


src\com\sun\hibernate\model\Student.hbm.xml

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

<hibernate-mapping>
    <class name="com.sun.hibernate.model.Student"  table="student">
        <id name="id" column="id"> 
            <generator class="native"/> 
        </id> 
        <property name="name" column="name"></property>
        <property name="age"  column="age"></property>
    </class>
</hibernate-mapping>


src\hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC 
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
 
<hibernate-configuration> 
    <session-factory > 
        <!-- mysql数据库驱动 --> 
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
        <!-- mysql数据库名称 --> 
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property> 
        <!-- 数据库的登陆用户名 --> 
        <property name="hibernate.connection.username">root</property> 
        <!-- 数据库的登陆密码 --> 
        <property name="hibernate.connection.password"></property> 
        <!-- 方言:为每一种数据库提供适配器,方便转换 --> 
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
         
  <mapping resource="com/sun/hibernate/model/Student.hbm.xml"/> 
    </session-factory> 
</hibernate-configuration> 


java web整合开发王者归来源代码

完整的源代码,包括每个案例。使用方法是找到对应章目名称的压缩包,去里面对应工程下找案例中名称的源码文件。比如第四周Struts框架篇的Struts 1.X概述,就去找“Struts"压缩包。
本资料共包含以下附件:

源代码.7z

http://down.51cto.com/data/845259


0 0