Spring

Spring的相关概念:

  1. Spring是一个开源的,轻量级的框架,轻量级的意思是依赖的东西比较少。
  2. spring的核心功能是aop(面向切面编程),ioc(控制反转)
    2.1 aop:在不改源代码的情况下去增加功能。
    2.2 ioc:不需要自己去new对象了,可以交给spring去创建。
  3. spring是一站式框架:spring在javaee三层中都提供了相应的解决方案。
    3.1 web层 springMvc
    3.2 service ioc
    3.3 jdbcTemplate
  4. spring的IOC操作:
    4.1 把对象的创建交给ioc进行管理。
    4.2 ioc可以通过配置文件或者注解的方式的实现。
  5. IOC的底层原理:
    5.1 使用xml的配置文件。
    5.2 利用dom4j去解析xml文件。
    5.3 利用工厂设计模式。
    5.4 使用反射技术。
    这里写图片描述

入门案例:

  1. 导入相关的jar包
    1.1 spring相关的功能
    这里写图片描述
    1.2 一般只要导入核心的jar就好了,最后还要导入支持日志输出的jar包。
  2. 创建类,并添加相应的方法
    这里写图片描述
  3. 创建spring相关的配置文件
    3.1 名字可以自己取,建议使用applicationContext,位置也是不固定的,建议位于src下。
    3.2 配置对象创建

    <?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:p="http://www.springframework.org/schema/p"
            xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
            <bean id="user" class="com.renwen.user.User"></bean>
    </beans>
    
  4. 进行测试
    这里写图片描述

spring bean管理:

  1. bean实例化的三种方式:
    1.1 使用无参的构造函数进行创建(重点):
    这里写图片描述
    1.2 使用静态工厂进行创建:即静态方法返回类对象
    这里写图片描述
    这里写图片描述
    1.3 使用实例工程进行创建:即实例方法返回类对象
    这里写图片描述
    这里写图片描述

  2. bean标签常用的属性:
    2.1 id属性:可以通过id来得到某个类的实例对象。
    2.2 class属性:配置对象所在的全路径。
    2.3 name属性:和id的功能基本相同,但是id的命名不可以有特殊符号,但是name属性可以,且name属性可以为同一个bean配置多个名字(基本不用了)。
    2.4 scope属性:singleton:单例的且是默认 prototype:多例

  3. 属性注入:创建对象的时候,向类里面的属性设置相应的值。
    3.1 使用属性的setter方法进行注入(重点)
    这里写图片描述
    这里写图片描述
    3.2 有参数的构造函数的方法进行注入
    这里写图片描述
    这里写图片描述

  4. 对象注入:

    public class Dao {
        public void  add() {
            System.out.println("dao add");
        }
    }
    public class Service {
        private Dao dao;
        public void add() {
            System.out.println("add....");
            dao.add();
        }
        public void setDao(Dao dao) {
            this.dao = dao;
        }
    }
    <bean id="dao" class="com.renwen.test.Dao"></bean>
    <bean id="service" class="com.renwen.test.Service">
        <property name="dao" ref="dao"></property>
    </bean>
    
  5. p名称空间的注入:
    5.1 第一步引入p名称空间的约束

    public class User {
            private String uname;
            public void show(){
                System.out.println(uname);
            }
            public void setUname(String uname){
                this.uname=uname;
            }
    }
    <bean id="service" class="com.renwen.test.Service">
            <property p:uname="zhao"></property>
    </bean>
    
  6. 注入负责数据类型(数组,list,map,properties)

    public class User {
        private String[]array;
        private Map<String,String>map;
        private List<String>list;
        private Properties properties;
        public void setArray(String[] array) {
            this.array = array;
        }
        public void setMap(Map<String, String> map) {
            this.map = map;
        }
        public void setList(List<String> list) {
            this.list = list;
        }
        public void setProperties(Properties properties) {
            this.properties = properties;
        }
        public void test() {
            for(String str:array){
                System.out.println(str);
            }
            for(String str:list){
                System.out.println(str);
            }
            Set<String>keySet=map.keySet();
            Iterator<String>it=keySet.iterator();
            while(it.hasNext()){
                System.out.println(map.get(it.next()));
            }
            System.out.println(properties);
        }
    }
    <bean id="user" class="com.renwen.user.User">
            <!-- 数组注入 -->
            <property name="array">
                <array>
                    <value>zhangsan1</value>
                    <value>zhangsan2</value>
                    <value>zhangsan3</value>
                </array>
            </property>
            <!-- list注入 -->
            <property name="list">
                <list>
                    <value>lisi1</value>
                    <value>lisi2</value>
                    <value>lisi3</value>
                </list>
            </property>
            <!-- map注入 -->
            <property name="map">
                <map>
                    <entry key="lisi1" value="zhangsan1"></entry>
                    <entry key="lisi2" value="zhangsan2"></entry>
                    <entry key="lisi3" value="zhangsan3"></entry>
                </map>
            </property>
            <!--property注入-->
            <property name="properties">
                <props>
                    <prop key="url">jdbc:mysql:/127.0.0.1</prop>
                    <prop key="username">root</prop>
                </props>
            </property>
    </bean>
    

IOC 和DI的区别:

  1. IOC:控制反转,把创建对象交给spring。
  2. DI: 依赖注入,例如在进行对象创建的时候,我们可以为属性设置相应的值。
  3. 关系:依赖不能单独存在,需要在ioc基础上完成操作。

Spring整合web项目的原理:

  1. 加载spring核心配置文件,根据核心配置文件来进行创建对象。

    ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
    

    但是效率比较差,解决方法可以在服务器启动的时候进行创建,并加载spring配置文件。

  2. 实现原理:
    2.1 使用ServletContext对象
    2.2 使用监听器
    2.3 具体使用:
    在服务器启动的时候会为我们创建一个唯一的servletContext对象,然后通过ServletContextListener来监听servletContext的产生,在该对象创建之前,可以创建配置文件加载的对象,然后将该对象放入context域中。

Spring 注解管理bean

  1. 注解介绍:
    1.1 代码里面的特殊标记,完成特定的功能。
    1.2 注解的写法 @注解名(属性名称=属性值)。
    1.3 注解可以使用在类上面,方法上面,属性上面。
  2. 注解开发案例:
    2.1 导入注解开发相应的jar包,引入相应得约束文件
  3. 注解创建对象:

    @Component(value="user")
    @Scope(value="prototype")//多实例
    public class User {
        public void show(){
            System.err.println("show....");
        }
    }
    public class TestSpring {
        @Test
        public void test(){
            ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
            User user=(User) ac.getBean("user");
            user.show();
        }
    }
    

    4 创建对象4个常用注解:
    4.1 @Component
    4.2 @Controller WEB层
    4.3 @Service service层
    4.4 @Respository dao层
    目前这四个注解的功能都一样,创建对象

  4. 属性注入:
    5.1 使用注解的方法进行注入的时候,不需要setter方法
    5.2 autowired进行注入

    @Repository(value="dao")
    public class Dao {
        public void  add() {
            System.out.println("dao add");
        }
    }
    @Component("service")
    public class Service {
        @Autowired
        private Dao dao;
        public void add() {
            System.out.println("service add....");
            dao.add();
        }
    }
    

    5.3 Resource进行注入

    @Repository(value="dao")
        public class Dao {
            public void  add() {
                System.out.println("dao add");
        }
    }
    @Component("service")
    public class Service {
        @Resource(name="dao")
        private Dao dao;
        public void add() {
            System.out.println("service add....");
            dao.add();
        }
    }
    

    5.4 注解与配置文件混合使用:

    public class Dao {
        public void  add() {
            System.out.println("dao add");
    }
    public class OrderDao {
        public void buy() {
            System.out.println("Order buy....");
        }
    }
    public class Service {
        @Resource(name="dao")
        private Dao dao;
        @Resource(name="orderDao")
        private OrderDao orderDao;
        public void add() {
            System.out.println("service add....");
            dao.add();
            orderDao.buy();
        }
    }
    <bean id="dao" class="com.renwen.test.Dao"></bean>
    <bean id="orderDao" class="com.renwen.test.OrderDao"></bean>
    <bean id="service" class="com.renwen.test.Service"></bean>
    

AOP :

  1. AOP概述:面向切面编程,扩展功能不通过修改源代码来实现。
  2. AOP采取横向抽取机制,取代了传统纵向继承体系的重复性代码。
  3. 相关的原理:
    这里写图片描述
    这里写图片描述

AOP 操作的相关术语:

这里写图片描述

Spring相关的AOP操作:

  1. 在spring中进行aop操作,使用aspectj来实现,aspecj是一个面向切面的框架,使用之前应该导入相应的jar包,且导入aop的相关约束。
  2. aspecj并不是spring的一部分。
  3. 使用aspectj实现aop的两种方式
    3.1 基于xml
    这里写图片描述

    <bean id="book" class="com.renwen.aop.Book"></bean>
    <bean id="mybook" class="com.renwen.aop.MyBook"></bean>
    <aop:config>
            <!--配置切入点-->
            <aop:pointcut expression="execution(* com.renwen.aop.Book.add(..))" id="addcut"/>
            <!--配置切面-->
            <aop:aspect ref="mybook">
                <aop:before method="Before1" pointcut-ref="addcut"/>
            </aop:aspect>
    </aop:config>
    

    环绕增强:

    public class MyBook {
        public void around(ProceedingJoinPoint point) throws Throwable{
            System.out.println("前");
            point.proceed();
            System.out.println("后");
        }
    }
    <aop:config>
    <!--配置切入点-->
    <aop:pointcut expression="execution(* com.renwen.aop.Book.add(..))" id="addcut"/>
    <!--配置切面-->
    <aop:aspect ref="mybook">
        <!-- <aop:before method="before1" pointcut-ref="addcut"/> -->
        <aop:around method="around" pointcut-ref="addcut"/>
    </aop:aspect>
    


    3.2 基于注解

log4J的介绍:

  1. 通过log4j可以看到程序运行中更加相信的信息。
  2. 可以通过它来查看日志
  3. 需要导入jar包并且导入配置文件到src下
  4. log4j.properties

    log4j.rootLogger=INFO, CONSOLE, FILE  
    ## for console  
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender  
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout  
    log4j.appender.CONSOLE.layout.ConversionPattern=%d{MM-ddHH:mm:ss}[%c-%L][%t][%-4r] - %m%n  
    ## for file  
    log4j.appender.FILE=org.apache.log4j.RollingFileAppender  
    log4j.appender.FILE.File=D:/logs/log4j.log  
    log4j.appender.FILE.MaxFileSize=1MB  
    log4j.appender.FILE.Append = true  
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  
    log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss} [%t] %-5p %c(line-%L) %-4r %x - %m%n  
    

注解AOP配置

  1. 创建相关配置文件,创建对象。
  2. 开启aop扫描。

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    
  3. 在增强的类上面使用注解来完成aop的操作。
  4. 注解设置

    @Aspect
    public class MyBook {
        @Before("execution(* com.renwen.aop.Book.add(..))")
        public void before1(){
            System.out.println("前置增强...");
        }
    }
    

Spring 的jdbcTemplate操作:

  1. jdbctemplate对jdbc做了封装
  2. 配置数据源:
  3. 相关操作

    public class DataSource {
                private static DriverManagerDataSource dataSource=null;
                static{
                    dataSource=new DriverManagerDataSource();
                    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                    dataSource.setUrl("jdbc:mysql://localhost:3306/hibernate");
                    dataSource.setPassword("zhaoliyou");
                    dataSource.setUsername("root");
                }
                public static DriverManagerDataSource getDataSource(){
                    return dataSource;
                }
    }
    3. 相关操作:
    
        public class JdbcTemplateTest {
        private static DriverManagerDataSource dataSource=DataSource.getDataSource();
                @Test
                public void add(){
                    JdbcTemplate template=new JdbcTemplate(dataSource);
                    String sql="insert into user(uname,pwd) values(?,?)";
                    int rows=template.update(sql,"zhangsan","123");
                    System.out.println(rows);
                }
                @Test
                public void update(){
                    JdbcTemplate template=new JdbcTemplate(dataSource);
                    String sql="update user set uname=? where uname=?";
                    int rows=template.update(sql,"lisi","zhangsan");
                    System.out.println(rows);
                }
                @Test
                public void delete(){
                    JdbcTemplate template=new JdbcTemplate(dataSource);
                    String sql="delete from user where uname=?";
                    int rows=template.update(sql,"lisi");
                    System.out.println(rows);
                }
                //对于结果集的处理,jdbctemplate有自己的接口RowMapper,但是需要自己进行实现
                @Test
                public void query(){
                    JdbcTemplate template=new JdbcTemplate(dataSource);
                    //查询返回一个值
                    String sql="select count(*) from user";
                    int rows=template.queryForObject(sql, Integer.class);
                    System.out.println(rows);
    
                    //返回某个对象
                    String sql2="select * from user where uname=?";
                    User user=template.queryForObject(sql2, new UserMapper(),"zhangsan");
                    System.out.println(user);
    
                    //返回List集合
                    String sql3="select * from user";
                    List<User>list=template.query(sql2, new UserMapper());
                    System.out.println(list);
    
                }
    }
    class UserMapper implements RowMapper<User>{
    
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                String uname=rs.getString("uname");
                String pwd=rs.getString("pwd");
                User user=new User();
                user.setPwd(pwd);
                user.setUname(uname);
                return user;
            }
    }
    

Spring 配置c3p0连接池,dao使用jdbcTemplate

  1. 原始配置c3p0:
    这里写图片描述

    public class User {
        private String uname;
        private String pwd;
        public String getUname() {
            return uname;
        }
        public String getPwd() {
            return pwd;
        }
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
        public void setUname(String uname) {
            this.uname = uname;
        }
        @Override
        public String toString() {
            return "User [uname=" + uname + ", pwd=" + pwd + "]";
        }
    }
    public class UserDao {
        private JdbcTemplate jdbcTemplate;
        public void add(User user){
            String sql="insert into user values(?,?)";
            jdbcTemplate.update(sql,user.getUname(),user.getPwd());
        }
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    }
    public class UserService {
        private UserDao userDao;
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
        public void add(User user) {
            System.out.println("service add");
            userDao.add(user);
        }
    }
    
    <!-- 创建数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate"></property>
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="user" value="root"></property>
            <property name="password" value="zhaoliyou"></property>
        </bean>
        <!--创建jdbcTemplate并且注入数据源  -->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 创建UserDao,且注入jdbc模板-->
        <bean id="userDao" class="com.renwen.test.UserDao">
            <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        </bean>
        <!-- 创建userService并且注入Userdao-->
        <bean id="userService" class="com.renwen.test.UserService">
            <property name="userDao" ref="userDao"></property>
        </bean>
    

Spring事务管理:

  1. 事务管理的两种方式:
    1.1 编程式事务管理
    1.2 声明式事务管理:基于xml或者注解方式实现。
  2. spring进行事务管理的一些api操作:
    2.1 PlatformTransactionManger:事务管理器
    这里写图片描述
    不同的持久层框架有不同的事务管理器
    2.2 TransactionDefinition:事务定义信息
    2.3 TransactionStatus :事务运行状态
    3.xml事务管理:

    public class Accountant {
        private int id;
        private String uname;
        private double balance;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUname() {
            return uname;
        }
        public void setUname(String uname) {
            this.uname = uname;
        }
        public double getBalance() {
            return balance;
        }
        public void setBalance(double balance) {
            this.balance = balance;
        }
    
    }
    public class OrderDao {
        private JdbcTemplate jdbcTemplate;
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
        public void addMoney(Accountant accountant,double money){
            String sql="update accountant set balance=balance+? where id=?";
            jdbcTemplate.update(sql,money,accountant.getId());
        }
        public void lessMoney(Accountant accountant,double money){
            String sql="update accountant set balance=balance-? where id=?";
            jdbcTemplate.update(sql,money,accountant.getId());
        }
    }
    public class OrderService {
        private OrderDao orderDao;
        public void setOrderDao(OrderDao orderDao) {
            this.orderDao = orderDao;
        }
        public void changeMoney(Accountant accountant1,Accountant accountant2,double money){
            orderDao.addMoney(accountant1, money);
            int num=1/0;
            orderDao.lessMoney(accountant2, money);
        }
    
    }
    
    <?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/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">
        <!-- 创建数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate"></property>
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="user" value="root"></property>
            <property name="password" value="zhaoliyou"></property>
        </bean>
        <!--创建jdbcTemplate并且注入数据源  -->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <bean id="orderDao" class="com.renwen.test.OrderDao">
            <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        </bean>
        <bean id="orderService" class="com.renwen.test.OrderService">
            <property name="orderDao" ref="orderDao"></property>
        </bean>
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--配置事务增强-->
        <tx:advice id="txadvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="changeMoney" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
        <!--配置切面 -->
        <aop:config>
            <aop:pointcut expression="execution(* com.renwen.test.OrderService.*(..))" id="mycut"/>
            <aop:advisor advice-ref="txadvice" pointcut-ref="mycut"/>
        </aop:config>
    </beans>
    
  3. 注解配置事务:
    4.1 配置事务管理器
    4.2 开始事务注解扫描
    4.3 在需要事务处理的方法或者类上加 @Transational

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解  -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    @Transactional
    public void changeMoney(Accountant accountant1,Accountant accountant2,double money){
        orderDao.addMoney(accountant1, money);
        int num=1/0;
        orderDao.lessMoney(accountant2, money);
    }
    

SSH整合:

  1. 思想:
    这里写图片描述
  2. spring整合struts2
    2.1 记得导入struts2.spring-plugin和spring-web包
    2.2 配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>ssh</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
    </web-app>
    

    2.3 配置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/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/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">
        <bean id="userAction" class="com.renwen.action.UserAction" scope="prototype"></bean>
    </beans>
    

    2.4 配置struts.xml

    <struts>
        <package name="mypack" extends="struts-default" namespace="/">
            <action name="userAction" class="userAction">
                <result name="ok">/index.jsp</result>
            </action>
        </package>
    </struts> 
    
  3. spring 整合hibernate
    3.1 把我们的数据库的基本信息在spring进行配置。
    3.2 sessionfactory在spring中进行创建。
    3.3 注意需要spring-orm的jar

整合完整案例:

  1. action

    package com.renwen.action;
    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.ModelDriven;
    import com.renwen.entity.User;
    import com.renwen.service.UserService;
    public class UserAction extends ActionSupport implements ModelDriven<User>{
        private User user=new User();
        private UserService userService;
        @Override
        public String execute() throws Exception {
            userService.change(1, 2, 50);
            return "ok";
        }
        public void setUserService(UserService userService) {
            this.userService = userService;
        }
        public User getUser() {
            return user;
        }
        public void setUser(User user) {
            this.user = user;
        }
        @Override
        public User getModel() {
            // TODO Auto-generated method stub
            return user;
        }
    }
    
  2. service

    package com.renwen.service;
    import org.springframework.transaction.annotation.Transactional;
    import com.renwen.dao.UserDao;
    import com.renwen.entity.User;
    
    public class UserService {
        private UserDao userDao;
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
        @Transactional
        public void change(int id1,int id2,int money){
            userDao.add(id1, 50);
            int num=1/0;
            userDao.less(id2, 50);
        }
    }
    
  3. dao

    package com.renwen.dao;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.renwen.entity.Accountant;
    import com.renwen.entity.User;
    public class UserDao {
        private SessionFactory sessionFactory;
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
        public void add(int id,int money){
            Session session=sessionFactory.getCurrentSession();
            Accountant accountant=(Accountant) session.get(Accountant.class, id);
            accountant.setBalance(accountant.getBalance()+money);
            session.save(accountant);
        }
        public void less(int id,int money){
            Session session=sessionFactory.getCurrentSession();
            Accountant accountant=(Accountant) session.get(Accountant.class, id);
            accountant.setBalance(accountant.getBalance()-money);
            session.save(accountant);
        }
    }
    
  4. entity:

    package com.renwen.entity;
    public class Accountant {
        private int id;
        private String uname;
        private double balance;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUname() {
            return uname;
        }
        public void setUname(String uname) {
            this.uname = uname;
        }
        public double getBalance() {
            return balance;
        }
        public void setBalance(double balance) {
            this.balance = balance;
        }
    
    }
    
  5. hibernate.cfg.xml配置文件:

    <?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">
    <!-- Generated by MyEclipse Hibernate Tools.                   -->
    <hibernate-configuration>
        <session-factory>
    
            <property name="hibernate.show_sql">true</property>
            <!-- 格式化输出sql语句 -->
            <property name="hibernate.format_sql">true</property>
            <!-- update如果有这个表了,就会更新,否则就会创建表 -->
            <property name="hibernate.hbm2ddl.auto">update</property>
            <!-- 数据库方言 -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- 把映射文件放到核心配置文件中 -->
            <mapping resource="com/renwen/entity/User.hbm.xml"/>
            <mapping resource="com/renwen/entity/Accountant.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
    <?xml version="1.0"?>    
    
  6. Accountant.hbm.xml

    <!DOCTYPE hibernate-mapping PUBLIC     
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="com.renwen.entity.Accountant"  table="accountant">
            <id name="id" column="id">
                <generator class="native"></generator>
            </id>
            <property name="uname" column="uname"></property>
            <property name="balance" column="balance"></property>
        </class>
    </hibernate-mapping>
    
  7. 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/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/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate"></property>
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="user" value="root"></property>
            <property name="password" value="zhaoliyou"></property>
        </bean>
        <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource"><ref bean="dataSource" /></property>
            <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
        </bean>
        <bean id="userService" class="com.renwen.service.UserService">
            <property name="userDao" ref="userDao"></property>
        </bean>
        <bean id="userAction" class="com.renwen.action.UserAction" scope="prototype">
            <property name="userService" ref="userService"></property>
        </bean>
        <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
    </beans>   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值