SSM 复习总结

Spring

spring 项目中对象容器,帮我们管理项目中的所有对象

Spring 就是一个大工厂,可以将所有对象创建和依赖关系维护,交给 Spring 管理
AOP 编程的支持

Spring 提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能
声明式事务的支持

只需要通过配置就可以完成对事务的管理,而无需手动编程
方便程序的测试

Spring 对 Junit4 支持,可以通过注解方便的测试 Spring 程序
方便集成各种优秀框架

Spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts、Hibernate、MyBatis、Quartz 等)的直接支持

Spring搭建

1. 下载Spring 的开发包:

比如下spring-framework-4.2.4.RELEASE 包

2. 把需要的包放到lib下4+2 4个核心包+2个日志:

图1
在WEB环境中使用Spring容器

1>导包 4+2+1(spring-web)

2>在web.xml中配置listener => ContextLoaderListener

|-配置参数,指定spring配置路径

3>在Action中,使用工具类获得容器.

|-WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)

3. 创建一个对象

 package cn.itcast.bean;
public class User {
    public User() {
            System.out.println("User对象空参构造方法!!!!");
    }
    private String name;
    private Integer age;
    private Car car;

    public User(String name, Car car) {
        System.out.println("User(String name, Car car)!!");
        this.name = name;
        this.car = car;
    }
    public User(Car car,String name) {
        System.out.println("User(Car car,String name)!!");
        this.name = name;
        this.car = car;
    }
    public User(Integer name, Car car) {
        System.out.println("User(Integer name, Car car)!!");
        this.name = name+"";
        this.car = car;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    public void init(){
        System.out.println("我是初始化方法!");
    }
    public void destory(){
        System.out.println("我是销毁方法!");
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
    }

}

4. 创建配置文件applicationContext.xml,导入约束

1.window->Preferences->搜cata,架<br>
2.点add->File System 选schema>beans>spring-beans-4.2.xsd架<br>
3.然后
![图2](2.jpg)
导入约束完成架<br>
4.xml文件中写beans,然后设计视图,右键 Edit Namespaces,然后Add,导入xsi,<br>
![图3](3.jpg)
![图4](4.jpg) 

在点add,选择Specify New Namespace,Browse..>
Select XML Catalog entry选择
图5
图6
图7

applicationContext.xml 导入成功后<会有提示的
引入约束:
spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configur
ation.html
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 将User对象交给spring容器管理 -->
    <!-- Bean元素:使用该元素描述需要spring容器管理的对象
            class属性:被管理对象的完整类名.
            name属性:给被管理的对象起个名字.获得对象时根据该名称获得对象.  
                    可以重复.可以使用特殊字符.
            id属性: 与name属性一模一样. 
                    名称不可重复.不能使用特殊字符.
            结论: 尽量使用name属性.
            Scope:Prototype 多例,singletion 单例
      -->
    <!-- 方式一-->      
<bean  name="user" class="cn.itcast.bean.User" ></bean>
    <!--静态工厂创建  调用UserFactory的createUser方法创建名为user2的对象.放入容器 -->     
<bean  name="user2" 
        class="cn.itcast.b_create.UserFactory" 
        factory-method="createUser" ></bean>
        <!-- 创建方式3:实例工厂创建 
         调用UserFactory对象的createUser2方法创建名为user3的对象.放入容器
         <bean  name="user3" 
        factory-bean="userFactory"
        factory-method="createUser2" ></bean>

    <bean  name="userFactory" 
        class="cn.itcast.b_create.UserFactory"   ></bean>
     -->
</beans>

5. 测试

public class Demo {
    @Test
    public void fun1(){

        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*//2 向容器"要"user对象
        User u = (User) ac.getBean("user");
        //3 打印user对象
        System.out.println(u);*/
    }
        @Test
    public void fun2(){
            //1 创建容器对象
            ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_create/applicationContext.xml");
            //2 向容器"要"user对象
            User u = (User) ac.getBean("user2");
            //3 打印user对象
            System.out.println(u);
    }
    //创建方式3:实例工厂
                @Test
                public void fun3(){
                    //1 创建容器对象
                    ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/b_create/applicationContext.xml");
                    //2 向容器"要"user对象
                    User u = (User) ac.getBean("user3");
                    //3 打印user对象
                    System.out.println(u);
                }

}

package cn.itcast.b_create;

import cn.itcast.bean.User;

public class UserFactory {

    public static User createUser(){

        System.out.println("静态工厂创建User");

        return new User();

    }

    public  User createUser2(){

        System.out.println("实例工厂创建User");

        return new User();

    }

}


Spring 依赖注入

IOC 反转控制:对象的创建以及依赖关系可以由spring完成创建以及注入

DI 依赖注入: 需要有 IOC 的环境,Spring 创建这个类的过程中,Spring 将类的依
赖的属性设置进去
注入方式:set方法注入,构造方法注入,字段注入,注入类型:值类型,引用类型

注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:p="http://www.springframework.org/schema/p"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">

    <!-- set方式注入: -->
    <bean  name="user" class="cn.itcast.bean.User" >
        <!--值类型注入: 为User对象中名为name的属性注入tom作为值 -->
        <property name="name" value="tom" ></property>
        <property name="age"  value="18" ></property>
        <!-- 引用类型注入: 为car属性注入下方配置的car对象 -->
        <property name="car"  ref="car" ></property>
    </bean>

    <!-- 将car对象配置到容器中 -->
    <bean name="car" class="cn.itcast.bean.Car" >
        <property name="name" value="兰博基尼" ></property>
        <property name="color" value="黄色" ></property>
    </bean>
<!-- ============================================================ -->
    <!-- 构造函数注入 -->
<bean name="user2" class="cn.itcast.bean.User" >
    <!-- name属性: 构造函数的参数名 -->
    <!-- index属性: 构造函数的参数索引 -->
    <!-- type属性: 构造函数的参数类型-->
    <constructor-arg name="name" index="0" type="java.lang.Integer" value="999"  ></constructor-arg>
    <constructor-arg name="car" ref="car" index="1" ></constructor-arg>
</bean>
</bean>
package cn.itcast.c_injection;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.bean.User;

public class Demo {
    @Test
    public void fun1(){

        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/c_injection/applicationContext.xml");
        //2 向容器"要"user对象
        User u = (User) ac.getBean("user");
        //3 打印user对象
        System.out.println(u);

    }
    @Test
    public void fun2(){

        //1 创建容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/c_injection/applicationContext.xml");
        //2 向容器"要"user对象
        User u = (User) ac.getBean("user2");
        //3 打印user对象
        System.out.println(u);

    }

Spring 注解配置

导入新的约束 spring-context-4.2.xsd,一样加xml命名空间
图8

 applicationContext.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!-- 指定扫描cn.itcast.bean报下的所有类中的注解.
     注意:扫描包时.会扫描指定报下的所有子孙包
 -->
<context:component-scan base-package="cn.itcast.bean"></context:component-scan>

<bean name="car2" class="cn.itcast.bean.Car"  >
    <property name="name" value="布加迪威龙" ></property>
    <property name="color" value="black"  ></property>
</bean>
</beans>
 User.java
 package cn.itcast.bean;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.xml.ws.RespectBinding;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

//<bean name="user" class="cn.itcast.bean.User"  />
//@Component("user")
//    @Service("user") // service层
//    @Controller("user") // web层
    @Repository("user")// dao层
//指定对象的作用范围
@Scope(scopeName="singleton")
public class User {
    private String name;
    @Value("18")
    private Integer age;

    //@Autowired //自动装配
    //问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象.
    //@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象
    @Resource(name="car")//手动注入,指定注入哪个名称的对象
    private Car car;

    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    public String getName() {
        return name;
    }
    @Value("tom")    
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @PostConstruct //在对象被创建后调用.init-method
    public void init(){
        System.out.println("我是初始化方法!");
    }
    @PreDestroy //在销毁之前调用.destory-method
    public void destory(){
        System.out.println("我是销毁方法!");
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
    }

}

Spring junit测试

加入spring-test包:
图9

 package cn.itcast.b_test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.itcast.bean.User;
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器时使用哪个配置文件,要在src下面
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    //将名为user的对象注入到u变量中
    @Resource(name="user")
    private User u;

    @Test
    public void fun1(){

        System.out.println(u);

    }

    @Test
    public void fun2(){

        System.out.println(u);

    }

    @Test
    public void fun3(){

        System.out.println(u);

    }
}

Spring AOP切面编程

1.导包 4+2+2+2

前面一样,后面的包:
spring的aop包:

spring-aspects-4.2.4.RELEASE.jar

spring-aop-4.2.4.RELEASE.jar

spring需要第三方aop包:

com.springsource.org.aopalliance-1.0.0.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

图10

2.准备目标对象

package cn.itcast.service;

public class UserServiceImpl implements UserService {
    @Override
    public void save() {
        System.out.println("保存用户!");
        //int i = 1/0;
    }
    @Override
    public void delete() {
        System.out.println("删除用户!");
    }
    @Override
    public void update() {
        System.out.println("更新用户!");
    }
    @Override
    public void find() {
        System.out.println("查找用户!");
    }
}

3.准备通知

 package cn.itcast.d_springaop;

import org.aspectj.lang.ProceedingJoinPoint;

//通知类
public class MyAdvice {

    //前置通知    
//        |-目标方法运行之前调用
    //后置通知(如果出现异常不会调用)
//        |-在目标方法运行之后调用
    //环绕通知
//        |-在目标方法之前和之后都调用
    //异常拦截通知
//        |-如果出现异常,就会调用
    //后置通知(无论是否出现 异常都会调用)
//        |-在目标方法运行之后调用
//----------------------------------------------------------------
    //前置通知
    public void before(){
        System.out.println("这是前置通知!!");
    }
    //后置通知
    public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }
    //环绕通知
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法
        System.out.println("这是环绕通知之后的部分!!");
        return proceed;
    }
    //异常通知
    public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }
    //后置通知
    public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}

4.配置进行织入,将通知织入目标对象中

 applicationContext.xml 
 导入新的约束 spring-aop-4.2.xsd,一样加xml命名空间
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

<!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
    <bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
    <bean name="myAdvice" class="cn.itcast.d_springaop.MyAdvice" ></bean>
<!-- 3.配置将通知织入目标对象 -->
    <aop:config>
        <!-- 配置切入点 
            public void cn.itcast.service.UserServiceImpl.save() 
            void cn.itcast.service.UserServiceImpl.save()
            * cn.itcast.service.UserServiceImpl.save()
            * cn.itcast.service.UserServiceImpl.*()

            * cn.itcast.service.*ServiceImpl.*(..)
            * cn.itcast.service..*ServiceImpl.*(..)
        -->
        <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="pc"/>
        <aop:aspect ref="myAdvice" >
            <!-- 指定名为before方法作为前置通知 -->
            <aop:before method="before" pointcut-ref="pc" />
            <!-- 后置 -->
            <aop:after-returning method="afterReturning" pointcut-ref="pc" />
            <!-- 环绕通知 -->
            <aop:around method="around" pointcut-ref="pc" />
            <!-- 异常拦截通知 -->
            <aop:after-throwing method="afterException" pointcut-ref="pc"/>
            <!-- 后置 -->
            <aop:after method="after" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>
</beans>
--测试
  package cn.itcast.d_springaop;

  import javax.annotation.Resource;

  import org.junit.Test;
  import org.junit.runner.RunWith;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.support.ClassPathXmlApplicationContext;
  import org.springframework.test.context.ContextConfiguration;
  import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

  import cn.itcast.bean.User;
  import cn.itcast.service.UserService;
  @RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration("classpath:cn/itcast/d_springaop/applicationContext.xml")
  public class Demo {
      @Resource(name="userService")
      private UserService us;

      @Test
      public void fun1(){
          us.save();
      }

  }

用注解的写法

  applicationContext.xml 
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">

<!-- 准备工作: 导入aop(约束)命名空间 -->
<!-- 1.配置目标对象 -->
    <bean name="userService" class="cn.itcast.service.UserServiceImpl" ></bean>
<!-- 2.配置通知对象 -->
    <bean name="myAdvice" class="cn.itcast.e_annotationaop.MyAdvice" ></bean>
<!-- 3.开启使用注解完成织入 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>
 package cn.itcast.e_annotationaop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

//通知类
@Aspect
//表示该类是一个通知类
public class MyAdvice {
    @Pointcut("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void pc(){}
    //前置通知
    //指定该方法是前置通知,并制定切入点
    @Before("MyAdvice.pc()")
    public void before(){
        System.out.println("这是前置通知!!");
    }
    //后置通知
    @AfterReturning("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void afterReturning(){
        System.out.println("这是后置通知(如果出现异常不会调用)!!");
    }
    //环绕通知
    @Around("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("这是环绕通知之前的部分!!");
        Object proceed = pjp.proceed();//调用目标方法
        System.out.println("这是环绕通知之后的部分!!");
        return proceed;
    }
    //异常通知
    @AfterThrowing("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void afterException(){
        System.out.println("出事啦!出现异常了!!");
    }
    //后置通知
    @After("execution(* cn.itcast.service.*ServiceImpl.*(..))")
    public void after(){
        System.out.println("这是后置通知(出现异常也会调用)!!");
    }
}
测试还是上面一样的测

spring整合JDBC

导包

4+2+spring-test,spring-aop,junit4类库
c3p0连接池,JDBC驱动,spring-jdbc,spring-tx事务

图11

Dao

package cn.itcast.a_jdbctemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cn.itcast.bean.User;
//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        String sql = "insert into t_user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  t_user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        String sql = "select * from t_user where id = ? ";
        return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);

    }
    @Override
    public int getTotalCount() {
        String sql = "select count(*) from t_user  ";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from t_user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

applicationContext.xml配置

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>


<!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

<!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
    <!-- <property name="jt" ref="jdbcTemplate" ></property> -->
    <property name="dataSource" ref="dataSource" ></property>
</bean>
</beans>

db.properties
jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234

测试

 package cn.itcast.a_jdbctemplate;

import java.beans.PropertyVetoException;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.itcast.bean.User;

//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
        @Resource(name="userDao")
    private UserDao ud;

    @Test
    public void fun1() throws Exception{

        //0 准备连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql:///hibernate_32");
        dataSource.setUser("root");
        dataSource.setPassword("1234");
        //1 创建JDBC模板对象
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);
        //2 书写sql,并执行
        String sql = "insert into t_user values(null,'rose') ";
        jt.update(sql);

    }

    @Test
    public void fun2() throws Exception{
        User u = new User();
        u.setName("tom");
        ud.save(u);
    }
    @Test
    public void fun3() throws Exception{
        User u = new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);

    }

    @Test
    public void fun4() throws Exception{
        ud.delete(2);
    }

    @Test
    public void fun5() throws Exception{
        System.out.println(ud.getTotalCount());
    }

    @Test
    public void fun6() throws Exception{
        System.out.println(ud.getById(1));
    }

    @Test
    public void fun7() throws Exception{
        System.out.println(ud.getAll());
    }

}

事务

导入新的约束

spring-tx-4.2.4.RELEASE

图12

事务配置

 applicationContext.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
</bean>

<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
        <!-- 以方法为单位,指定方法应用什么事务属性
            isolation:隔离级别
            propagation:传播行为
            read-only:是否只读
         -->
        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
    </tx:attributes>
</tx:advice>


<!-- 配置织入 -->
<aop:config  >
    <!-- 配置切点表达式 -->
    <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc"/>
    <!-- 配置切面 : 通知+切点
             advice-ref:通知的名称
             pointcut-ref:切点的名称
     -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>


<!-- 1.将连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>



<!-- 2.Dao-->
<bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
    <property name="tt" ref="transactionTemplate" ></property>
</bean>  

</beans>
 AccountDaoImpl.java
 package cn.itcast.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao  {

    @Override
    public void increaseMoney(Integer id, Double money) {

        getJdbcTemplate().update("update t_account set money = money+? where id = ? ", money,id);

    }

    @Override
    public void decreaseMoney(Integer id, Double money) {

        getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id);
    }

}

测试

 package cn.itcast.tx;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.itcast.service.AccountService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
        @Resource(name="accountService")
    private AccountService as;

    @Test
    public void fun1(){

        as.transfer(1, 2, 100d);

    }
}

注解配置

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
</bean>

<!-- 开启使用注解管理aop事务 -->
<tx:annotation-driven/>

<!-- 1.将连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>



<!-- 2.Dao-->
<bean name="accountDao" class="cn.itcast.dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
    <property name="tt" ref="transactionTemplate" ></property>
</bean>  

</beans>
  AccountServiceImpl.java
  package cn.itcast.service;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import cn.itcast.dao.AccountDao;

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService {

    private AccountDao ad ;
    private TransactionTemplate tt;

    @Override
    @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
    public void transfer(final Integer from,final Integer to,final Double money) {
                //减钱
                ad.decreaseMoney(from, money);
                int i = 1/0;
                //加钱
                ad.increaseMoney(to, money);
    }
    public void setAd(AccountDao ad) {
        this.ad = ad;
    }
    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }
}

MyBatis

导包

下载mybatis
加入mybatis包和mysql驱动包

xml 一般使用

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 写Sql语句   -->
<mapper namespace="com.itheima.mybatis.mapper.UserMapper">
    <sql id="selector">
        select * from user
    </sql>

    <!-- 通过ID查询一个用户 -->
    <select id="findUserById" parameterType="Integer" resultType="User">
        select * from user where id = #{v}
    </select>

    <!-- //根据用户名称模糊查询用户列表
    #{}    select * from user where id = ?    占位符  ? ==  '五'
    ${}    select * from user where username like '%五%'  字符串拼接  

     -->
    <select id="findUserByUsername" parameterType="String" resultType="com.itheima.mybatis.pojo.User">
        select * from user where username like "%"#{haha}"%"
    </select>

    <!-- 添加用户 -->
    <insert id="insertUser" parameterType="com.itheima.mybatis.pojo.User">
        <selectKey keyProperty="id" resultType="Integer" order="AFTER">
            select LAST_INSERT_ID()
        </selectKey>
        insert into user (username,birthday,address,sex) 
        values (#{username},#{birthday},#{address},#{sex})
    </insert>

    <!-- 更新 -->
    <update id="updateUserById" parameterType="com.itheima.mybatis.pojo.User">
        update user 
        set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}
        where id = #{id}
    </update>

    <!-- 删除 -->
    <delete id="deleteUserById" parameterType="Integer">
        delete from user 
        where id = #{vvvvv}
    </delete>

    <!-- 根据用户名模糊查询 -->
    <select id="findUserByQueryVo" parameterType="QueryVo" resultType="com.itheima.mybatis.pojo.User">
        select * from user where username like "%"#{user.username}"%"
    </select>

    <!-- 
     -->
     <select id="countUser" resultType="Integer">
         select count(1) from user
     </select>


     <!--    根据性别和名字查询用户  where 可以去掉第一个前ANd   -->
     <select id="selectUserBySexAndUsername" parameterType="User" resultType="User">
         <include refid="selector"/>
         <where>
             <if test="sex != null and sex != ''">
                  and sex = #{sex} 
             </if>
             <if test="username != null and username != ''">
                  and username = #{username}
             </if>
         </where>
     </select>

     <!-- 多个ID (1,2,3)-->
     <select id="selectUserByIds" parameterType="QueryVo" resultType="User">
         <include refid="selector"/>
         <where>
             <foreach collection="list" item="id" separator="," open="id in (" close=")">
                 #{id}
             </foreach>
         </where>
     </select>
</mapper>

mybatis+spring整合

图13

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <package name="com.itheima.mybatis.pojo" />
    </typeAliases>

    <mappers>
        <package name="com.itheima.mybatis.mapper"/>
    </mappers>
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- Mybatis的工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 核心配置文件的位置 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>



    <!-- Mapper动态代理开发   扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 基本包 -->
        <property name="basePackage" value="com.itheima.mybatis.mapper"/>
    </bean>
</beans>
 db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
log4j.properties
 # Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Pojo

  User.java
package com.itheima.mybatis.pojo;
import java.util.Date;
public class User {
    private Integer id;

    private String username;

    private Date birthday;

    private String sex;

    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }
}

mapper

 UserMapper.java
 package com.itheima.mybatis.mapper;

import com.itheima.mybatis.pojo.User;
import com.itheima.mybatis.pojo.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface UserMapper {
    int countByExample(UserExample example);

    int deleteByExample(UserExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    List<User> selectByExample(UserExample example);

    User selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}
  mapper.xml
  <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itheima.mybatis.mapper.UserMapper" >
  <resultMap id="BaseResultMap" type="com.itheima.mybatis.pojo.User" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="username" property="username" jdbcType="VARCHAR" />
    <result column="birthday" property="birthday" jdbcType="DATE" />
    <result column="sex" property="sex" jdbcType="CHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    id, username, birthday, sex, address
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.itheima.mybatis.pojo.UserExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.itheima.mybatis.pojo.UserExample" >
    delete from user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.itheima.mybatis.pojo.User" >
    insert into user (id, username, birthday, 
      sex, address)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE}, 
      #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.itheima.mybatis.pojo.User" >
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="username != null" >
        username,
      </if>
      <if test="birthday != null" >
        birthday,
      </if>
      <if test="sex != null" >
        sex,
      </if>
      <if test="address != null" >
        address,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null" >
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="birthday != null" >
        #{birthday,jdbcType=DATE},
      </if>
      <if test="sex != null" >
        #{sex,jdbcType=CHAR},
      </if>
      <if test="address != null" >
        #{address,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.itheima.mybatis.pojo.UserExample" resultType="java.lang.Integer" >
    select count(*) from user
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update user
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.username != null" >
        username = #{record.username,jdbcType=VARCHAR},
      </if>
      <if test="record.birthday != null" >
        birthday = #{record.birthday,jdbcType=DATE},
      </if>
      <if test="record.sex != null" >
        sex = #{record.sex,jdbcType=CHAR},
      </if>
      <if test="record.address != null" >
        address = #{record.address,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update user
    set id = #{record.id,jdbcType=INTEGER},
      username = #{record.username,jdbcType=VARCHAR},
      birthday = #{record.birthday,jdbcType=DATE},
      sex = #{record.sex,jdbcType=CHAR},
      address = #{record.address,jdbcType=VARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.itheima.mybatis.pojo.User" >
    update user
    <set >
      <if test="username != null" >
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="birthday != null" >
        birthday = #{birthday,jdbcType=DATE},
      </if>
      <if test="sex != null" >
        sex = #{sex,jdbcType=CHAR},
      </if>
      <if test="address != null" >
        address = #{address,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.itheima.mybatis.pojo.User" >
    update user
    set username = #{username,jdbcType=VARCHAR},
      birthday = #{birthday,jdbcType=DATE},
      sex = #{sex,jdbcType=CHAR},
      address = #{address,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

Test

  package com.itheima.mybatis.junit;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itheima.mybatis.mapper.UserMapper;
import com.itheima.mybatis.pojo.User;
import com.itheima.mybatis.pojo.UserExample;

public class JunitTest {
    @Test
    public void testMapper() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper = ac.getBean(UserMapper.class);
        UserExample example = new UserExample();
        String username = "明";
        example.createCriteria().andSexEqualTo("1").andUsernameLike("%" + username + "%");

        example.setOrderByClause("id desc");

        int countByExample = userMapper.countByExample(example);
        System.out.println(countByExample);

        User user = userMapper.selectByPrimaryKey(10);
        System.out.println(user);


        List<User> users = userMapper.selectByExample(example);
        for (User user2 : users) {
            System.out.println(user2.getId());
        }
    }
}

springmvc/SSM整合Demo

springmvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

        <!-- 扫描@Controler  @Service   -->
        <context:component-scan base-package="com.itheima"/>

        <!-- 处理器映射器 -->
<!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
        <!-- 处理器适配器 -->
<!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
        <!-- 注解驱动 -->
        <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>

        <!-- 配置Conveter转换器  转换工厂 (日期、去掉前后空格)。。 -->
        <bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <!-- 配置 多个转换器-->
            <property name="converters">
                <list>
                    <bean class="com.itheima.springmvc.conversion.DateConveter"/>
                </list>
            </property>
        </bean>

        <!-- 上传图片配置实现类 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 上传图片的大小   B   5M  1*1024*1024*5-->
            <property name="maxUploadSize" value="5000000"/>
        </bean>

        <!-- Springmvc的异常处理器 -->
<!--         <bean class="com.itheima.springmvc.exception.CustomExceptionResolver"/> -->

        <!-- SPringmvc的拦截器 -->
        <mvc:interceptors>
            <!-- 多个拦截器 -->
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <!-- 自定义的拦截器类 -->
                <bean class="com.itheima.springmvc.interceptor.Interceptor1"/>
            </mvc:interceptor>
    <!--         <mvc:interceptor>
                <mvc:mapping path="/**"/>
                自定义的拦截器类
                <bean class="com.itheima.springmvc.interceptor.Interceptor2"/>
            </mvc:interceptor> -->
        </mvc:interceptors>

        <!-- 视图解释器 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>

   </beans>

applicationContext.xml

  <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- Mybatis的工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 核心配置文件的位置 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>

    <!-- Mapper动态代理开发   扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 基本包 -->
        <property name="basePackage" value="com.itheima.springmvc.dao"/>
    </bean>

    <!-- 注解事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

sqlMapConfig.xml

    <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 设置别名 -->
    <typeAliases>
        <!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
        <package name="com.itheima.springmvc.pojo" />
    </typeAliases>
</configuration>

SSM 整合代码下载

一个小demo 对SSM整合

图14

github代码下载: https://github.com/zy20081/JAVA/tree/master/springmvc-mybatis02


转载请注明: Zhou•Yong SSM 复习总结

上一篇
Git下载某个文件夹 Git下载某个文件夹
方法一需要工具:TortoiseSVN 操作举例: 例如,你只需要“NLPIR SDK”中“classify”文件夹下的代码,先打开 classify,其 URL 为: “https://github.com/NLPIR-team/NL
2019-01-28
下一篇
上传与下载 上传与下载
上传与下载听说好多面试的时候喜欢出上传与下载的题目,这里我就写winform版本和.net版本都写一个,写核心代码,细节就不写了,仅供参考 Form //上传 private void btnUpload_Click(ob
2019-01-17
目录