SSM整合(IDEA版)

1 环境准备

1.1 软件架构

JDK 1.8
Spring 4.x
Mybatis 3.x
Maven 3.x
MySQL 5.7

1.2 创建数据库

创建数据库,数据库名ssm-demo,字符集utf-8,排序规则默认。

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
	`id` BIGINT ( 20 ) NOT NULL AUTO_INCREMENT,
	`username` VARCHAR ( 60 ) DEFAULT NULL,
	`password` VARCHAR ( 60 ) DEFAULT NULL,
	`nick_name` VARCHAR ( 60 ) DEFAULT NULL,
	`telephone` VARCHAR ( 60 ) DEFAULT NULL,
	`email` VARCHAR ( 60 ) DEFAULT NULL,
	`birthday` date DEFAULT NULL,
	`gender` CHAR ( 1 ) DEFAULT NULL,
	`status` CHAR ( 1 ) DEFAULT NULL,
	`create_time` datetime DEFAULT NULL,
	`update_time` datetime DEFAULT NULL,
	 PRIMARY KEY ( `id` ) 
);

1.3 Maven配置

修改settings.xml配置。

<!-- 设置aliyun镜像 -->
<mirrors>
    <mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>
    </mirror>
</mirrors>
        
<!-- 设置jdk1.8版本编译 -->
<profiles>
    <profile>
        <id>jdk8</id>
        <activation>
            <activeByDefault>true</activeByDefault>
            <jdk>1.8</jdk>
        </activation>
        <properties>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        </properties>
    </profile>
</profiles>

1.4 创建工程

SSM整合(IDEA版)

点击next,填写相关信息。

SSM整合(IDEA版)

点击next创建项目。

SSM整合(IDEA版)

在main文件夹下创建java文件夹、resources文件夹,在src文件夹下创建test文件夹,在test文件夹下创建java文件夹。

SSM整合(IDEA版)

定义文件夹类型,main文件夹下java文件夹选择Sources Root,resources文件夹选择 Resources Root,test文件夹下java文件夹选择Tests。

SSM整合(IDEA版)

点击ok。

SSM整合(IDEA版)

1.4 配置tomcat

SSM整合(IDEA版)

选择tomcat路径。

SSM整合(IDEA版)

点击fix。

SSM整合(IDEA版)

选择war-exploded

SSM整合(IDEA版)

修改Application context。

SSM整合(IDEA版)

点击ok。

SSM整合(IDEA版)

1.5 添加Maven依赖

完整的pom.xml。

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zl</groupId>
    <artifactId>ssm-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>ssm-demo </name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>4.3.7.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- spring、springmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>

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

        <!-- pageHelper分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.0.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- jstl、servlet-api -->
        <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>

        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>ssm-demo</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

1.6 添加配置文件

1.6.1 applicationContext.xml

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

	<!-- 配置包扫描 -->
	<context:component-scan base-package="com.zl" />

	<!-- 引入配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>

	<!-- 配置数据源 -->
	<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClass}"/>
		<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
		<property name="user" value="${jdbc.user}"/>
		<property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- Spring整合Mybatis -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定Mybatis核心配置文件 -->
		<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
		<!-- 配置数据源 -->
		<property name="dataSource" ref="myDataSource"/>
        <!-- 指定Mapper文件的位置 -->
		<property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- Mapper代理形式开发dao,扫描包形式配置mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zl.dao"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="myDataSource"/>
    </bean>

	<!-- 通知 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
			<!-- 传播行为 -->
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="create*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="query*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

	<!-- 切面 -->
	<aop:config>
		<!-- 切入点表达式 -->
		<aop:pointcut expression="execution(* com.zl.service..*(..))" id="txPoint"/>
		<!-- 配置事务增强 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
	</aop:config>

</beans>

1.6.2 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: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.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 配置Controller包扫描 -->
    <context:component-scan base-package="com.zl.controller"/>

    <!-- 配置注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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

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

	<typeAliases>
		<!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) -->
		<package name="com.zl.domain" />
	</typeAliases>
	
	<plugins>
		<!-- pageHelper分页插件配置 -->
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
			<!-- 分页参数合理化 -->
			<property name="reasonable" value="true"/>
		</plugin>
	</plugins>

</configuration>

1.6.4 jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm-demo
jdbc.user=root
jdbc.password=1234

1.6.5 log4j.properties

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

1.6.6 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- Spring上下文的位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- SpringMVC前端控制器 -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- 此处不配置 默认找 /WEB-INF/[servlet-name]-servlet.xml -->
            <param-value>classpath:springMvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 字符编码过滤器,一定要放在所有过滤器之前 -->
    <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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

1.7 编写代码

1.7.1 domain代码

@Data
public class User implements Serializable {

    private static final long serialVersionUID = -7761320977621867375L;

    private Long id;
    private String username;
    private String password;
    private String nickName;
    private String telephone;
    private String email;
    private Date birthday;
    private String gender;
    private String status;
    private Date createTime;
    private Date updateTime;

}

1.7.2 dao代码

public interface UserDao {

    List<User> queryUsersList(User user);

    int queryUsersCount(User user);

    User queryUserById(Long id);

    List<User> queryUsers();

    List<User> queryUsersByIds(Long[] ids);

    void insertUser(User user);

    void updateUser(User user);

    void deleteUserById(Long id);

    void deleteUsersByIds(Long[] ids);

}

1.7.3 mapper文件

<?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.zl.dao.UserDao">

    <!-- 声明sql片段 -->
    <sql id="userColumns">
        id
        , username, password, nick_name, telephone, email, birthday, gender, status, create_time, update_time
    </sql>

    <!-- resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询 -->
    <resultMap id="userResult" type="User">
        <id property="id" column="id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <result property="nickName" column="nick_name"/>
        <result property="telephone" column="telephone"/>
        <result property="email" column="email"/>
        <result property="birthday" column="birthday"/>
        <result property="gender" column="gender"/>
        <result property="status" column="status"/>
        <result property="createTime" column="create_time"/>
        <result property="updateTime" column="update_time"/>
        <!-- association :配置一对一的关系 -->
        <!-- collection :配置一对多的关系 -->
    </resultMap>

    <!-- 分页查询 -->
    <!-- 注意这里的 resultType 返回值类型是集合内存储数据的类型,不是 'list' -->
    <select id="queryUsersList" parameterType="User"
            resultMap="userResult">
        select
        <include refid="userColumns"/>
        from t_user
        <where>
            <if test="username != null and username != ''">
                and username like concat('%', #{username}, '%')
            </if>
            <if test="nickName != null and nickName != ''">
                and nick_name like concat('%', #{nickName}, '%')
            </if>
            <if test="telephone != null and telephone != ''">
                and telephone like concat('%', #{telephone}, '%')
            </if>
        </where>
    </select>

    <!-- 查询条数 -->
    <select id="queryUsersCount" parameterType="User"
            resultType="Integer">
        select count(1) from t_user
        <where>
            <if test="username != null and username != ''">
                and username like concat('%', #{username}, '%')
            </if>
            <if test="nickName != null and nickName != ''">
                and nick_name like concat('%', #{nickName}, '%')
            </if>
            <if test="telephone != null and telephone != ''">
                and telephone like concat('%', #{telephone}, '%')
            </if>
        </where>
    </select>

    <!-- 查询全部 -->
    <select id="queryUsers" parameterType="String" resultMap="userResult">
        select
        <include refid="userColumns"/>
        from t_user
    </select>

    <!-- 精确查询 -->
    <select id="queryUserById" parameterType="Long" resultMap="userResult">
        select
        <include refid="userColumns"/>
        from
        t_user where id = #{id}
    </select>

    <!-- 批量查询 -->
    <select id="queryUsersByIds" parameterType="Long" resultMap="userResult">
        select
        <include refid="userColumns"/>
        from
        t_user
        <where>
            <foreach collection="array" item="id" open="id in (" close=")"
                     separator=",">
                #{id}
            </foreach>
        </where>
    </select>

    <!-- 添加 -->
    <insert id="insertUser" parameterType="User">
        <!-- mysql自增主键返回,数据库表主键设置为自动递增 -->
        <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="Long">
            select last_insert_id()
        </selectKey>
        insert into t_user
        (username, password, nick_name, telephone, email, birthday, gender, status, create_time, update_time)
        values (#{username}, #{password}, #{nickName}, #{email}, #{telephone}, #{birthday}, #{gender},
        #{status}, #{createTime},
        #{updateTime})
    </insert>

    <!-- 更新 -->
    <update id="updateUser" parameterType="User">
        update t_user
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <if test="nickName != null and nickName != ''">
                nick_name = #{nickName},
            </if>
            <if test="telephone != null and telephone != ''">
                telephone = #{telephone},
            </if>
            <if test="email != null and email != ''">
                email = #{email},
            </if>
            <if test="birthday != null">
                birthday = #{birthday},
            </if>
            <if test="gender != null and gender != ''">
                gender = #{gender},
            </if>
            <if test="status != null and status != ''">
                status = #{status},
            </if>
            <if test="createTime != null">
                create_time = #{createTime},
            </if>
            <if test="updateTime != null">
                update_time = #{updateTime},
            </if>
        </set>
        where id = #{id}
    </update>

    <!-- 删除 -->
    <delete id="deleteUserById" parameterType="Long">
        delete
        from t_user
        where id = #{id}
    </delete>

    <!-- 批量删除 -->
    <delete id="deleteUsersByIds" parameterType="Long">
        delete from t_user
        <where>
            <!-- foreach标签,进行遍历 -->
            <!-- collection:遍历的集合-->
            <!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 -->
            <!-- open:在前面添加的sql片段 -->
            <!-- close:在结尾处添加的sql片段 -->
            <!-- separator:指定遍历的元素之间使用的分隔符 -->
            <foreach collection="array" item="id" open="id in (" close=")"
                     separator=",">
                #{id}
            </foreach>
        </where>
    </delete>

    <!-- 根据用户名密码查询用户 -->
    <select id="queryUserByUsernameAndPassword" parameterType="User" resultMap="userResult">
        select
        <include refid="userColumns"/>
        from
        t_user
        <where>
            <if test="username != null and username != ''">
                and username = #{username}
            </if>
            <if test="password != null and password != ''">
                and password = #{password}
            </if>
        </where>
    </select>
</mapper>

1.7.4 service代码

public interface UserService {

    List<User> queryUsersList(User user);

    int queryUsersCount(User user);

    User queryUserById(Long id);

    List<User> queryUsers();

    List<User> queryUsersByIds(Long[] ids);

    void insertUser(User user);

    void updateUser(User user);

    void deleteUserById(Long id);

    void deleteUsersByIds(Long[] ids);

}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> queryUsersList(User user) {
        return userDao.queryUsersList(user);
    }

    @Override
    public int queryUsersCount(User user) {
        return userDao.queryUsersCount(user);
    }

    @Override
    public User queryUserById(Long id) {
        return userDao.queryUserById(id);
    }

    @Override
    public List<User> queryUsers() {
        return userDao.queryUsers();
    }

    @Override
    public List<User> queryUsersByIds(Long[] ids) {
        return userDao.queryUsersByIds(ids);
    }

    @Override
    public void insertUser(User user) {
        userDao.insertUser(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public void deleteUserById(Long id) {
        userDao.deleteUserById(id);
    }

    @Override
    public void deleteUsersByIds(Long[] ids) {
        userDao.deleteUsersByIds(ids);
    }

    @Override
    public User queryUserByUsernameAndPassword(User user) {
        return userDao.queryUserByUsernameAndPassword(user);
    }
}

1.7.5 controller代码

1.8 测试

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class UserTest {

    @Autowired
    private UserDao userDao;

    @Test
    public void insert() {
        for (int i = 0; i < 20; i++) {
            User user = new User();
            user.setUsername("user" + i);
            user.setPassword("123456");
            user.setNickName("用户" + i);
            user.setCreateTime(new Date());
            userDao.insertUser(user);
        }
    }

    @Test
    public void update() {
        User user = userDao.queryUserById(2L);
        user.setUsername("hahaha");
        user.setUpdateTime(new Date());
        userDao.updateUser(user);
    }

    @Test
    public void deleteById() {
        userDao.deleteUserById(2L);
    }

    @Test
    public void deleteByIds() {
        userDao.deleteUsersByIds(new Long[]{3L, 4L});
    }

    @Test
    public void query() {
        // pageHelper分页的一种
        PageHelper.startPage(1, 10);
        PageHelper.orderBy("create_time desc");
        List<User> list = userDao.queryUsersList(new User());
        int count = userDao.queryUsersCount(new User());
        System.out.println(list);
        System.out.println(count);
    }
}
上一篇:什么是IOC容器?为什么需要IOC容器?


下一篇:Spring AOP介绍和JDK的动态代理