spring(13) spring整合hibernate

1. Spring整合Hibernate,整合什么?

1). IOC容器来管理Hibernate的SessionFactory

2). Hibernate使用上Spring的声明式事务

 

2.整合步骤

1). 加入hibernate

(1)加入jar

(2)配置hibernate.cfg.xml

(3)编写持久化类及.hbm.xml

2). 加入Spring

(1)加入jar包

(2)加入spring的配置文件

3). 整合


Hibernate.cfg.xml配置如下:

<!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>
		<!-- 配置hibernate的基本属性 -->
		<!-- 1.数据源配置到IOC容器中,所以此处不再需要配置数据源 -->
		<!-- 2.关联的*.hbm.xml也在IOC容器配置SessionFactory实例时进行配置 -->
		<!-- 3.配置hibernate的基本属性:方言,SQL显示格式化,生成数据表的策略及二级缓存 -->
		
		<!-- 配置方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		
		<!-- SQL显示 -->
		<property name="show_sql">true</property>
		
		<!-- 格式化 -->
		<property name="format_sql">true</property>
		
		<!-- 生成数据表策略:
				update:
				最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),
				以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。
				要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
		 -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 配置hibernate二级缓存相关的属性 -->
	</session-factory>
</hibernate-configuration>

编写实体类及映射文件

实体类略

映射文件Account.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.xdy.spring.hibernate.entities.Account" table="SH_ACCOUNT">
		<id name="id" type="integer">
			<!-- Native主键生成方式会根据不同的底层数据库自动选择Identity、Sequence、Hilo主键生成方式  -->
			<generator class="native"/>
		</id>
		<property name="username"/>
		<property name="balance"/>
	</class>
</hibernate-mapping>

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"
	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.xdy.spring.hibernate"></context:component-scan>
	<!-- 配置数据源 -->
	<!-- 导入资源文件 -->
	<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>
	<!-- 配置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/xdy/spring/hibernate/entities/*.hbm.xml"></property>
	</bean>
	<!-- 配置Spring的声明式事务  -->	
	<!-- 1.配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 2.配置事务属性,需要事务管理器 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="purchase" propagation="REQUIRES_NEW"/>
			<tx:method name="*"/>
		</tx:attributes>
	</tx:advice>
	<!-- 3.配置事务切点,并把切点和事务属性关联起来 -->
	<aop:config>
		<aop:pointcut id="txPointcut" expression="execution(* com.xdy.spring.hibernate.service.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
	</aop:config>
</beans>			

编写测试类:

package com.xdy.spring.hibernate.test;

import java.sql.SQLException;
import java.util.Arrays;

import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xdy.spring.hibernate.service.BookShopService;
import com.xdy.spring.hibernate.service.Cashier;

public class SpringHibernateTest {

	private ApplicationContext ctx = null;
	private BookShopService bookShopService;
	private Cashier cashier;
	
	{
		ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		bookShopService = ctx.getBean(BookShopService.class);
		cashier = ctx.getBean(Cashier.class);
	}
	
	@Test
	public void testCashier(){
		cashier.checkout("aa", Arrays.asList("1001","1002"));
	}
	
	@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());
	}
}

BookShopDao:

package com.xdy.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);
}

BookStockException:

package com.xdy.spring.hibernate.exceptions;

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) {
		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
	}


}

BookShopDaoImpl:

package com.xdy.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.xdy.spring.hibernate.dao.BookShopDao;
import com.xdy.spring.hibernate.exceptions.BookStockException;
import com.xdy.spring.hibernate.exceptions.UserAccountException;

@Repository
public class BookShopDaoImpl implements BookShopDao {
	@Autowired
	private SessionFactory sessionFactory;
	
	//获取和当前线程绑定的session
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	} 

	@Override
	public int findBookPriceByIsbn(String isbn) {
		String hql = "select b.price from Book b where b.isbn=?";
		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 = (Integer) 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 hql = "select a.balance from Account a where a.username=?";
		int balance = (Integer)getSession().createQuery(hql).setString(0, username).uniqueResult();
		if(balance<price){
			throw new UserAccountException("余额不足!");
		}
		
		String hql2 = "update Account a set a.balance = a.balance-? where a.username=?";
		getSession().createQuery(hql2).setInteger(0, price).setString(1, username).executeUpdate();
	}

}

BookShopServiceImpl:

package com.xdy.spring.hibernate.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xdy.spring.hibernate.dao.BookShopDao;
import com.xdy.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);
		System.out.println("price="+price);
		bookShopDao.updateBookStock(isbn);
		bookShopDao.updateUserAccount(username, price);
	}

}

CashierImpl:

package com.xdy.spring.hibernate.service.Impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xdy.spring.hibernate.service.BookShopService;
import com.xdy.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);
		}
	}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring整合Hibernate是一种常见的Java开发组合,通过将SpringHibernate框架结合起来,可以实现更加灵活、高效的应用程序开发。下面是一个简单的Spring整合Hibernate的示例。 首先,我们需要创建一个Spring的配置文件applicationContext.xml,配置Hibernate的会话工厂、数据源以及其他相关的Bean。在该配置文件中,我们可以指定数据源、事务管理器,并定义Hibernate的会话工厂,以及设置SessionFactory所需要的Hibernate属性。 接下来,我们需要创建一个Hibernate的配置文件hibernate.cfg.xml,用于设置数据库连接、持久化实体类的映射关系等。在该配置文件中,我们可以指定数据库连接的URL、用户名和密码,还可以定义实体类与数据库表之间的映射关系。 然后,我们需要创建实体类,这些实体类将与数据库表对应。我们需要使用注解或XML来映射实体类与数据库表之间的字段关系。 接下来,在DAO层中定义接口和实现类。接口用于声明数据库操作的方法,而实现类则负责具体的数据库操作,包括增删改查等。在实现类中,我们可以使用Hibernate的API和查询语言来访问数据库,实现对数据库的操作。 最后,在Service层中定义业务逻辑的方法。Service层负责处理业务逻辑,并调用DAO层的方法访问数据库。在Service层中,我们可以通过@Transactional注解来定义事务的边界,保证数据库操作的一致性和完整性。 通过以上步骤,我们就完成了Spring整合Hibernate的基本配置和代码编写。在运行项目时,Spring会自动加载配置文件并创建相关的对象,同时会自动管理事务和会话等。 通过Spring整合Hibernate,我们可以充分发挥SpringHibernate各自的优势,实现数据库访问的灵活性、可扩展性和高性能。它们共同为Java开发提供了一个强大的框架,使得开发者能够更加便捷地开发出功能完善、高效稳定的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值