spring 2

什么是AOP

1.       面向切面编程Aspect-Oriented-Programming

a)       是对面向对象的思维方式的有力补充

2.       Spring_1400_AOP_Introduction

3.       好处:可以动态的添加和删除在切面上的逻辑而不影响原来的执行代码

a)       Filter

b)       Struts2的interceptor

4.       概念:

a)       JoinPoint

b)       PointCut

c)       Aspect(切面)

d)       Advice

e)       Target

f)        Weave

_________________________________

动态代理

package com.demo.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class LogInterceptor implements InvocationHandler {
	private Object target;
	
	public Object getTarget() {
		return target;
	}
	public void setTarget(Object target) {
		this.target = target;
	}
	public void beforeMethod(Method m) {
		System.out.println(m.getName() + " start");
	}
	/*Object proxy:指被代理的对象。 
	Method method:要调用的方法 
	Object[] args:方法调用时所需要的参数 
	 */
	
	@Override
	public Object invoke(Object proxy, Method m, Object[] args)
			throws Throwable {
		beforeMethod(m);
		m.invoke(target, args);
		return null;
	}
}


package com.demo.dao;

import com.demo.model.User;

public interface UserDAO {
	public void save(User u);
	
	public void delete();
}

package com.demo.dao.impl;
import com.demo.dao.UserDAO;
import com.demo.model.User;

public class UserDAOImpl implements UserDAO {

	@Override
	public void save(User u) {
		System.out.println("user save");
	}
	@Override
	public void delete() {
		System.out.println("user deleted");
	}
}

package com.demo.dao.impl;

import com.demo.dao.UserDAO;
import com.demo.model.User;

public class UserDAOImpl2 extends UserDAOImpl {

	@Override
	public void save(User u) {
		System.out.println("save start ....");
		super.save(u);
	}

}

package com.demo.dao.impl;

import com.demo.aop.LogInterceptor;
import com.demo.dao.UserDAO;
import com.demo.model.User;

public class UserDAOImpl3 extends UserDAOImpl {

	private UserDAO userDAO = new UserDAOImpl();
	
	@Override
	public void save(User u) {
		new LogInterceptor().beforeMethod(null);
		userDAO.save(u);
	}
	public void delete() {
		
	}

}

package com.demo.service;

import java.lang.reflect.Proxy;

import org.junit.Test;

import com.demo.aop.LogInterceptor;
import com.demo.dao.UserDAO;
import com.demo.dao.impl.UserDAOImpl;
import com.demo.model.User;
import com.demo.spring.BeanFactory;
import com.demo.spring.ClassPathXmlApplicationContext;

public class UserServiceTest {
	
	
	@Test
	public void testAdd() throws Exception{
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
		
		UserService service = (UserService)ctx.getBean("userService");
	}
	
	@Test
	public void testProxy() {
		UserDAO userDAO = new UserDAOImpl();
		LogInterceptor li = new LogInterceptor();
		li.setTarget(userDAO);
		/*1、第一个参数是说我们要用那个ClassLoader来产生
		 * 2、第二个参数是说产生的那些被代理对象它应该是实现那些接口
		 * 3、当我产生代理之后调用代理里面的方法,要用那一个handler 进行处理
		 * (参数说明: 
		ClassLoader loader:类加载器 
		Class<?>[] interfaces:得到全部的接口 
		InvocationHandler h:得到InvocationHandler接口的子类实例 )
		 * */
		
		UserDAO userDAOproxy =  (UserDAO)Proxy.newProxyInstance(userDAO.getClass().getClassLoader(), new Class[]{UserDAO.class}, li);
		userDAOproxy.delete();
		userDAOproxy.save(new User());
	}
}

aop 标签自动提示配置

xmlns:aop="http://www.springframework.org/schema/aop"

 http://www.springframework.org/schema/aop 

http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"


Spring AOP配置与应用

1.       两种方式:

a)       使用Annotation

b)       使用xml

2.       Annotation

a)       加上对应的xsd文件spring-aop.xsd

b)       beans.xml <aop:aspectj-autoproxy />

c)       此时就可以解析对应的Annotation了

d)       建立我们的拦截类

e)       用@Aspect注解这个类

f)        建立处理方法

g)       用@Before来注解方法

h)       写明白切入点(execution …….)

i)        让spring对我们的拦截器类进行管理@Component

3.       常见的Annotation:

a)       @Pointcut

b)       @Before

c)       @AfterReturning

d)       @AfterThrowing

e)       @After

f)        @Around

4.       织入点语法

a)       void !void

b)       参考文档(* ..)

5.       xml配置AOP

a)       把interceptor对象初始化

b)       <aop:config

                       i.             <aop:aspect …..

1.       <aop:pointcut

2.       <aop:before


<aop:aspectj-autoproxy />  // 自动的帮我产生代理,容器启动过程当中,它扫描到了有这样一个东西,需要产生代理,它就会帮你产生代理

aspectj 专门实现代理的框架

package com.demo.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect  //切面  可以把它切到其他的方法上面去
@Component  //初始化 LogInterceptor 
public class LogInterceptor {
	@Before("execution(public void com.demo.dao.impl.UserDAOImpl.save(com.demo.model.User))") // 在方法执行之前先执行我这个方法
	public void before() {
		System.out.println("method start");
	}
}

package com.demo.aop;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect  //切面  可以把它切到其他的方法上面去
@Component  //初始化 LogInterceptor 
public class LogInterceptor {
	@Pointcut("execution(public * com.demo.dao..*.*(..))")  
//	@Pointcut("execution(public * com.demo.service..*.add(..))")
	public void myMethod() {}

	@Before("myMethod()")
	public void before() {
		System.out.println("method before");
	}
	
	@AfterReturning("myMethod()")
	public void afterReturning() {
		System.out.println("method after Returning");
	}
	
	
	
	
	/*//@Before("execution(public void com.demo.dao.impl.UserDAOImpl.save(com.demo.model.User))") // 在方法执行之前先执行我这个方法
	@Before("execution(public * com.demo.dao..*.*(..))")  //记住此一个方法即可
	public void before() {
		System.out.println("method before");
	}
	
	@After("execution(public * com.demo.dao..*.*(..))")  //记住此一个方法即可
	public void afterReturning() {
		System.out.println("method after Returning");
	}*/
}

        Spring_1600_AOP_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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.demo"/>
    
    <bean id="logInterceptor" class="com.demo.aop.LogInterceptor"></bean>
    
    <!--<aop:config>
        <aop:pointcut expression="execution(public * com.demo.service..*.add(..))" 
            id="servicePointcut"/>
            
        <aop:aspect id="logAspect" ref="logInterceptor">
            <aop:before method="before" pointcut-ref="servicePointcut" />
        </aop:aspect>
    
    </aop:config>
    -->
    
    <aop:config>
        <aop:aspect id="logAspect" ref="logInterceptor">
            <aop:before method="before" pointcut="execution(public * com.demo.service..*.add(..))" />
        </aop:aspect>
    
    </aop:config>
    
</beans>


    Spring_1600_Spring_DataSource

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.demo"/>
	
	<!--
	  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	  <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
	  <property name="username" value="root"/>
	  <property name="password" value="root"/>
	  </bean>
	-->

		<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	    <property name="locations">
	        <value>classpath:jdbc.properties</value>
	    </property>
		</bean>
	
		<bean id="dataSource" destroy-method="close"
	      class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
		</bean>
	
	<bean id="logInterceptor" class="com.demo.aop.LogInterceptor"></bean>
	
</beans>

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root

package com.demo.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Component;

import com.demo.dao.UserDAO;
import com.demo.model.User;

@Component("u")
public class UserDAOImpl implements UserDAO {
	private DataSource dataSource;
	public DataSource getDataSource() {
		return dataSource;
	}
	@Resource
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public void save(User u) {
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			conn.createStatement().executeUpdate("insert into user values (null,'lisi')");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(conn != null) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e2) {
				e2.printStackTrace();
			}
		}
		
		System.out.println("user save");
	}

}


——————————————————————————————————————————————————————————————————————————

Spring整合Hibernate
1.	Spring 指定datasource
a)	参考文档,找dbcp.BasicDataSource
i.	c3p0
ii.	dbcp
iii.	proxool
b)	在DAO或者Service中注入dataSource
c)	在Spring中可以使用PropertyPlaceHolderConfigure来读取Properties文件的内容
2.	Spring整合Hibernate
a)	<bean .. AnnotationSessionFactoryBean>
i.	<property dataSource
ii.	<annotatedClasses
b)	引入hibernate 系列jar包
c)	User上加Annotation
d)	UserDAO或者UserServie 注入SessionFactory
e)	jar包问题一个一个解决
3.	声明式的事务管理
a)	事务加在DAO层还是Service层?
b)	annotation
i.	加入annotation.xsd
ii.	加入txManager bean
iii.	<tx:annotation-driven
iv.	在需要事务的方法上加:@Transactional
v.	需要注意,使用SessionFactory.getCurrentSession 不要使用OpenSession
c)	@Transactional详解
i.	什么时候rollback 
1.	运行期异常,非运行期异常不会触发rollback
2.	必须uncheck (没有catch)
3.	不管什么异常,只要你catch了,spring就会放弃管理
4.	事务传播特性:propagation_required
5.	read_only
d)	xml(推荐,可以同时配置好多方法)
i.	<bean txmanager
ii.	<aop:config 
1.	<aop:pointcut
2.	<aop:advisor pointcut-ref advice-ref
iii.	<tx:advice: id transaction-manager = 
e)	HibernateTemplate、HibernateCallback、HibernateDaoSupport(不重要)介绍
i.	设计模式:Template Method
ii.	Callback:回调/钩子函数
iii.	第一种:(建议)
1.	在spring中初始化HibernateTemplate,注入sessionFactory
2.	DAO里注入HibernateTemplate
3.	save写getHibernateTemplate.save();
iv.	第二种:
1.	从HibernateDaoSupport继承
2.	必须写在xml文件中,无法使用Annotation,因为set方法在父类中,而且是final的
f)	spring整合hibernate的时候使用packagesToScan属性,可以让spring自动扫描对应包下面的实体类


1.       Spring 指定datasource

a)       参考文档,找dbcp.BasicDataSource

                       i.             c3p0

                     ii.             dbcp

                   iii.             proxool

b)       在DAO或者Service中注入dataSource

c)       在Spring中可以使用PropertyPlaceHolderConfigure来读取Properties文件的内容



beans.xml 几种dataSource连接方式

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	  <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
	  <property name="username" value="root"/>
	  <property name="password" value="root"/>
	  </bean>

<bean id="dataSource" destroy-method="close"
	      class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
		</bean>


		<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	    <property name="locations">
	        <value>classpath:jdbc.properties</value>
	    </property>
		</bean>
	
		<bean id="dataSource" destroy-method="close"
	      class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
		</bean>

1.       Spring整合Hibernate

a)       <bean .. AnnotationSessionFactoryBean>

                       i.             <property dataSource

                     ii.             <annotatedClasses

b)       引入hibernate 系列jar包

c)       User上加Annotation

d)       UserDAO或者UserServie 注入SessionFactory

e)       jar包问题一个一个解决


下面用hibernate 的sessionFactory连接数据库

 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
	    <property name="dataSource" ref="dataSource"/>
	    <property name="annotatedClasses">
	      <list>
	        <value>com.demo.model.User</value>
	      </list>
	    </property>
	    <property name="hibernateProperties">
	    <props>
	     	<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
          	<prop key="hibernate.show_sql">true</prop>
         </props>
	    </property>
	  </bean>

package com.demo.dao.impl;

import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import com.demo.dao.UserDAO;
import com.demo.model.User;

@Component("u")
public class UserDAOImpl implements UserDAO {
    
    private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    @Override
    public void save(User u) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(u);
        session.getTransaction().commit();
        session.close();
        System.out.println("user save");
    }

}

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here    表示这里不能用.getCurrentSession()

@Component("logDAO") //就是spring在为这个类生成对象的时候它的key、id、名字是LgDAO


1.       声明式的事务管理

a)       事务加在DAO层还是Service层?

b)       annotation

                       i.             加入annotation.xsd

                     ii.             加入txManager bean

                   iii.             <tx:annotation-driven

                   iv.             在需要事务的方法上加:@Transactional

                     v.             需要注意,使用SessionFactory.getCurrentSession不要使用OpenSession

<?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/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.demo"/>

			<!--
	  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
	  <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
	  <property name="username" value="root"/>
	  <property name="password" value="root"/>
	  </bean>
	-->

		<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	    <property name="locations">
	        <value>classpath:jdbc.properties</value>
	    </property>
		</bean>
	
		<bean id="dataSource" destroy-method="close"
	      class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
		</bean>

<!-- -	<bean id="logInterceptor" class="com.demo.aop.LogInterceptor"></bean> -->

	 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
	    <property name="dataSource" ref="dataSource"/>
	    <property name="annotatedClasses">
	      <list>
	        <value>com.demo.model.User</value>
	        <value>com.demo.model.Log</value>
	      </list>
	    </property>
	    <property name="hibernateProperties">
	    <props>
	     	<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
          	<prop key="hibernate.show_sql">true</prop>
         </props>
	    </property>
	  </bean>
	  
	  <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  	  <property name="sessionFactory" ref="sessionFactory"/>
  	  </bean>
  	
  	  <tx:annotation-driven transaction-manager="txManager"/>
  	
</beans>

/*
    @Transactional //运行时异常会回滚
    public void add(User u) {
        this.userDAO.save(u);
        Log log = new Log();
        log.setMsg("a log saved");
        this.logDAO.save(log);
    }
*/


package com.demo.dao;
import com.demo.model.Log;
public interface LogDAO {
	public void save(Log log);
}

package com.demo.dao.impl;

import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.stereotype.Component;

import com.demo.dao.LogDAO;
import com.demo.dao.UserDAO;
import com.demo.model.Log;
import com.demo.model.User;

@Component //就是spring在为这个类生成对象的时候它的key、id、名字是LgDAO
public class LogDAOImpl implements LogDAO {
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void save(Log log) {
		Session session = sessionFactory.getCurrentSession();
		session.save(log);
		
		//throw new RuntimeException("Error"); Transaction 事物在运行时异常会回滚
	}

}

package com.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_log")
public class Log {
	private int id;
	private String msg;
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	
}

package com.demo.dao.impl;

import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.stereotype.Component;
import com.demo.dao.UserDAO;
import com.demo.model.User;

@Component("u")
public class UserDAOImpl implements UserDAO {
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void save(User u) {
		Session session = sessionFactory.getCurrentSession();
		session.save(u);
	}

}


package com.demo.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.demo.dao.LogDAO;
import com.demo.dao.UserDAO;
import com.demo.dao.impl.UserDAOImpl;
import com.demo.model.Log;
import com.demo.model.User;
// 面向接口或者抽象编程,需要用谁直接在service 里面new谁 实现DAO接口即可
//面向抽象编程就是 灵活

@Component("userService")
public class UserService {
	private UserDAO userDAO;
	private LogDAO logDAO;
	
	
	public LogDAO getLogDAO() {
		return logDAO;
	}
	@Resource
	public void setLogDAO(LogDAO logDAO) {
		this.logDAO = logDAO;
	}

	public void init() {
		System.out.println("init");
	}
	
	public UserDAO getUserDAO() {
		return userDAO;
	}
	
	@Resource(name="u") //常用
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	@Transactional //运行时异常会回滚
	public void add(User u) {
		this.userDAO.save(u);
		Log log = new Log();
		log.setMsg("a log saved");
		this.logDAO.save(log);
	}
	
	public void destroy() {
		System.out.println("destroy");
	}
}


propagation  transaction 的产生过程

@Transactional(propagation=Propagation.REQUIRED) //transaction运行时异常会回滚 
	//propagation=Propagation.REQUIRED 就是在当前的环境里面如果已经有transaction了就用原来的,没有就创建新的(重要)

用xml的方式配置Transaction (大多数情况下用xml)

<!-- 以下是xml 的方式完成声明式的事物 -->  
	  <aop:config>
	  	<aop:pointcut id="bussinessService" expression="execution(public * com.demo.service..*.*(..))"/>
	  	<aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService"/>
	  </aop:config>
	
	    <tx:advice id="txAdvice" transaction-manager="txManager">
	    <tx:attributes>
    		<tx:method name="getUser*" read-only="true"/>
    		<tx:method name="add*" propagation="REQUIRED"/>
  		</tx:attributes>
  		</tx:advice>


扫描model此包下面的实体类

<property name="packagesToScan">
	      <list>
	        <value>com.demo.model</value>
	      </list>
	    </property>


a)       HibernateTemplate、HibernateCallback、HibernateDaoSupport(不重要)介绍

                       i.             设计模式:TemplateMethod

                     ii.             Callback:回调/钩子函数

                   iii.             第一种:(建议)

1.       在spring中初始化HibernateTemplate,注入sessionFactory

2.       DAO里注入HibernateTemplate

3.       save写getHibernateTemplate.save();

                   iv.             第二种:

1.       从HibernateDaoSupport继承

2.       必须写在xml文件中,无法使用Annotation,因为set方法在父类中,而且是final的

b)       spring整合hibernate的时候使用packagesToScan属性,可以让spring自动扫描对应包下面的实体类


HibernateTemplate  (模板)

<bean id="sesssionFactory" class="org.springframework.orm.hibernate3.HibernateTemplate">
			<property name="sessionFactory" ref="sessionFactory"></property>
		</bean>

package com.demo.dao.impl;

import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.demo.dao.UserDAO;
import com.demo.model.User;

@Component("u")
public class UserDAOImpl implements UserDAO {
	
	private HibernateTemplate hibernateTemplate;
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public void save(User u) {
		hibernateTemplate.save(u);
	}

}


<! -- 
HibernateDaoSupport  三种方 不重要
-->

package com.demo.dao.impl;import javax.annotation.Resource;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.HibernateTemplate;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import org.springframework.stereotype.Component;/*@Componentpublic class SupportDAO {public HibernateTemplate hibernateTemplate;public HibernateTemplate getHibernateTemplate() {return hibernateTemplate;}@Resourcepublic void setHibernateTemplate(HibernateTemplate hibernateTemplate) {this.hibernateTemplate = hibernateTemplate;}}*//*@Componentpublic class SupportDAO extends HibernateDaoSupport{@Resource(name="hibernateTemplate")public void setSupporHibernateTemplate(HibernateTemplate hibernateTemplate) {super.setHibernateTemplate(hibernateTemplate);}}*/@Componentpublic class SupportDAO extends HibernateDaoSupport{@Resource(name="sessionFactory")public void setSupportSessionFactory(SessionFactory sessionFactory) {super.setSessionFactory(sessionFactory);}}————————————————————————————————————————————package com.demo.dao.impl;

import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.demo.dao.UserDAO;
import com.demo.model.User;

@Component("u")
public class UserDAOImpl extends SupportDAO implements UserDAO {
    
    @Override
    public void save(User u) {
        super.getHibernateTemplate().save(u);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值