SSM 整合

SpringMVC、Spring、Mybatis整合

maven项目打war包并引入依赖,并添加静态资源:


依赖及静态资源

<dependencies>
    <!-- 单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.6.RELEASE</version>
    </dependency>

    <!-- Mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.8</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.2</version>
    </dependency>
    <!-- MySql -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.32</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.6.4</version>
    </dependency>

    <!-- Jackson Json处理工具包 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.0</version>
    </dependency>

    <!-- 连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.9</version>
    </dependency>
    <!-- JSP相关 -->
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

css文件及页面资源:

/*表格样式*/
table.altrowstable {
    font-family: verdana, arial, sans-serif;
    font-size: 11px;
    color: #333333;
    border-width: 1px;
    border-color: #a9c6c9;
    border-collapse: collapse;
}

table.altrowstable th {
    border-width: 1px;
    padding: 30px;
    border-style: solid;
    border-color: #a9c6c9;
}

table.altrowstable td {
    border-width: 1px;
    padding: 10px;
    border-style: solid;
    border-color: #a9c6c9;
    text-align: center;
}

在WEB-INF下创建views文件夹,并创建users.jsp文件:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>Title</title>
    <link  rel="stylesheet" href="/css/user.css"/>
</head>
<body>
<!-- Table goes in the document BODY -->
<table class="altrowstable" id="alternatecolor">
    <tr>
        <th>用户编号</th>
        <th>用户名</th>
        <th>真实姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>出生日期</th>
        <th>创建日期</th>
        <th>更新日期</th>
        <th>删除操作</th>
    </tr>
    <c:forEach var="user" items="${userList}">
        <tr>
            <td>${user.id}</td>
            <td>${user.userName}</td>
            <td>${user.name}</td>
            <td>${user.age}</td>
            <td>${user.sex==1?"男":"女"}</td>
            <td><f:formatDate value="${user.birthday}" pattern="yyyy-MM-dd"></f:formatDate></td>
            <td><f:formatDate value="${user.created}" pattern="yyyy-MM-dd"></f:formatDate></td>
            <td> <f:formatDate value="${user.updated}" pattern="yyyy-MM-dd"></f:formatDate> </td>
            <td><a href="/user/deleteUserById?id=100">删除</a></td>
        </tr>
    </c:forEach>

</table>
</body>
</html>

创建数据库及实体类:


数据库及实体类

创建如图所示数据库并插入测试数据:

数据库

按照数据库创建实体类:

public class User {

    private Long id;

    // 用户名
    private String userName;

    // 密码
    private String password;

    // 姓名
    private String name;

    // 年龄
    private Integer age;

    // 性别,1男性,2女性
    private Integer sex;

    // 出生日期
    private Date birthday;

    // 创建时间
    private Date created;

    // 更新时间
    private Date updated;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                ", birthday=" + birthday +
                ", created=" + created +
                ", updated=" + updated +
                '}';
    }

    public Long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    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 Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

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

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }
}

创建mapper接口即mybatis相关配置文件:


Mybatis相关

UserMapper接口:

public interface UserMapper {
    public User findUserById(Long id);
}

创建mybatis-config.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>

    <!-- 加载外部的jdbc.properties -->
    <properties resource="jdbc.properties"></properties>
    <typeAliases>
        <!-- 配置pojo的别名映射 -->
        <package name="com.bilibili.pojo"></package>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClass}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
     <mappers>
        <mapper resource="mappers/UserMapper.xml"></mapper>
    </mappers>
</configuration>

添加log4j.properties和jdbc.properties配置:

log4j.properties:

### direct log messages to stdout ###
### 配置输出源的   log4j.appender.输出源名=输出源的实现类
### 属性的配置  log4j.appender.输出源名.属性名=属性值
log4j.appender.a=org.apache.log4j.ConsoleAppender
log4j.appender.a.Target=System.out
log4j.appender.a.layout=org.apache.log4j.PatternLayout
log4j.appender.a.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n


### set log levels - for more verbose logging change 'info' to 'debug' ###
### log4j.rootLogger=输出级别,输出源1,输出源2....
log4j.rootLogger=debug, a

jdbc.properties:

jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.username = root
jdbc.password = 1234

创建接口映射userMapper.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.bilibili.mapper.UserMapper">
    <!-- statement的id就是方法的名字 -->
    <select id="findUserById" resultType="User">
        select * from tb_user where id = #{id}
    </select>
</mapper>

此时文件结构如下:

文件结构

创建Mapper测试类测试mybatis:


Mybatis测试类

public class UserMapperTest {

    private UserMapper userMapper;
    @Before
    public void setUp() throws Exception {
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void findUserById() {
        User user = userMapper.findUserById(1L);
        System.out.println(user);
    }
}

Spring与Mybatis整合

添加mybatis-spring依赖:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.3</version>
</dependency>

Mybatis和spring的整合包提供了一个SqlSessionFactoryBean,该对象是一个工厂bean,实现了FactoryBean,可以通过其getObject方法来返回一个SqlSessionFactory。(实现FactoryBean接口之后,获取该bean时会使用其getObject方法)

创建spring主配置文件applicationContext.xml,并修改mybatis主配置文件:

通过配置SqlSessionFactoryBean的bean来将SqlSessionFactory交给spring来管理。(需要注入 数据源dataSource、mybatis核心文件位置configLocation、别名映射typeAliasesPackage、mapper文件mapperLocations


spring与mybatis主配置文件

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"
       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">


    <!-- 加载外部配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- bean definitions here -->


    <!-- 装配sqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 将mybatis中的别名映射配置 转移 到spring中来-->
        <property name="typeAliasesPackage" value="com.bilibili.pojo"></property>
        <!-- 将mybatis中的映射文件的配置 转移 到spring中来-->
        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

修改mybatis-config.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>
    <settings>
        <!-- 只剩下驼峰映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

创建测试类进行测试:

public class UserMapperTest2 {

    private UserMapper userMapper;

    @Before
    public void setUp(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) ac.getBean("sqlSessionFactory");
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void findUserById() {
        userMapper.findUserById(1l);
    }
}

此时已将SqlSessionFactory交给Spring来管理,但仍然可以继续整合。


将Mapper接口对象也交给Spring管理:

在Spring配置中MapperFactoryBean


配置单个Mapper作为bean

<?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"
       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">


    <!-- 加载外部配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- bean definitions here -->


    <!-- 装配sqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <property name="typeAliasesPackage" value="com.bilibili.pojo"></property>

        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
    </bean>


    <!-- 配置单个userMapper对象 -->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!-- 配置sqlSessionFacotroy对象 -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        <!-- 配置userMapper对象的接口 -->
        <property name="mapperInterface" value="com.bilibili.mapper.UserMapper"></property>
    </bean>


    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

此时已经将mapper接口也交个spring来管理,不过mapper一个一个配置太麻烦,可以修改为包扫描的方式:

<!-- 配置包扫描方式,创建多个mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.bilibili.mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

最终配置:


spring配置文件即mybatis配置文件最终结果

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"
       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">


    <!-- 加载外部配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- bean definitions here -->


    <!-- 装配sqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <property name="typeAliasesPackage" value="com.bilibili.pojo"></property>

        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
    </bean>


    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置包扫描方式,创建多个mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bilibili.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

</beans>

mybati-config.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>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

Spring与SpringMVC整合

创建springMVC.xml文件,并配置web.xml文件:


springMVC配置文件即web.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.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启注解驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 扫描指定包下的注解 -->
    <context:component-scan base-package="com.bilibili.controller"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 返回的视图前缀(Json的话不需要这玩意) -->
        <property name="prefix" value="WEB-INF/views/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 放行静态资源 -->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>

配置web.xml,配置乱码过滤器,springMVC的前端控制器,spring的监听器:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
           version="3.0">


    <!-- 乱码过滤器 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- 前端控制器 -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- 配置springMVC核心配置文件的位置 -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!-- 拦截的路径 -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    
    <!-- spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <!-- spring核心配置文件 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>

创建一个测试Controller:


测试Controller

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("findAllUsers")
    public String findAllUsers(Model model){
        //1.调用service查询所有数据
        List<User> userList = userService.findAllUsers();
        //2.将数据转发到jsp页面去
        model.addAttribute("userList",userList);
        return "users";
    }
}

创建UserService接口并创建其实现类:


UserServiceImpl

@Service //注册当前是一个service层的bean到spring容器
public class UserServiceImpl implements UserService {

    @Autowired //自动根据类型注入
    private UserMapper userMapper;

    public List<User> findAllUsers() {
        //调用dao层查询所有用户信息
        return userMapper.findAllUsers();
    }
}

编写接口及其mapper.xml


mapper接口及其映射xml

接口中添加方法:

public List<User> findAllUsers();

xml中添加SQL语句

<select id="findAllUsers" resultType="User">
    select * from tb_user
</select>

在spring中开启service层注解扫描:

<!-- 注解扫描service -->
<context:component-scan base-package="com.bilibili.service"></context:component-scan>

Service整合事务

在controller中调用添加用户方法:


web层

@RequestMapping("addUsers")
public String addUsers(){
    //调用service新增2个用户信息
    userService.addUsers();
    //重定向到查询用户页面去
    return "redirect:findAllUsers";
}

Service层添加两个用户:


Service层

public void addUsers() {
    User user = new User();
    user.setUserName("zzzxxx");
    user.setPassword("zzzxxx");
    User user2 = new User();
    user2.setUserName("zzzxxx2");
    user2.setPassword("zzzxxx2");

    userMapper.addUser(user);
    //测试事务用的错误
    //int i = 1/0;
    userMapper.addUser(user2);
}

持久层添加方法:


dao层

public void addUser(User user);
<insert id="addUser">
    insert into tb_user(user_name,password) values(#{userName},#{password})
</insert>

spring中盘配置事务管理器、事务策略、事务AOP:


事务相关

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


    <!-- 注解扫描service -->
    <context:component-scan base-package="com.bilibili.service"></context:component-scan>

    <!-- 加载外部配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- bean definitions here -->


    <!-- 装配sqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <property name="typeAliasesPackage" value="com.bilibili.pojo"></property>

        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
    </bean>


    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置包扫描方式,创建多个mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bilibili.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>


    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务策略 -->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置aop -->
    <aop:config>
        <aop:pointcut id="transaction" expression="execution(* com.bilibili.service.impl.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="transaction" ></aop:advisor>
    </aop:config>
</beans>

注解方式配置事务:
spring配置中开启事务注解:

<!-- 开启注解事务 -->
<tx:annotation-driven></tx:annotation-driven>

然后在实现类上添加@Transaction即可:

@Transactional//当前实现类的所有方法添加事务
@Service
public class UserServiceImpl implements UserService {}

配置文件优化

将applicationContext.xml拆分成三个文件:

1. applicationContext-tx.xml:事务相关的。
2. applicationContext-mybatis:mybatis相关的。
3. applicationContext.xml:注解扫描和数据源相关的

Spring配置文件拆分:


配置文件拆分

事务相关的 applicationContext-tx.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: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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- bean definitions here -->

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--  &lt;!&ndash; 配置事务策略 &ndash;&gt;
      <tx:advice id="txAdvice">
          <tx:attributes>
              <tx:method name="*"/>
          </tx:attributes>
      </tx:advice>

      &lt;!&ndash; 配置aop &ndash;&gt;
      <aop:config>
          <aop:pointcut id="transaction" expression="execution(* com.bilibili.service.impl.*.*(..))"></aop:pointcut>
          <aop:advisor advice-ref="txAdvice" pointcut-ref="transaction" ></aop:advisor>
      </aop:config>-->

    <!-- 开启注解事务 -->
    <tx:annotation-driven></tx:annotation-driven>
</beans>

mybatis相关的 applicationContext-mybatis.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"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- bean definitions here -->

    <!-- 装配sqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

        <property name="typeAliasesPackage" value="com.bilibili.pojo"></property>

        <property name="mapperLocations" value="classpath:mappers/*.xml"></property>
    </bean>

    <!-- 配置包扫描方式,创建多个mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bilibili.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>

注解扫描和数据源相关的 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"
       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">


    <!-- 注解扫描service -->
    <context:component-scan base-package="com.bilibili.service"></context:component-scan>

    <!-- 加载外部配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- bean definitions here -->

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
</beans>

修改web.xml的配置,加载所有的spring的核心配置文件


修改web.xml

<!-- spring的监听器 -->
<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>

Maven高级

maven打pom包可以作为父项目来同一管理依赖版本:

<!-- 只是声明依赖的版本,不会真的引入依赖,子工程通过坐标引入依赖 -->
<dependencyManagement>
    <dependencies>
    ...
    </dependencies>
</dependencyManagement>

maven聚合和maven继承虽然概念不同,但一般同时使用。

好像没什么可说的

标签: Java, Spring, Mybatis

添加新评论