spring整合hibernate
来源:互联网 发布:mac win10 能耗 编辑:程序博客网 时间:2024/06/03 21:21
目录结构:
配置文件: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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.liuchangjie.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="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"></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>
<!-- 使用 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/liuchangjie/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="find*" 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.liuchangjie.spring.hibernate.service.*.*(..))"
id="txPointCut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
</aop:config>
</beans>
配置文件: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>
<!-- 配置 hibernate 的基本属性 -->
<!-- 1. 数据源需配置到 IOC 容器中, 所以在此处不再需要配置数据源 -->
<!-- 2. 关联的 .hbm.xml 也在 IOC 容器配置 SessionFactory 实例时在进行配置 -->
<!-- 3. 配置 hibernate 的基本属性: 方言, SQL 显示及格式化, 生成数据表的策略以及二级缓存等. -->
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
资源文件:db.properties
jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///springHibernate
jdbc.initialPoolSize=10
jdbc.maxPoolSize=100
各类文件:所有类都已经黏贴到此处,读者可以复制下来研究一下
类文件 BookShopDao.java:
package com.liuchangjie.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);
}
类文件 BookShopDaoImpl.java:
package com.liuchangjie.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.liuchangjie.spring.hibernate.dao.BookShopDao;
import com.liuchangjie.spring.hibernate.exception.BookStockException;
import com.liuchangjie.spring.hibernate.exception.UserAccountException;
@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public int findBookPriceByIsbn(String isbn) {
String hql = "Select a.price from Book a where a.isbn = ?";
Query query = getSession().createQuery(hql).setString(0, isbn);
int price = (int) query.uniqueResult();
return price;
}
@Override
public void updateBookStock(String isbn) {
// 验证库存是否足够
String hql2 = "Select a.stock from Book a where a.isbn=?";
Query query = getSession().createQuery(hql2).setString(0, isbn);
int stock = (int) query.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=?";
Query query = getSession().createQuery(hql2).setString(0, username);
int balance = (int) query.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.liuchangjie.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
package com.liuchangjie.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;
}
}
映射文件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-5-23 12:20:21 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.liuchangjie.spring.hibernate.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="USER_NAME" />
</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-5-23 12:20:21 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.liuchangjie.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>
两个异常类文件:只需要继承RuntimeException之后将构造器导入即可,不需要代码修改
BookStockException.java
UserAccountException.java
两个接口文件:
BookShopService.java
package com.liuchangjie.spring.hibernate.service;
public interface BookShopService {
public void purchase(String username, String isbn);
}
Cashier.java
package com.liuchangjie.spring.hibernate.service;
import java.util.List;
public interface Cashier {
public void checkout(String username, List<String> isbns);
}
上面两个接口的实现类:
实现类:BookShopServiceImpl.java
package com.liuchangjie.spring.hibernate.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.liuchangjie.spring.hibernate.dao.BookShopDao;
import com.liuchangjie.spring.hibernate.service.BookShopService;
@Service("bookShopService")
public class BookShopServiceImpl implements BookShopService {
@Autowired
private BookShopDao bookShopDao;
@Override
public void purchase(String username, String isbn) {
// 1.获取书的单价
int price = bookShopDao.findBookPriceByIsbn(isbn);
// 2.更新库存
bookShopDao.updateBookStock(isbn);
// 3.更新账户余额
bookShopDao.updateUserAccount(username, price);
}
}
实现类:CashierImpl.java
package com.liuchangjie.spring.hibernate.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.liuchangjie.spring.hibernate.service.BookShopService;
import com.liuchangjie.spring.hibernate.service.Cashier;
@Service("cashier")
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);
}
}
}
测试类:SpringHibernateTest.java
package com.liuchangjie.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.liuchangjie.spring.hibernate.dao.BookShopDao;
import com.liuchangjie.spring.hibernate.service.BookShopService;
import com.liuchangjie.spring.hibernate.service.Cashier;
public class SpringHibernateTest {
private ApplicationContext ctx = null;
private BookShopDao bookShopDao = null;
private BookShopService bookShopService;
private Cashier cashier;
{
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
bookShopDao = (BookShopDao) ctx.getBean("bookShopDao");
bookShopService = (BookShopService) ctx.getBean("bookShopService");
cashier = (Cashier) ctx.getBean("cashier");
}
@Test
public void testCashier() {
cashier.checkout("AA", Arrays.asList("1001", "1002"));
}
@Test
public void testBookShopService() {
bookShopService.purchase("AA", "1001");
}
@Test
public void testConnection() throws SQLException {
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}
必须导入的jar包(此处只是黏贴jar包名字):
lib:
antlr-2.7.7.jar
c3p0-0.9.1.2.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-logging-1.1.1.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
mysql-connector-java-5.1.7-bin.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
//后面两个可以不导入,因为不涉及web
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
数据库文件:
创建数据库之后导入以下文件:
文件名:springhibernate.sql
/*
SQLyog Ultimate v10.00 Beta1
MySQL - 5.1.37-community : Database - springhibernate
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springhibernate` /*!40100 DEFAULT CHARACTER SET gb2312 */;
USE `springhibernate`;
/*Table structure for table `sh_account` */
DROP TABLE IF EXISTS `sh_account`;
CREATE TABLE `sh_account` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_NAME` varchar(255) DEFAULT NULL,
`BALANCE` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gb2312;
/*Data for the table `sh_account` */
insert into `sh_account`(`ID`,`USER_NAME`,`BALANCE`) values (1,'AA',20);
/*Table structure for table `sh_book` */
DROP TABLE IF EXISTS `sh_book`;
CREATE TABLE `sh_book` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`BOOK_NAME` varchar(255) DEFAULT NULL,
`ISBN` varchar(255) DEFAULT NULL,
`PRICE` int(11) DEFAULT NULL,
`STOCK` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=gb2312;
/*Data for the table `sh_book` */
insert into `sh_book`(`ID`,`BOOK_NAME`,`ISBN`,`PRICE`,`STOCK`) values (1,'Java','1001',100,8),(2,'Oracle','1002',80,9);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
- Spring:Spring整合Hibernate
- 【Spring】Spring+hibernate整合
- struts整合spring整合hibernate
- spring 整合hibernate整合方式
- 整合 struts spring hibernate
- struts+spring+hibernate整合
- struts,hibernate,spring整合
- struts+spring+hibernate整合
- struts+spring+hibernate整合
- Spring+hibernate+DWR整合
- webwork+spring+hibernate整合
- webwork+spring+hibernate整合
- Spring整合Hibernate
- Struts hibernate Spring 整合
- Struts hibernate Spring 整合
- Spring整合Hibernate
- 整合Spring、Struts、Hibernate
- webwork+spring+hibernate整合
- Android ScrollView和ListView滑动冲突问题
- 数据结构排序算法总结
- 【神经网络】:如何实现感知机
- Custom圆环
- github团队合作
- spring整合hibernate
- char* 与string
- 如何看待操作系统的用户空间和内核空间?
- java跳出多重嵌套循环
- 自己写的日志文件printTx
- caffe学习笔记(9):优化之Gradient descent
- 最原生最干净的mysql登录和执行
- ffmpeg: error while loading shared libraries: libiconv.so.2
- ORA-01756: quoted string not properly terminated问题