`

spring_hibernate_transation_annotation&xml

 
阅读更多
一。测试
public class UserServiceTest {
	public static void main(String[] args) {
		ApplicationContext ac =  new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService service = (UserService)ac.getBean("userService");
		User u = new User();
		u.setName("haha success!!");
		service.add(u);
	}
}


二。application.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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!-- 配置自动装配 AutowiredAnnotationBeanPostProcessor等接口,实现注入等功能 -->
	<context:annotation-config/>
	<!-- 配置扫描包路径,将包下所有组件实例化 -->
	<context:component-scan base-package="com.job"/>
	
	<!-- 声明一个处理实现类 -->
	<bean id="userDAOImpl" class="com.job.dao.UserDAOImpl">
		<!-- 将sessionFactory注入到处理实理类中 -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 在spring容器中,创建数据库连接Bean -->
    <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/test?useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
    </bean>
    
	<!-- 创建hibernate的sessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    	<!-- 将spring容器中存在的数据库连接Bean,配置到sessionFactory中 -->
        <property name="dataSource" ref="DataSource"/>
        
        <!-- 配置hibernate映射实体对象到表的文件(一) -->
         <property name="packagesToScan">
            <list>
                <value>com.job.model</value>
            </list>
        </property>
        <!-- 配置hibernate映射实体对象到表的文件(二)
        <property name="annotatedClasses">
            <list>
                <value>com.job.model.User</value>
                <value>com.job.model.Log</value>
            </list>
        </property>
         -->
         
        <!-- 配置hibernate属性,方言,显示sql,是否创建数据表 -->
        <property name="hibernateProperties">
        	<props>
        		<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        		<prop key="hibernate.show_sql">true</prop>
        		<prop key="hibernate.hbm2ddl.auto">update</prop>
        	</props>
        </property>
    </bean>
    
    <!-- 配置事务,注意xmlns:tx引入 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
   		 <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

</beans>

1.导入对应的 xmlns:tx标签
2.运用hibernate4的sessionFactory和transaction

三。增加事务及注入处理逻辑
@Component
public class UserService {
	
	private UserDAO userDAO;
	private LogDAO logDAO;
	
	@Transactional
	public void add(User u){
		this.userDAO.save(u);
		Log log = new Log();
		log.setMessage("a object saved!");
		this.logDAO.save(log);
	}

	@Resource(name="userDAOImpl")
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	@Resource(name="logDAOImpl")
	public void setLogDAO(LogDAO logDAO) {
		this.logDAO = logDAO;
	}
	
	public UserDAO getUserDAO() {
		return userDAO;
	}
	public LogDAO getLogDAO() {
		return logDAO;
	}
}

xml事务配置方式:
 <!-- 配置事务,注意xmlns:tx引入 -->
    <!--<tx:annotation-driven transaction-manager="transactionManager"/>-->
    <bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
   		 <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- 声明一个类中哪些方法增加建议-->
    <aop:config>
    	<!-- public * com.job.service..*.*(..)表示方法:公共,任何返回值,com.job.service包,任何类,任何方法,任何参数 -->
        <aop:pointcut id="fooServiceOperation" expression="execution(public * com.job.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
    </aop:config>
 
 
    <!-- 声明一个aop建议 ,注入事务管理-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 事务属性-->
        <tx:attributes>
            <!-- 所有以get开头的方法都设置成 read-only 方式,sping会进行优化-->
            <tx:method name="get*" read-only="true"/>
            <!-- 其它的方法设置成默认REQUIRED,即调用方法之前有事务,则运用之前的事务,否则新建一个事务 -->
            <tx:method name="add*"/>
        </tx:attributes>
    </tx:advice>

@Transactional增加事务,xml方式配置都配置到application.xml里
@Resource注入组件

四。服务组件
用户服务
public interface UserDAO {
	public void save(User u);
}

@Component
public class UserDAOImpl implements UserDAO{
	
	private SessionFactory sessionFactory;
	
	public void save(User u) {
		Session s = sessionFactory.getCurrentSession();
		s.save(u);
		throw new RuntimeException("error!!!!!");
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}

抛出异常作测试,注入sessionFactory.

public interface LogDAO {
	public void save(Log log);
}

@Component
public class LogDAOImpl implements LogDAO{
	
	private SessionFactory sessionFactory;
	
	public void save(Log log){
		Session s = sessionFactory.getCurrentSession();
		s.save(log);
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}


五。实体类
@Entity 
@Table(name="Users")
public class User {
	private int id;
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	@Id
	@GeneratedValue
	@Column(name="USER_ID")
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}


@Entity 
@Table(name="log")
public class Log {
	private int id;
	private String message;
	

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}

@Entity 声明实体类
@Table映射表设置
@Column设置属性对映表中的列

六。测试结果
数据报错则回滚!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics