How to use Hibernate - XML Configuration

使用Hibernate进行开发时,有两种方式,一种是使用XML配置,这是比较传统的方式。另一种是使用注解,这是JPA标准所支持的。今天介绍得是使用XML配置的方式使用Hibernate。具体使用方式如下:

1.下载Hibernate 包

http://hibernate.org/orm/

hibernate-release-4.3.10.Final.zip

2.新建工程

How to use Hibernate - XML Configuration_第1张图片

这里的Reference Librarys  分为两部分,一部分是Hibernate 的required里面的jar包,一部分是连接sqlserver 2012数据库的jar包(sqljdbc4.jar)

3.model类

package com.wicresoft.model;

public class Student {

	private int id;
	private int age;
	private String name;
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
4.student.hbm.xml

<?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.wicresoft.model">
	<class name="Student" table="student">
		<id name="id" column="ID">
			<generator class="identity"/>
		</id>
		<property name="age" />
		<property name="name" />
	</class>
</hibernate-mapping>
5.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>
		<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
		<property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=HibernateDB</property>
		<property name="connection.username">sa</property>
		<property name="connection.password">1234</property>
		<!-- JDBC connection pool (use the built-in) -->
		<property name="connection.pool_size">1</property>
		<!-- SQLDialect -->
		<property name="dialect">org.hibernate.dialect.SQLServerDialect</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>
		<!-- 显示SQL语句 -->
		<property name="show_sql">true</property>
		<!-- 格式化输出SQL语句 -->
		<property name="format_sql">true</property>
		<!-- validate 加载hibernate时,验证创建数据库表结构 -->
		<!-- create 每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。 -->
		<!-- create-drop 加载hibernate时创建,退出是删除表结构 -->
		<!-- update 加载hibernate自动更新数据库结构 -->
		<!--  
		<property name="hbm2ddl.auto">create</property>
		<property name="myeclipse.connection.profile"></property>
		-->
		<!-- hibernate与数据库的对象关系映射文件**.hbm.xml -->
		<mapping resource="com/wicresoft/model/Student.hbm.xml" />
		<!-- 使用annotion注解时,hibernate与数据库对象关系映射表示 -->
		<mapping class="com.wicresoft.model.Teacher" />
		
		<!-- 推荐使用annotion注解来表示映射关系 -->
		<!--  
		<mapping class="com.lsj.hibernate.model.Teacher" />
		-->
	</session-factory>
</hibernate-configuration>
6.Test

package com.wicresoft.test;

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

import com.wicresoft.model.Student;

public class StudentTest {

	public static void main(String[] args) {
		Student s = new Student();
		//s.setId(3);
		s.setAge(22);
		s.setName("AAA");

		Configuration cfg = new Configuration();
		// 读取hibernate.cfg.xml中的配置
		cfg.configure();
		// 获取SessionFactory
		SessionFactory sf = cfg.buildSessionFactory();
		// 获取Session
		Session session = sf.openSession();
		// 开启事务
		session.beginTransaction();
		// 保存
		session.save(s);
		// 提交事务
		session.getTransaction().commit();
		// 关闭连接
		session.close();
		sf.close();
	}
}
7.输出

How to use Hibernate - XML Configuration_第2张图片
Hibernate会输出sql语句在这里,参数被问好替代了。

7.建表sql

USE [master] 
GO 
IF EXISTS(SELECT 1 FROM sysdatabases WHERE NAME=N'HibernateDB') 
BEGIN 
	DROP DATABASE HibernateDB --如果数据库存在先删掉数据库 
END 
GO 
CREATE DATABASE HibernateDB 
ON 
PRIMARY --创建主数据库文件 
( 
	NAME = 'HibernateDB', 
	FILENAME = 'E:\MySpace\HibernateDB\HibernateDB.dbf', 
	SIZE = 5MB, 
	MaxSize = 20MB, 
	FileGrowth = 1MB 
) 
LOG ON --创建日志文件 
( 
	NAME = 'HibernateDBLog', 
	FileName = 'E:\MySpace\HibernateDB\HibernateDB.ldf', 
	Size = 2MB, 
	MaxSize = 20MB, 
	FileGrowth = 1MB 
) 
GO 

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'STUDENT') AND type in (N'U')) 
BEGIN 
CREATE TABLE STUDENT 
( 
	ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
	AGE INT NULL,
	NAME NVARCHAR(50) NULL
)
END

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'TEACHER') AND type in (N'U')) 
BEGIN 
CREATE TABLE TEACHER 
( 
	ID INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
	NAME NVARCHAR(50) NULL,
	TITLE NVARCHAR(50) NULL
)
END

INSERT INTO STUDENT VALUES(20,'TOM');
INSERT INTO STUDENT VALUES(21,'HEY');

INSERT INTO TEACHER VALUES('T1','L1');
INSERT INTO TEACHER VALUES('T2','L2');

SELECT * FROM STUDENT;
SELECT * FROM TEACHER;

DROP TABLE TEACHER;
DROP TABLE STUDENT;



你可能感兴趣的:(Hibernate,xml,orm)