一起学习Spring4.0(七)Spring整合Hibernate

本节讲述Spring整合Hibernate。

准备

JBoss官网
Spring jar包:spring-framework-4.0.4.RELEASE
Hibernate jar包:hibernate-release-4.2.4.Final

根据自己Eclipse版本下载对应的插件。我的是Eclipse Kepler 4.3.2,与之对应的Hibernate Tools版本是hibernatetools-Update-4.1.2.Final_2014-03-18_15-46-19-B706
官网上写它的Requirements: Java 6 or Java 7 and Eclipse Kepler 4.3.2。

下载好hibernatetools之后将其解压,在Eclipse目录下新建文件夹MyPlugins,在MyPlugins文件夹下新建Hibernatetools文件夹,这两个文件夹的名字可以任意取,这样命名是便于识别。将解压好的hibernatetools文件夹下的features和plugins两个文件夹复制到Hibernatetools文件夹下。

在Eclipse目录下新建links文件夹,在links文件夹下新建hibernatetools.link文件,这个文件的名字可以任意取,这样取是便于识别。在hibernatetools.link文件里写入path=/MyPlugins/Hibernatetools,也可以写绝对路径,都OK的。重启Eclipse,在New-> Other 之后,输入h,看到Hibernate即为安装成功。

目标

1.有IOC容器来生成Hibernate的SessionFactory。
2.让Hibernate使用上Spring的声明式事务。

步骤

1.加入Hibernate
①.添加jar包并build path。
②.添加Hibernate配置文件:hibernate.cfg.xml。
③.编写了持久化类对应的 .hbm.xml文件。
2.加入Spring。
①.jar包。
②.加入Spring的配置文件。
3.整合。
Spring hibernate 事务的流程:
1.在方法开始之前:
①.获取Session。
②.把Session和当前线程绑定,这样就可以在Dao中使用SessionFactory的getCurrentSession()方法来获取Session了。
③.开启事务。
2.若方法正常结束,即没有出现异常,则:
①.提交事务。
②.使用当前线程绑定的Session,解除绑定。
③.关闭Session。
3.若方法出现异常,则:
①.回滚事务。
②.使和当前线程绑定的Session解除绑定。
③.关闭Session。

新建项目spring-04。
新建bin文件夹。将下载的Hibernate jar包解压缩。进入lib-> required文件夹,将全部8个必要jar包复制到bin文件夹下。
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.2.Final.jar
hibernate-core-4.2.4.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.15.0-GA.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
再添加c3p0-0.9.1.2.jar,mysql-connector-java-5.1.22-bin.jar并build path。

在该项目下新建包com.leezp.spring.hibernate.entities。在该包下新建hibernate的配置文件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
<?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>
<!-- 配置hibernate的基本属性 -->
<!-- 1.数据源需配置到IOC容器中,所以此处不再需要配置数据源。 -->
<!-- 2.关联的 .hbm.xml 也在IOC容器配置SessionFactory实例时再进行配置。 -->
<!-- 3.配置hibernate的基本属性:方言,SQL显示及格式化,生成数据表的策略及二级缓存等。 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 是否显示所生成 SQL 语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 是否格式化生成的 SQL 语句,增加可读性,不然全挤在一行 -->
<property name="hibernate.format_sql">true</property>
<!--hibernate.hbm2ddl.auto 用于 自动创建|更新|验证数据库表结构。 create | update | validate
| create-drop -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- create: 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。 -->
<!-- create-drop : 每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。 -->
<!-- update: 最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据
model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等
应用第一次运行起来后才会。 -->
<!-- validate : 每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。 -->
<!-- 配置hibernate 二级缓存相关的属性 -->
</session-factory>
</hibernate-configuration>

在该包下新建Account.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
25
26
27
28
29
30
31
32
33
34
35
package com.leezp.spring.hibernate.entities;
public class Account {
private Integer id;
private String username;
private int balance;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}

在该包下新建Book.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.leezp.spring.hibernate.entities;
public class Book {
private Integer id;
private String bookName;
private String isbn;
private int price;
private int stock;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}

鼠标单击包,右键new-> Other…-> Hibernate XML Mapping file(hbm.xml),如下图。

点击Next,点Finish。发现包下多了两个文件,这是Hibernate Tools为我们自动生成的hibernate Mapping文件。

打开Book.hbm.xml。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-9-11 10:14:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.leezp.spring.hibernate.entities.Account" table="ACCOUNT">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="balance" type="int">
<column name="BALANCE" />
</property>
</class>
</hibernate-mapping>

打开Account.hbm.xml。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-9-11 10:14:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.leezp.spring.hibernate.entities.Account" table="ACCOUNT">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="balance" type="int">
<column name="BALANCE" />
</property>
</class>
</hibernate-mapping>

修改Account.hbm.xml文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-9-11 10:14:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.leezp.spring.hibernate.entities.Account" table="SH_ACCOUNT">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<!-- 生成主键的方式,如有疑问见最后的参考文献:Hibernate 的<generator class="native"></generator>的不同属性含义 -->
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="balance" type="int">
<column name="BALANCE" />
</property>
</class>
</hibernate-mapping>

修改Book.hbm.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
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-9-11 10:14:02 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.leezp.spring.hibernate.entities.Book" table="SH_BOOK">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="bookName" type="java.lang.String">
<column name="BOOK_NAME" />
</property>
<property name="isbn" type="java.lang.String">
<column name="ISBN" />
</property>
<property name="price" type="int">
<column name="PRICE" />
</property>
<property name="stock" type="int">
<column name="STOCK" />
</property>
</class>
</hibernate-mapping>

新建属性文件db.properties。

1
2
3
4
5
6
7
jdbc.user=root
jdbc.password=root
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring_hibernate
jdbc.initPoolSize=5
jdbc.maxPoolSize=10

spring4-required jar包
将下载好的spring4-required jar包里的所有jar文件复制到bin文件夹下并且build path。

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
新建Spring的配置文件applicationContext.xml。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 1.配置数据源 -->
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 2.配置Hibernate 的 SessionFactory实例 :通过Spring 提供的LocalSessionFactoryBean进行配置 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 配置数据源属性 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置hibernate配置文件的位置及名称 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- 配置hibernate映射文件的位置及名称,可以使用通配符 -->
<property name="mappingLocations"
value="classpath:com/leezp/spring/hibernate/entities/*.hbm.xml"></property>
</bean>
<!-- 3.配置Spring的声明式事务 -->
</beans>

在mysql中新建数据库spring_hibernate。不创建任何表。

新建包com.leezp.spring.hibernate.test。在该包下新建测试类SpringHibernateTest.java。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringHibernateTest {
private ApplicationContext ctx = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testDataSource() throws SQLException {
DataSource dataSource=ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}
}

运行上面的测试类。在数据库里刷新,发现为我们建立好了数据表。

新建包com.leezp.spring.hibernate.dao。在该包下新建接口BookShopDao.java。

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.leezp.spring.hibernate.dao;
public interface BookShopDao {
//根据书号获取书的单价
public int findBookPriceByIsbn(String isbn);
//更新书的库存,使书号对应的库存 -1
public void updateBookStock(String isbn);
//更新用户的账户余额:使username的balance - price
public void updateUserAccount(String username,int price);
}

新建包com.leezp.spring.hibernate.dao.impl。在该包下新建接口BookShopDao.java的实现类BookShopDaoImpl.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.leezp.spring.hibernate.dao.impl;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.leezp.spring.hibernate.dao.BookShopDao;
import com.leezp.spring.hibernate.exception.BookStockException;
import com.leezp.spring.hibernate.exception.UserAccountException;
@Repository
public class BookShopDaoImpl implements BookShopDao {
// 线程安全的
@Autowired
private SessionFactory sessionFactory;
// HibernateTemplate 和 HibernateDaoSupport是Spring的API,
// 不推荐使用,因为这样会导致Dao和Spring的API进行耦合,可移植性变差,建议原生Hibernate接口。
// private HibernateTemplate hibernateTemplate;
//
// public class BookShopDaoImpl extends HibernateDaoSupport implements
// BookShopDao {
// Hibernate 获取跟当前线程绑定的Session
private Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public int findBookPriceByIsbn(String isbn) {
String hql = " select b.price from Book b where b.isbn = ? ";
// import org.hibernate.Query;
Query query = getSession().createQuery(hql).setString(0, isbn);
return (Integer) query.uniqueResult();
}
@Override
public void updateBookStock(String isbn) {
// 验证书的库存是否充足
String hql2 = " select b.stock from Book b where b.isbn= ? ";
int stock = (int) getSession().createQuery(hql2).setString(0, isbn)
.uniqueResult();
if (stock == 0) {
throw new BookStockException("库存不足!");
}
String hql = " update Book b set b.stock=b.stock -1 where b.isbn= ? ";
getSession().createQuery(hql).setString(0, isbn).executeUpdate();
}
@Override
public void updateUserAccount(String username, int price) {
// 验证余额是否足够
String hql2 = " select a.balance from Account a where a.username=? ";
int balance = (int) getSession().createQuery(hql2)
.setString(0, username).uniqueResult();
if (balance < price) {
throw new UserAccountException("余额不足!");
}
String hql = " update Account a set a.balance=a.balance-? where a.username=? ";
getSession().createQuery(hql).setInteger(0, price)
.setString(1, username).executeUpdate();
}
}

新建包com.leezp.spring.hibernate.service。
新建接口BookShopService.java。

1
2
3
4
5
6
package com.leezp.spring.hibernate.service;
public interface BookShopService {
public void purchase(String username, String isbn);
}

新建接口Cashier.java。

1
2
3
4
5
6
7
8
package com.leezp.spring.hibernate.service;
import java.util.List;
public interface Cashier {
public void checkout(String username, List<String> isbns);
}

新建包com.leezp.spring.hibernate.service.impl。
在该包下新建接口BookShopService.java的实现类BookShopServiceimpl.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.leezp.spring.hibernate.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.leezp.spring.hibernate.dao.BookShopDao;
import com.leezp.spring.hibernate.service.BookShopService;
@Service
public class BookShopServiceImpl implements BookShopService {
@Autowired
private BookShopDao bookShopDao;
/**
* Spring hibernate 事务的流程:
*
* 1.在方法开始之前
*
* ①.获取Session
*
* ②.把Session和当前线程绑定,这样就可以在Dao中使用SessionFactory的
* getCurrentSession()方法来获取Session了。
*
* ③.开启事务
*
* 2.若方法正常结束,即没有出现异常,则
*
* ①.提交事务
*
* ②.使用当前线程绑定的Session,解除绑定
*
* ③.关闭Session
*
* 3.若方法出现异常,则:
*
* ①.回滚事务
*
* ②.使和当前线程绑定的Session解除绑定
*
* ③.关闭Session
*/
@Override
public void purchase(String username, String isbn) {
int price = bookShopDao.findBookPriceByIsbn(isbn);
bookShopDao.updateBookStock(isbn);
bookShopDao.updateUserAccount(username, price);
}
}

在该包下新建接口Cashier.java的实现类CashierImpl.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
package com.leezp.spring.hibernate.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.leezp.spring.hibernate.service.BookShopService;
import com.leezp.spring.hibernate.service.Cashier;
@Service
public class CashierImpl implements Cashier {
@Autowired
private BookShopService bookShopService;
@Override
public void checkout(String username, List<String> isbns) {
for (String isbn : isbns) {
bookShopService.purchase(username, isbn);
}
}
}

新建包com.leezp.spring.hibernate.exception。
在该包下新建异常类BookStockException.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.leezp.spring.hibernate.exception;
//继承RuntimeException,Generate Constructors from SuperClass添加构造器
// Add default serial version ID
public class BookStockException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public BookStockException() {
super();
// TODO Auto-generated constructor stub
}
public BookStockException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public BookStockException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public BookStockException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public BookStockException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}

在该包下新建异常类UserAccountException.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
25
26
27
28
29
30
31
32
33
34
35
36
package com.leezp.spring.hibernate.exception;
public class UserAccountException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public UserAccountException() {
super();
// TODO Auto-generated constructor stub
}
public UserAccountException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public UserAccountException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public UserAccountException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public UserAccountException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}

向Spring配置文件applicationContext.xml中添加:

1
2
<!-- 使用注解要配置自动扫描的包 -->
<context:component-scan base-package="com.leezp.spring.hibernate"></context:component-scan>

修改测试类SpringHibernateTest.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
25
26
27
28
29
30
31
32
33
34
package com.leezp.spring.hibernate.test;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.leezp.spring.hibernate.service.BookShopService;
public class SpringHibernateTest {
private ApplicationContext ctx = null;
private BookShopService bookShopService = null;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
bookShopService = ctx.getBean(BookShopService.class);
}
@Test
public void testBookShopService() {
bookShopService.purchase("aa", "1001");
}
@Test
public void testDataSource() throws SQLException {
DataSource dataSource = ctx.getBean(DataSource.class);
System.out.println(dataSource.getConnection());
}
}

获取数据库spring_hibernate

在测试类SpringHibernateTest.java中运行testBookShopService方法进行测试。

获取源代码

补充说明

Hibernate的配置文件hibernate.cfg.xml不是必须的,可以在Spring配置文件applicationContext.xml里通过配置来取代它。但是不建议这么使用,因为在Spring配置文件中配置Hibernate提示功能不是很好,而且配置Hibernate插件时不如在hibernate配置文件中配置方便。具体操作根据项目需求来定。

修改applicationContext.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 使用注解要配置自动扫描的包 -->
<context:component-scan base-package="com.leezp.spring.hibernate"></context:component-scan>
<!-- 1.配置数据源 -->
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:db.properties" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>
<!-- 2.配置Hibernate 的 SessionFactory实例 :通过Spring 提供的LocalSessionFactoryBean进行配置 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 配置数据源属性 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置hibernate配置文件的位置及名称 -->
<!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> -->
<!-- 使用hibernateProperties属性来配置Hibernate原生的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<!-- 测试方法:将这里的true改成false,若不显示sql语句(之前显示sql语句),证明配置生效 -->
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 配置hibernate映射文件的位置及名称,可以使用通配符 -->
<property name="mappingLocations"
value="classpath:com/leezp/spring/hibernate/entities/*.hbm.xml"></property>
</bean>
<!-- 3.配置Spring的声明式事务 -->
<!-- ①.配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- ②.配置事务属性,需要事务管理器 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- ③.配置事务切点,并把切点和事务属性关联起来 -->
<aop:config>
<!-- com.leezp.spring.hibernate.service包下的所有类,所有方法,参数值任意 -->
<aop:pointcut
expression="execution(* com.leezp.spring.hibernate.service.*.*(..))"
id="txPointCut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
</aop:config>
</beans>

获取源代码

参考文献
hibernate中的映射文件xxx.hbm.xml详解总结
xxx.hbm.xml文件配置详解,适合保存。
Hibernate 的的不同属性含义

版权声明:本文为博主原创文章,转载请注明出处 Leezp’s Blog

点击按钮打赏作者!