spring+hibernate整合

</pre>1,学习spring+hibernate整合<img src="file:///C:\Users\12868\AppData\Roaming\Tencent\Users\1286899020\QQ\WinTemp\RichOle\O@{Y_@~8@A(~8IM)MPL71`L.png" alt="" /></div><div><span style="font-size:32px;"><img src="file:///C:\Users\12868\AppData\Roaming\Tencent\Users\1286899020\QQ\WinTemp\RichOle\O@{Y_@~8@A(~8IM)MPL71`L.png" alt="" /></span></div><p>目录结构:</p><p><img src="https://img-blog.csdn.net/20160902114016333" alt="" /></p><p></p><p></p><p><strong><span style="color:#ff6666;">1、首先添加jar包 为整合做准备;</span></strong></p><p><img src="https://img-blog.csdn.net/20160902114542527" alt="" /></p><p>3,spring的配置文件和hibernate的配置文件、db.properties文件</p><p><strong><span style="font-size:18px;color:#66cccc;">applicationContext.xml</span></strong></p><p></p><pre name="code" class="java"><span style="font-size:14px;"><?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.idfar.spring.sh"></context:component-scan>
	<!-- 导入资源文件 -->
	<context:property-placeholder location="classpath:db.properties" />

	<!-- 配置 C3P0 数据源 -->
	<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="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
		<property name="driverClass" value="${jdbc.driverClass}"></property>

		<property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
		<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
	</bean>
	<!--通过LocalSessionFactoryBean 配置Hibernate 的SessionFactory实例 -->
	<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>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		<!-- 配置 hibernate 映射文件的位置及名称, 可以使用通配符 -->
		<property name="mappingLocations" value="classpath:com/idfar/spring/sh/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="txAdcice" 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 expression="execution(* com.idfar.spring.sh.service.*.*(..))" 
			id="txPointcut"/>
		<aop:advisor advice-ref="txAdcice" pointcut-ref="txPointcut"/>
	</aop:config>
</beans></span>
2.hibernate.cfg.xml
<span style="background-color: rgb(255, 255, 255);"><span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<!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>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<property name="hibernate.hbm2ddl.auto">update</property>
	</session-factory>
</hibernate-configuration></span></span>

3.db.properties

jdbc.user=root
jdbc.password=#######//自己的数据库密码
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

4,编写具体的代码。

BookShopDao.java

package com.idfar.spring.sh.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);
}
BookShopDaoImpl.java
package com.idfar.spring.sh.dao.lmpl;

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.idfar.spring.sh.dao.BookShopDao;
import com.idfar.spring.sh.exceptions.BookStockException;
import com.idfar.spring.sh.exceptions.UserAccountException;

@Repository
public class BookShopDaoImpl implements BookShopDao {
	// 不推荐使用 原因:导致Dao和spring的API,
	/* private HibernateTemplate hibernateTemplate; */
	@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 = (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();

	}

}
Account.java

package com.idfar.spring.sh.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

package com.idfar.spring.sh.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;
	}

}
通过Account.ava、Book.java,生成Account.hbm.xml、Book.hbm.xml

Account.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">
<!-- Generated 2016-9-1 11:42:24 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.idfar.spring.sh.entities.Account" table="SH_ACCOUNT">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <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

<?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-1 11:42:24 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.idfar.spring.sh.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>

这里需要两个异常BookStockException.java、UserAccountException在计算库存  和价格是需要用到

<strong style="font-size:14px;">package com.idfar.spring.sh.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,
			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
	}

	
}
<span style="font-size:14px;"></span></strong><pre name="code" class="java"><strong><span style="font-size:32px;">UserAccountException.java</span></strong>

UserAccountException.java

</pre><pre name="code" class="java">package com.idfar.spring.sh.exceptions;

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
	}

	
	
}


 
BookShopService.java 

<span style="font-size:14px;">package com.idfar.spring.sh.service;

public interface BookShopService {
	
	public void purchase(String username, String isbn);
	
}</span><span style="font-size:24px;">
</span>
BookShopServiceImpl.java

package com.idfar.spring.sh.service.Impl;

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

import com.idfar.spring.sh.dao.BookShopDao;
import com.idfar.spring.sh.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<测试事务的传播行为>

<span style="font-size:14px;">package com.idfar.spring.sh.service;

import java.util.List;

public interface Cashier {

	public void checkout(String username, List<String> isbns);
	
}</span><span style="font-size:24px;">
</span>

CashierImpl.java

package com.idfar.spring.sh.service.Impl;

import java.util.List;

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

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

}

测试以上的代码

JDBCTest.java

package com.idfar.spring.sh.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.idfar.spring.sh.service.BookShopService;
import com.idfar.spring.sh.service.Cashier;

public class JDBCTest {
	
	private ApplicationContext ctx = null;

	private BookShopService bookShopService = null;
	private Cashier cashier = null;
	
	{
		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());
	}

}

结束,新手  花了1天的时间整理的  ,希望大家多提提意见,在此感谢佟刚老师,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值