SSM之DAO部分Spring与MyBatis整合

原文地址:http://blog.csdn.net/uq_jin/article/details/51527404

前面我们已经创建了一个基于Maven的web工程,如果你还没有创建,请参考:
http://blog.csdn.net/uq_jin/article/details/51527145

整合完成图

SSM之DAO部分Spring与MyBatis整合_第1张图片

配置web.xml

SSM之DAO部分Spring与MyBatis整合_第2张图片

可以看的默认的servlet是2.3的,我们修改为Tomcat下默认的Servlet版本。可以去Tomcat目录下的webapps\examples\WEB-INF下的web.xml里拷贝头如下:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1"
         metadata-complete="true">
    <display-name>Archetype Created Web Application</display-name>
</web-app>

配置pom.xml

在pom里添加依赖相关包的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>me.jinkun</groupId>
    <artifactId>SSM</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SSM Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- 配置Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- 配置日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- 数据库 mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.37</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!-- DAO -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- Web Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.0</version>
        </dependency>

        <!-- Spring -->
        <!-- Spring Core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!--Spring Dao -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <!-- Spring Web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>

        <!-- Spring test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.1.7.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SSM</finalName>
    </build>
</project>

User.java

这里只是一个测试的实体

public class User {
    private Long userId;
    private String username;
    private String userpass;


    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserpass() {
        return userpass;
    }

    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", username='" + username + '\'' +
                ", userpass='" + userpass + '\'' +
                '}';
    }
}

UserDAO.java

这是一个DAO接口只定义了两个方法

public interface UserDao {
    public List<User> findAll();

    public void save(User user);
}

UserDAO.xml

这是和UserDao对应的mapper文件,实现UserDao对应额接口方法

<?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">
<!-- 实现UserDao接口对应的方法 -->
<mapper namespace="me.jinkun.ssm.dao.UserDao">
    <!-- 增 -->
    <insert id="save" parameterType="User">
        INSERT INTO t_user(user_id,username,userpass)
        VALUES (#{userId},#{username},#{userpass});
    </insert>

    <!-- 查 -->
    <select id="findAll" resultType="User">
      SELECT * FROM t_user;
    </select>
</mapper>

jdbc.properties

配置JDBC的连接属性,需修改为自己的数据库

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

mybatis-config.xml

配置mybatis的一些全局配置属性

<?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">
<!-- 参考官网:http://www.mybatis.org/mybatis-3/zh/configuration.html#settings -->
<configuration>
    <!-- 全局配置 -->
    <settings>
        <!-- 使用列标签代替列名 -->
        <setting name="useColumnLabel" value="true"/>
        <!--允许 JDBC 支持自动生成主键-->
        <setting name="useGeneratedKeys" value="false"/>
        <!--是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

spring-dao.xml

Spring配置与mybatis整合的配置文件

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

    <!-- 导入外部的properties文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置数据源 使用的是c3p0数据源 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="1000"/>
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 配置mybatis的sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 扫描domain下的实体,方便在mapper下的xml中使用别名,例如User则会找到me.jinkun.ssm.domain.User -->
        <property name="typeAliasesPackage" value="me.jinkun.ssm.domain"/>
        <!-- 自动扫描mapper下的Xx.xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类并注入到Spring的容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="me.jinkun.ssm.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- 自动扫描与装配dao-->
    <context:component-scan base-package="me.jinkun.ssm.dao"/>
</beans>

UserDaoTest.java

Spring junit测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/spring/*.xml"})
public class UserDaoTest {
    @Resource
    private UserDao mUserDao;

    @Test
    public void save() {
        User user = new User();
        user.setUserId(1L);
        user.setUsername("jack");
        user.setUserpass("1234");
        mUserDao.save(user);
    }

    @Test
    public void findAll() {
        List<User> userList = mUserDao.findAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

ssm.sql

主要是创建测试数据库和表的sql语句

CREATE DATABASE ssm DEFAULT CHARACTER SET utf8;
USE ssm;

CREATE TABLE t_user ( user_id BIGINT AUTO_INCREMENT, username VARCHAR(32) COMMENT '用户名', userpass VARCHAR(32) COMMENT '用户密码', PRIMARY KEY (user_id) );

查看整合结果

SSM之DAO部分Spring与MyBatis整合_第3张图片

可以看到我们成功插入了一条数据并查询出来,说明我们整合mybatis成功,下一节我们将设计Service层。

源码下载地址: https://github.com/cskun/SSM.git

你可能感兴趣的:(DAO,springMVC,mybatis)