Hibernate教程01_Hibernate的HelloWorld及基本配置

本教程开发环境为:
Myeclipse 8.5 、Hibernate3.3.2、JDK 1.6、mysql5.5

本教程每节课都附带源码,强烈大家建议配合源码学习。

本节源码:http://download.csdn.net/detail/e421083458/5253680


资源

http://www.hibernate.org
hibernate zh_CN文档
hibernate annotation references

环境准备

下载hibernate-distribution-3.3.2.GA-dist
下载hibernate-annotations-3[1].4.0.GA
注意阅读hibernate compatibility matrix(hibernate 网站download)
下载slf4jl.5.8

一共需要14个包:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
ejb3-persistence.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate-core.jar
hibernate3.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
log4j-1.2.17.jar
mysql-connector-java-5.1.23-bin.jar
slf4j-api-1.5.8.jar
slf4j-log4j12-1.5.8.jar

1.建立新java 项目,名为s2sh_Hibernate01_HelloWorld_BasicConfiguration
2.引入以上的jar包
3.src路径下创建hibernate.cfg.xml

<?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:3310/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- Enable Hibernate's automatic session conttext 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 show -->
        <property name="show_sql">true</property>
        
        <!-- Format SQL -->
        <property name="format_sql">true</property>
        
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        
        <mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>



4.在src目录下创建log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace



5.创建实体类:
package com.bjsxt.hibernate;

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;
    }
}


6.在src目录下创建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.bjsxt.hibernate.Student" table="_Student">
        <id name="id"></id>
        <property name="name"/>
        <property name="age"/>
    </class>
</hibernate-mapping>


7.创建Test.java

package com.bjsxt.hibernate;

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

public class Test {
    public static void main(String args[]){
        Student s = new Student();
        s.setId(1);
        s.setName("zhangsan");
        s.setAge(8);
        
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.save(s);
        session.getTransaction().commit();
    }
}



8.手动建立mysql数据库库名为:hibernate

9.运行测试脚本!

ok,一个最简单的Hibernate应用创建完毕!我们使用数据库查看工具查看一下,在hibernate库程序自动创建了一张名为Student的表,其字段值与实体类Student.java相对应。


总结:
1.hibernate.cfg.xml中配置如下,表明如果数据表不存在,将会自动创建数据表!
<property name="hbm2ddl.auto">update</property>
2.使用Hibernate映射实体类可以在hibernate.cfg.xml中配置<mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>

下面说一下Hibernate的另一种映射方式Annotation映射。
1.添加实体类Teacher
package com.bjsxt.hibernate;

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

@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;
    }
    
    
}




2.修改Hibernate.cfg.xml,在
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>之后添加一行
<mapping class="com.bjsxt.hibernate.Teacher"/>

3.创建测试脚本:
package com.bjsxt.hibernate;

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

public class TeacherTest {
    public static void main(String args[]){
        Teacher t = new Teacher();
        t.setId(1);
        t.setName("t1");
        t.setTitle("middle");
        
        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.save(t);
        session.getTransaction().commit();        
    }
}



我们查看到hibernate数据库中自动为我们创建了teacher表,表示测试成功!

总结:
1.
结果显示:
Hibernate:
    insert
    into
        Teacher
        (name, title, id)
    values
        (?, ?, ?)
这里是由
        <!-- Echo all executed SQL to show -->
        <property name="show_sql">true</property>
        
        <!-- Format SQL -->
        <property name="format_sql">true</property>
        
设置产生的。

2.使用Annotation方式只需要在hibernate.cfg.xml中添加
<mapping class="com.bjsxt.hibernate.Teacher"/>即可。

3.@Entity表示该对象为实体类
4.@Id表示getXxx对应的字段为主键

注意:以后所有事例都在此基础之上进行开发,重复的步骤不再提及。

你可能感兴趣的:(Hibernate教程01_Hibernate的HelloWorld及基本配置)