<?
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.mysql.jdbc.Driver
</
property
>
<
property
name
=
"connection.url"
>
jdbc:mysql://localhost:3306/demo
</
property
>
<
property
name
=
"connection.username"
>
root
</
property
>
<
property
name
=
"connection.password"
>
root
</
property
>
<!-- SQL
方言
-->
<
property
name
=
"dialect"
>
org.hibernate.dialect.MySQLInnoDBDialect
</
property
>
<!--
实际操作数据库时是否显示
SQL -->
<
property
name
=
"show_sql"
>
true
</
property
>
<!--
将数据库
schema
的
DDL
导出到数据库
-->
<!--
property
name
=
"hibernate.hbm2ddl.auto"
>
create
</
property!--
>
<!--
以下设置对象与数据库表的映像文件
-->
......
</
session-factory
>
</
hibernate-configuration
>
|
package
org.qiujy.demo;
/**
*
User
持久化类
*
第一个
Hibernate
示例
*
@author
Administrator
*
*/
public
class
User {
private
Integer
id
;
private
String
name
;
private
Integer
age
;
public
User(){}
public
Integer getAge() {
return
age
;
}
public
void
setAge(Integer age) {
this
.
age
= age;
}
public
Integer getId() {
return
id
;
}
public
void
setId(Integer id) {
this
.
id
= id;
}
public
String getName() {
return
name
;
}
public
void
setName(String name) {
this
.
name
= name;
}
}
|
CREATE TABLE user (
id INT(11) NOT NULL auto_increment PRIMARY KEY,
name VARCHAR(100) NOT NULL default '',
age INT
);
|
<?
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
=
"org.qiujy.demo.User"
table
=
"user"
>
<
id
name
=
"id"
column
=
"id"
type
=
"java.lang.Integer"
>
<
generator
class
=
"native"
/>
</
id
>
<
property
name
=
"name"
column
=
"name"
type
=
"java.lang.String"
/>
<
property
name
=
"age"
column
=
"age"
type
=
"java.lang.Integer"
/>
</
class
>
</
hibernate-mapping
>
|
<
session-factory
>
<!--
以下设置对象与数据库表的映像文件
-->
<
mapping
resource
=
"org/qiujy/demo/User.hbm.xml"
/>
</
session-factory
>
|
package org.qiujy.common;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
* HibernateSession
工厂
*/
public class HibernateSessionFactory {
/** Hibernate
的配置文件
hibernate.cfg.xml */
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/** Session
的线程本地变量
*/
private static final ThreadLocal threadLocal = new ThreadLocal();
/** transaction
的线程本地变量
*/
private static final ThreadLocal txThreadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
private HibernateSessionFactory() {
}
/**
*
获得一个线程本地化的
Hibernate session
实例
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
*
关闭线程化的
Hibernate session
实例
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
/**
*
在本地
session
实例上开启事务
*/
public static void beginTransaction(){
Transaction tx = (Transaction)txThreadLocal.get();
if(tx == null){
tx = getSession().beginTransaction();
txThreadLocal.set(tx);
}
}
/**
*
在本地
session
实例上提交事务
*/
public static void commitTransaction(){
Transaction tx = (Transaction)txThreadLocal.get();
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.commit();
txThreadLocal.set(null);
}
}
/**
*
在本地
session
实例上回滚事务
*/
public static void rollbackTransaction(){
Transaction tx = (Transaction)txThreadLocal.get();
txThreadLocal.set(null);
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
tx.rollback();
}
}
}
|
package
org.qiujy.dao.impl;
import
org.apache.log4j.Logger;
import
org.hibernate.HibernateException;
import
org.hibernate.Session;
import
org.qiujy.common.HibernateSessionFactory;
import
org.qiujy.domain.User;
public
class
UseDaoHBImpl {
private
static
Logger
myLogger
= Logger.getLogger(UseDaoHBImpl.
class
);
/**
*
新增一个用户
*
@param
user
用户对象
*/
public
void
saveUser(User user) {
Session session = HibernateSessionFactory.getSession();
try
{
HibernateSessionFactory.beginTransaction();
session.save(user);
HibernateSessionFactory.commitTransaction();
}
catch
(HibernateException e) {
HibernateSessionFactory.rollbackTransaction();
myLogger
.error(
"
新增用户失败
"
, e);
}
finally
{
HibernateSessionFactory.closeSession();
}
}
/**
*
根据
ID
删除该用户对象
*
@param
id
用户
ID
*/
public
void
removeUserByID(
int
id){
Session session = HibernateSessionFactory.getSession();
try
{
HibernateSessionFactory.beginTransaction();
User user = (User) session.get(User.
class
,
new
Integer(id));
session.delete(user);
HibernateSessionFactory.commitTransaction();
}
catch
(HibernateException e) {
HibernateSessionFactory.rollbackTransaction();
myLogger
.error(
"
新增用户失败
"
, e);
}
finally
{
HibernateSessionFactory.closeSession();
}
}
/**
*
更新用户的信息
*
@param
user
用户对象
*/
public
void
updateUser(User user){
Session session = HibernateSessionFactory.getSession();
try
{
HibernateSessionFactory.beginTransaction();
session.saveOrUpdate(user);
HibernateSessionFactory.commitTransaction();
}
catch
(HibernateException e) {
HibernateSessionFactory.rollbackTransaction();
myLogger
.error(
"
新增用户失败
"
, e);
}
finally
{
HibernateSessionFactory.closeSession();
}
}
/**
*
根据用户
ID
查询该用户对象
*
@param
id
用户
ID
*
@return
User
查询成功返回该用户对象,否则返回
null
*/
public
User getUserByID(
int
id) {
User user =
null
;
Session session = HibernateSessionFactory.getSession();
try
{
//get
与
load
的区别
?
user = (User) session.get(User.
class
,
new
Integer(id));
}
catch
(HibernateException e) {
myLogger
.error(
"
查询用户失败
"
, e);
}
finally
{
HibernateSessionFactory.closeSession();
}
return
user;
}
public
static
void
main(String[] args) {
User user =
new
User();
user.setName(
"
张三
"
);
user.setAge(
new
Integer(26));
UseDaoHBImpl manager =
new
UseDaoHBImpl();
//
增
manager.saveUser(user);
//
查
User user1 = manager.getUserByID(1);
if
(user1 !=
null
){
user1.setName(
"
李四
"
);
//
改
manager.updateUser(user1);
//
删
//manager.removeUserByID(user1.getId().intValue());
}
}
}
|