spring整合hibernate
来源:互联网 发布:搜狐汽车 大数据 编辑:程序博客网 时间:2024/06/05 00:24
上次讲到了struts2与spring的整合,今天讲一下spring和hibernate的整合。
两者一般的分配角色是:hibernate负责和数据库打交道,主要实现的是dao层的业务逻辑。spring主要是工作在dao层上面的service层,调用dao层的业务功能完成service层的业务逻辑,同时对service层提供声明式事务。
spring整合hibernate步骤:
一:jar包,包括spring和hibernate的各自必须的jar包:
二:配置文件
hibernate配置文件:
<?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> <!-- 配置连接数据库的基本属性,这一部分可以写在spring框架的applicationcontext.xml文件中 --> <!-- 连接映射文件 ,同上,写在applicationcontext.xml文件中 其实在spring整合hibernate的时候,hibernate的配置文件完全可以不要,而把所有配置信息写到applicationcontext.xml文件中--> <!-- 基本属性 --> <property name="hibernate.show_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.format_sql">true</property> <property name="hbm2ddl.auto">update</property> </session-factory></hibernate-configuration>
spring配置文件:
<?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/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.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 配置数据源 --> <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 --> <bean id="sessionfactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="classpath:com/sh/en/*.hbm.xml"></property> </bean> <!-- 配置事务管理器 --> <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> <aop:pointcut expression="execution(* com.service.*.*(..))" id="pointcut"/> <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"/> </aop:config><!-- 配置dao层bean --> <bean id="bookdao" class="com.dao.BookDaoImp"> <property name="sessionfactory" ref="sessionfactory"></property> </bean><!-- 配置service层 --><bean id="bookservice" class="com.service.BookService"> <property name="bookdaoimp" ref="bookdao"></property></bean></beans>
下面看示例代码:
实体类:
book类:public class Books { private Integer BookId; private String BookName; private Integer BookBalance; private Integer BookStore; public Integer getBookBalance() { return BookBalance; } public void setBookBalance(Integer bookBalance) { BookBalance = bookBalance; }
account类:
public class account { private Integer accountId; private String accountName; private Integer accountBalance; public Integer getaccountId() { return accountId; } public void setaccountId(Integer accountId) { accountId = accountId; } public String getaccountName() { return accountName; } public void setCountName(String accountName) { accountName = accountName; } public Integer getaccountBalance() { return accountBalance; } public void setCountBalance(Integer accountBalance) { accountBalance = accountBalance; }}
映射文件:
book类:<?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 2017-8-25 12:29:58 by Hibernate Tools 3.5.0.Final --><hibernate-mapping> <class name="com.sh.en.Books" table="BOOKS"> <id name="BookId" type="java.lang.Integer"> <column name="BOOKID" /> <generator class="native" /> </id> <property name="BookName" type="java.lang.String"> <column name="BOOKNAME" /> </property> <property name="BookBalance" type="java.lang.Integer"> <column name="BOOKBALANCE"></column> </property> <property name="BookStore" type="java.lang.Integer"> <column name="BOOKSTORE" /> </property> </class></hibernate-mapping>
account类:
<?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 2017-8-25 12:29:58 by Hibernate Tools 3.5.0.Final --><hibernate-mapping> <class name="com.sh.en.Count" table="COUNT"> <id name="CountId" type="java.lang.Integer"> <column name="COUNTID" /> <generator class="native" /> </id> <property name="CountName" type="java.lang.String"> <column name="COUNTNAME" /> </property> <property name="CountBalance" type="java.lang.Integer"> <column name="COUNTBALANCE" /> </property> </class></hibernate-mapping>
dao层:无非就是数据库的增删改查
package com.dao;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import com.Exception.BookStoreException;import com.Exception.CountBalanceException;public class BookDaoImp implements BookDao{ private SessionFactory sessionfactory; public SessionFactory getSessionfactory() { return sessionfactory; } public void setSessionfactory(SessionFactory sessionfactory) { this.sessionfactory = sessionfactory; } public Session GetSession() { return sessionfactory.getCurrentSession(); } //查询书的单价 @Override public int findbookpricebyname(String bookname) { String hql="SELECT b.BookBalance from Books b where b.BookName=?"; Query query=GetSession().createQuery(hql).setString(0, bookname); return (int) query.uniqueResult(); } //查询用户余额 @Override public int findcountbalancebyname(String username) { String hql="select c.CountBalance from Count c where c.CountName=?"; Query query=GetSession().createQuery(hql).setString(0, username); return (int) query.uniqueResult(); } //更新书的库存 @Override public void updatebookstore(String bookname) { //检查异常 String hql="select b.BookStore from Books b where b.BookName=?"; int bookstore=(Integer) GetSession().createQuery(hql).setString(0, bookname).uniqueResult(); if(bookstore==0) { throw new BookStoreException("库存不足"); } hql="update Books b set b.BookStore=b.BookStore-1 where b.BookName=?"; GetSession().createQuery(hql).setString(0, bookname).executeUpdate(); } //更新用户余额 @Override public void updateacountbalance(String username,int price) { //检查异常 String hql="select c.CountBalance from Count c where c.CountName=?"; int countbalance=(int) GetSession().createQuery(hql).setString(0, username).uniqueResult(); if(countbalance<price) { throw new CountBalanceException("余额不足"); } hql="update Count c set c.CountBalance= c.CountBalance-? where c.CountName=?"; GetSession().createQuery(hql).setInteger(0, price).setString(1, username).executeUpdate(); }}
service层:调用dao层的业务功能
import com.dao.BookDaoImp;public class BookService { private BookDaoImp bookdaoimp; public BookDaoImp getBookdaoimp() { return bookdaoimp; } public void setBookdaoimp(BookDaoImp bookdaoimp) { this.bookdaoimp = bookdaoimp; } public int findbookbalancebyname(String name) { return bookdaoimp.findbookpricebyname(name); } public void Countbuybook(String countname,String bookname) { bookdaoimp.updatebookstore(bookname); bookdaoimp.updateacountbalance(countname, bookdaoimp.findbookpricebyname(bookname)); }}
异常类:
public class BookStoreException extends RuntimeException{ private static final long serialVersionUID = 1L; public BookStoreException(String message) { super(message); } }
public class CountBalanceException extends RuntimeException{ public CountBalanceException(String message) { super(message); }}
三:编写测试
import static org.junit.Assert.*;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.dao.BookDaoImp;import com.service.BookService;public class test { private BookService bookservice; private ApplicationContext ac; { ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); bookservice=ac.getBean(BookService.class); } @Test public void buybook() { bookservice.Countbuybook("Tom", "c++"); } @Test public void testbookdao() { System.out.println(bookservice.findbookbalancebyname("java")); } @Test public void tests() throws SQLException { DataSource datasource=(DataSource) ac.getBean(DataSource.class); System.out.println(datasource.getConnection()); }}
上面只是简单的测试了一下,可以使用的
至此,spring和hibernate的整合完成,具体功能就根据项目需求了
阅读全文
0 0
- 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整合
- @Subselect映射,子查询,视图.
- iOS之《Effective Objective-C 2.0》读书笔记(21)
- 算法导论第二章算法练习
- 数据库常见优化
- apk打包遇到的问题
- spring整合hibernate
- 索引使用场景
- P1854 花店橱窗布置
- 文字展示多余的用三个点显示
- explan语句说明
- drupal汉化
- 非线性方程的解法
- Linux下编译多个不同目录下的文件以及静态库、动态库的使用
- 为保存的瞬时实力解决方法