Spring学习(十)
需要的jar包
1、Spring核心必须依赖的库:commons-logging-1.1.1.jar
2、Spring IoC部分核心库:
- spring-beans-4.3.9.RELEASE.jar
- spring-context-4.3.9.RELEASE.jar
- spring-context-support-4.3.9.RELEASE.jar
- spring-core-4.3.9.RELEASE.jar
- spring-expression-4.3.9.RELEASE.jar
- spring-web-4.3.9.RELEASE.jar ------> 支持在Web环境中使用Spring IoC容器
3、Spring AOP部分核心库:
- spring-aop-4.3.9.RELEASE.jar
- spring-aspects-4.3.9.RELEASE.jar
4、Spring AOP需要依赖于aspectj库:
- aspectjrt.jar
- aspectjweaver.jar
5、Spring JDBC部分核心库:
- spring-jdbc-4.3.9.RELEASE.jar
- spring-tx-4.3.9.RELEASE.jar
6、Spring ORM部分核心库:
- spring-orm-4.3.9.RELEASE.jar
7、若配置的是c3p0数据源还需要:
- c3p0-0.9.5.2.jar
- hibernate-c3p0-5.2.10.Final.jar
- mchange-commons-java-0.2.11.jar
8、Hibernate部分核心库:
- antlr-2.7.7.jar
- classmate-1.3.0.jar
- dom4j-1.6.1.jar
- hibernate-commons-annotations-5.0.1.Final.jar
- hibernate-core-5.2.10.Final.jar
- hibernate-jpa-2.1-api-1.0.0.Final.jar
- jandex-2.0.3.Final.jar
- javassist-3.20.0-GA.jar
- jboss-logging-3.3.0.Final.jar
- jboss-transaction-api_1.2_spec-1.0.1.Final.jar
9、Ehcache部分核心库:
- ehcache-2.10.3.jar
- hibernate-ehcache-5.2.10.Final.jar
- slf4j-api-1.7.7.jar
10、数据库对应的驱动包:mysql-connector-java-5.1.40-bin.jar
Spring整合Hibernate
1、使用Spring依赖注入和AOP简化Hibernate应用,由IOC 容器来管理 Hibernate 的 SessionFactory,让 Hibernate 使用上 Spring 的声明式事务
2、整合步骤
- 引用jar包
- 创建数据库和表
DROP TABLE IF EXISTS t_customer ; CREATE TABLE t_customer (
id INT(5) PRIMARY KEY ,
email VARCHAR(60) UNIQUE NOT NULL,
password VARCHAR(32) NOT NULL ,
nickname VARCHAR(150) ,
gender VARCHAR(3) ,
birthdate DATE ,
married CHAR(1)
); - 创建类创建类
Customer类
package ecut.hibernate.entity; import java.util.Date; public class Customer { private Integer id;
private String email;
private String password;
private String nickname;
private char gender;
private Date birthdate;
private boolean married; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getNickname() {
return nickname;
} public void setNickname(String nickname) {
this.nickname = nickname;
} public char getGender() {
return gender;
} public void setGender(char gender) {
this.gender = gender;
} public Date getBirthdate() {
return birthdate;
} public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
} public boolean isMarried() {
return married;
} public void setMarried(boolean married) {
this.married = married;
} }CustomerController类
package ecut.hibernate.controller; import java.util.List; import ecut.hibernate.entity.Customer;
import ecut.hibernate.service.CustomerService; public class CustomerController { private CustomerService customerService ; public String regist( Customer c ){
System.out.println( "CustomerController # regist ." );
customerService.save( c );
return "success" ;
} public List<Customer> allCustomer(){
return customerService.findAll();
} public CustomerService getCustomerService() {
return customerService;
} public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
} }CustomerService类
package ecut.hibernate.service; import java.util.List; import ecut.hibernate.dao.CustomerDao;
import ecut.hibernate.entity.Customer; public class CustomerService { private CustomerDao customerDao ; public boolean save( Customer c ) {
System.out.println( "CustomerService # save ." );
return customerDao.persist( c );
} public List<Customer> findAll(){
return customerDao.loadAll() ;
} public CustomerDao getCustomerDao() {
return customerDao;
} public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
} }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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
<!-- 注入数据源,用来获得数据库连接 -->
<property name="dataSource" ref="dataSource" />
<!-- 注入 hibernate 的配置 ( 方言、二级缓存 、查询缓存) -->
<property name="hibernateProperties">
<props>
<!-- 指示数据库的基本信息 -->
<!--
<prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.url" >jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8</prop>
<prop key="hibernate.connection.username" >root</prop>
<prop key="hibernate.connection.password" >123456</prop>
-->
<!-- 启用二级缓存 -->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<!-- 启用查询缓存 -->
<prop key="hibernate.cache.use_query_cache" >true</prop>
<!-- 指定数据方言 类-->
<prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>
<!-- 指示是否显示sql -->
<prop key="hibernate.show_sql" >true</prop>
<!-- 指示是否对sql格式化输出 -->
<prop key="hibernate.format_sql" >true</prop>
</props>
</property> <!-- 引入映射文件 -->
<!-- mappingResources 对应的是 String 数组,不支持 使用 通配符 ,下面的写法是错误的 -->
<!-- <property name="mappingResources" value="classpath:ecut/hibernate/entity/*.hbm.xml" /> -->
<!-- mappingLocations 对应的 是 Resource 数组 ,因此 支持 使用 通配符 -->
<property name="mappingLocations" value="classpath:ecut/hibernate/entity/*.hbm.xml"></property> </bean> <!-- 配置平台事务管理器 ,由HibernateTransactionManager类来完成事务管理-->
<bean id="platformTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 提供对事务的配置 ( Advice ) -->
<tx:advice id="transactionAdvice" transaction-manager="platformTransactionManager">
<tx:attributes>
<tx:method name="persist*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" />
<tx:method name="save*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" />
<tx:method name="update*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" />
<tx:method name="delete*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" />
<tx:method name="remove*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="false" /> <tx:method name="load*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" />
<tx:method name="get*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" />
<tx:method name="query*" propagation="REQUIRED" isolation="READ_COMMITTED" read-only="true" />
</tx:attributes>
</tx:advice> <!-- aop实现事务控制:使用 aop:config 实现将 Advice 织入到 相应的 连接点中 -->
<aop:config>
<aop:pointcut id="tx-pointcut" expression="execution(* ecut.hibernate.service.*.*(..))"/>
<!-- 声明事务控制 切面 -->
<aop:advisor pointcut-ref="tx-pointcut" advice-ref="transactionAdvice"/>
</aop:config>
<!-- hibernate所有操作都是通过sessionFactory实现的 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <bean id="customerDao" class="ecut.hibernate.dao.CustomerDao" >
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean> <bean id="customerService" class="ecut.hibernate.service.CustomerService" >
<property name="customerDao" ref="customerDao" />
</bean> <bean id="customerController" class="ecut.hibernate.controller.CustomerController" >
<property name="customerService" ref="customerService" />
</bean> </beans>在spring配置文件中,配置平台事务管理器 ,由HibernateTransactionManager类来完成事务管理,并引用sessionFactory。在sessionFactory中注入 hibernate 的配置 ( 方言、二级缓存 、查询缓存)和数据源,以及引入映射文件,需要注意的是引入配置文件时mappingLocations 对应的 是 Resource 数组 ,因此 支持 使用 通配符,但是mappingResources 对应的是 String 数组,不支持使用通配符。最终通过AOP来实现事务的控制。controller中添加了CustomerService的对象,因此需要将CustomerService以ref的方式引入到controller中。service中添加了CustomerDao的对象,因此需要将CustomerDao以ref的方式引入到service中。dao中添加了jdbcTemplate的对象,因此需要将jdbcTemplate以ref的方式引入到dao中。而Template依赖与DataSource,以ref的方式为JdbcTemplate注入引用。DataSource的属性可以通过注入数据库的一些配置属性添加。
Hibernate配置文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- 指定 那个类 ( name 指定类名 ) 对应 那个表 ( table 指定表名 ) -->
<class name="ecut.hibernate.entity.Customer" table="t_customer"> <!-- 对于 与 数据库主键 对应的 对象标识符属性 来说,要单独使用 id 标签来映射 -->
<id name="id" type="integer" column="id" >
<generator class="increment" /> <!-- 由 hibernate 提供的 对象标识符 生成策略 -->
</id> <!-- 指定 那个属性 ( name 指定属性名 ) 对应 那个列 ( column 属性指定 列名 ) -->
<property name="email" type="string" column="email" />
<!-- 使用 type 属性指定 映射类型 ( 既不是 Java 类型,也不是 数据库类型,而是 中间类型 ( 媒婆 ) ) -->
<property name="password" type="string" column="password" />
<property name="nickname" type="string" column="nickname" />
<!-- Java 中的 char 类型在 hibernate 中对应的映射类型是 character -->
<property name="gender" type="character" column="gender" />
<property name="birthdate" type="date" column="birthdate" />
<!-- Java 中的 boolean 类型在 hibernate 中对应的映射类型可以是 true_false 、yes_no -->
<property name="married" type="yes_no" column="married" /> </class> </hibernate-mapping>CustomerDao类
package ecut.hibernate.dao; import java.io.Serializable;
import java.util.List; import ecut.hibernate.entity.Customer;
import org.springframework.orm.hibernate5.HibernateTemplate; public class CustomerDao { private HibernateTemplate hibernateTemplate; public boolean persist( Customer c ) {
try{
//没有提交事务所以需要增加事务的配置
Serializable id = hibernateTemplate.save( c );
return id != null ;
} catch ( Exception e) {
e.printStackTrace();
return false ;
}
} public boolean update( Customer c ) {
try{
hibernateTemplate.update( c );
return true ;
} catch ( Exception e) {
return false ;
}
} public boolean delete( Customer c ) {
try{
hibernateTemplate.delete( c );
return true ;
} catch ( Exception e) {
return false ;
}
} public Customer load( Integer id ) {
return hibernateTemplate.get( Customer.class , id ) ;
}
//@SuppressWarnings抑制编译器警告
@SuppressWarnings("unchecked")
public List<Customer> loadAll() {
final String HQL = "FROM Customer";
List<Customer> list = (List<Customer>)hibernateTemplate.find( HQL );
return list ;
} public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
} public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
} }测试类
package ecut.hibernate; import java.util.Date;
import java.util.List; import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import ecut.hibernate.controller.CustomerController;
import ecut.hibernate.entity.Customer;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestCustomerController { private static AbstractApplicationContext container ; public @BeforeClass static void init(){
String configLocations = "classpath:ecut/**/hibernate/beans.xml";
container = new ClassPathXmlApplicationContext( configLocations );
} public @Test void testRegist(){ Customer c = new Customer(); c.setEmail( "lao@ecut.edu.cn" );
c.setPassword( "hello2017" ); Date birthdate = new Date() ;
c.setBirthdate( birthdate );
c.setGender( '男' ); c.setNickname( "老王" );
c.setMarried( false ); CustomerController cc = container.getBean( "customerController" , CustomerController.class ); cc.regist( c ); } public @Test void all(){ CustomerController cc = container.getBean( "customerController" , CustomerController.class ); List<Customer> list = cc.allCustomer(); for( Customer c : list ){
System.out.println( c.getEmail() + " : " + c.getNickname() );
} } public @AfterClass static void destory(){
container.close();
} }通过整合,使数据库的操作得到了简化,Spring的IoC容器则提供了更好的管理方式,它不仅能以声明式的方式配置Session- Factory实例,也可充分利用IoC容器的作用,为SessionFactory注入数据源引用。
转载请于明显处标明出处:
https://www.cnblogs.com/AmyZheng/p/9281813.html
Spring学习(十)的更多相关文章
- Spring学习(十九)----- Spring的五种事务配置详解
前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...
- Spring学习十 rest
1: Web service: 是一个大的概念范畴,它表现了一种设计思想 SOAP 是 Web service 的一个重要组成部份. SOAP 是一种协议而非详细产品.SOAP 是通过 XML ...
- Spring 学习十五 AOP
http://www.hongyanliren.com/2014m12/22797.html 1: 通知(advice): 就是你想要的功能,也就是安全.事物.日子等.先定义好,在想用的地方用一下.包 ...
- spring学习十九 常用注解
1. @Component 创建类对象,相当于配置<bean/>2. @Service 与@Component 功能相同. 2.1 写在 ServiceImpl 类上.3. @Reposi ...
- spring学习 十八 spring的声明事物
1.编程式事务: 1.1 由程序员编程事务控制代码.commit与rollback都需要程序员决定在哪里调用,例如jdbc中conn.setAutoCimmit(false),conn.commit( ...
- spring学习 十六 spring加载属性文件
第一步:创建一个properties文件,以数据库链接作为实例db.properties jdbc.url=jdbc:mysql://192.168.153.128:3306/mybaties?cha ...
- spring学习 十五 spring的自动注入
一 :在 Spring 配置文件中对象名和 ref=”id” ,id 名相同使用自动注入,可以不配置<property/>,对应的注解@Autowired的作用 二: 两种配置办法 (1 ...
- spring学习 十四 注解AOP 通知传递参数
我们在对切点进行增强时,不建议对切点进行任何修改,因此不加以使用@PointCut注解打在切点上,尽量只在Advice上打注解(Before,After等),如果要在通知中接受切点的参数,可以使用Jo ...
- spring学习 十二 AspectJ-based的通知入门 带参数的通知
第一步:编写通知类 package com.airplan.pojo; import org.aspectj.lang.ProceedingJoinPoint; public class Advice ...
- spring学习 十 schema-based 前置后后置通知
spring 提供了 2 种 AOP 实现方式:(1)Schema-based ,(2)AspectJ Schema-based:每个通知都需要实现接口或类,配置 spring 配置文件时在<a ...
随机推荐
- 8.1.1 IO
IO对象无拷贝或赋值.进行IO操作的函数通常以引用的方式传递和返回流,且该引用不能是const的 确定一个流对象是否处于良好状态的最简单的方法是将它作为一个条件来使用 while (cin >& ...
- 为什么各家银行都抢着办理ETC业务?
最近据于各家银行抢着办ETC业务的话题很火,各家银行不仅有很大的折扣力度,而且又是送油卡又是送现金的,银行为什么会如此乐此不疲?为了让车主办理自家的ETC业务,银行究竟有多卖力? 就在近日,网上疯传一 ...
- ABB工业机器人(条件执行数字信号判断,画方or画圆)
一.前戏 条件:从安全点,到工具区域夹取工具(笔),到工作区域,判断数字信号 Di1 =1 ,Ture :画方,False:画圆,回到工具区域放下工具(笔),回到安全点 二. 准备工作 校准tcp工具 ...
- 浅谈DAO工厂设计模式(工厂模式的好处)
随着软件分层设计的流行及广泛的应用,对于DAO的设计模式大家已经不再陌生了,DAO层已经在软件系统的开发中成为必不可少的一层,将后台的数据层和前台的VO进行分离.前段时间也针对于DAO的设计介绍过一个 ...
- IDEA 运行项目、模块的多个实例
IDEA默认只能运行同一项目|模块的一个实例. 运行多个实例: 比如springcloud的端口设置: --server.port=9001 . 当然,也可以在项目的配置文件中修改参数. 命令行.ID ...
- mybatis--第一个mybatis程序
首先,创建一个数据库my,并在数据库中插入一张表user,然后在user表中插入一行数据,代码如下: create database my; use my; create table user( id ...
- curl模拟提交
function curl_post($url, $post){ $options = array( CURLOPT_RETURNTRANSFER =>true, CURLOPT_HEADER ...
- 架构师必备技能指南:SaaS(软件即服务)架构设计
1.介绍 从计算机诞生开始,就伴随着计算机应用程序的演变.简短的回顾历史,我们可以清楚的看到应用程序发生的巨大变化.上世纪70年代中期,随着个人PC机的爆炸式增长以及程序员的崛起,让计算机的计算能力得 ...
- socketserver 模块简介
一.socketserver模块简介 socketserver模块简化了网络编程,模块下有五个服务类:BaseServer.TCPServer.UDPServer.UnixStreamServer.U ...
- laravel5.1学习1-Model的创建
laravel5.1中可以很方便的用命令行创建Model 1.php artisan make:model Content 接着添加属性 $fillable =array('id','article_ ...