纵有千古,横有八荒;前途似海,来日方长。——梁启超
Spring+SpringMVC+MyBatis
ssm整合是结合spring的IoC,AOP,和springmvc的分层结构,加上mybatis的持久层数据录入。在老师讲解之后,自己试着编写运行,在这里保存一份
相关配置
pom文件:
<packaging>war</packaging>
<properties>
<!--统一管理spring所有的版本-->
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--spring的单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--serlvet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<!--不过滤java下的xml文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8888</port>
</configuration>
</plugin>
</plugins>
</build>
- web-xml将请求拦截到spring-mvc.xml配置文件中
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--配置Springmvc-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--spring写好的中文过滤器-->
<filter>
<filter-name>encode</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>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.spring-mvc.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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--设置ssm的整合注解配置-->
<!--<context:annotation-config/>-->
<!--设置包扫描,分别扫描controller和service包-->
<context:component-scan base-package="com.qfedu.controller"/>
<context:component-scan base-package="com.qfedu.service"/>
<!--注解驱动-->
<mvc:annotation-driven/>
<!--配置默认资源可以被访问-->
<mvc:default-servlet-handler/>
<!--引入spring和mybatis的整合文件-->
<import resource="classpath:spring-mybatis.xml"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.spring-mybatis.xml
在mvc配置文件中引入spring和mybatis整合的配置文件,该文件作为spring配置文件和mybatis配置文件的一个连接点,引入了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"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 引入数据库配置信息文件 -->
<context:property-placeholder location="classpath:db.properties" />
<context:component-scan base-package="com.qfedu.service" />
<!-- 配置druid数据源 -->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<!--<property name="url" value="jdbc:mysql://localhost:3306/integssm"></property>-->
<!--<property name="driverClassName" value="com.mysql.jdbc.Driver" />-->
<!--<property name="username" value="root" />-->
<!--<property name="password" value="123456" />-->
<property name="url" value="${url}"></property>
<property name="driverClassName" value="${driver}" />
<property name="username" value="${aaaa}" />
<property name="password" value="${bbbb}" />
</bean>
<bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.qfedu.pojo" />
<property name="mapperLocations" value="classpath:com/qfedu/dao/mapper/*Mapper.xml" />
<property name="dataSource" ref="ds"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qfedu.dao" />
<property name="sqlSessionFactoryBeanName" value="sf" />
</bean>
<!-- 配置事务管理器 -->
<bean id="dtx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<tx:advice id="tx" transaction-manager="dtx">
<!-- 声明属性,声明事务的规则 -->
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- 定义切面 -->
<aop:config>
<aop:pointcut id="mpt" expression="execution(* com.qfedu.service.*.*(..))" />
<aop:advisor advice-ref="tx" pointcut-ref="mpt" />
</aop:config>
</beans>
4.mybatis-config.xml
引入日志文件的配置,这里使用log4j日志框架
<?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="logImpl" value="LOG4J" />
</settings>
</configuration>
5.log4j.properties
# Global logging configuration
log4j.rootLogger=error, stdout, F
# MyBatis logging configuration...
log4j.logger.com.qfedu.dao=trace
# 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
log4j.appender.F = org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.File =myproj.log
log4j.appender.F.Append = true
log4j.appender.F.Threshold = DEBUG
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
6.最后添加db.properties文件
在spring-mybatis.xml文件中引入,密码已省略
url=jdbc:mysql://localhost:3306/integssm?characterEncoding=utf-8
driver=com.mysql.jdbc.Driver
aaaa=root
bbbb=******
maxActive=50
minIdle=1
至此,ssm整合的一个简单的配置文件体系就配置完成
功能实现代码
1.users类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Users {
private int uid;
private String username;
private String password;
private int age;
private String addr;
}
2.IUserDao.class
public interface IUserDao {
List<Users> getAllUsers();
Users getUserByUid(int uid);
void updateUser(Users u);
void deleteUserByUid(int uid);
}
3.usermapper.xml
为了便于管理,将它放在了dao层下的子目录中,文件中存放对应表的sql语句
<?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属性 -->
<mapper namespace="com.qfedu.dao.IUserDao">
<sql id="all">
select * from users
</sql>
<select id="getAllUsers" resultType="users">
<include refid="all" />
</select>
<select id="getUserByUid" resultType="users">
<include refid="all" />
where uid = #{uid}
</select>
<update id="updateUser">
update users set username=#{username}, password=#{password}, age=#{age}, addr =#{addr} where uid = #{uid}
</update>
<delete id="deleteUserByUid">
delete from users where uid = #{uid}
</delete>
</mapper>
4.IUserService.class
public interface IUserService {
List<Users> getAllUsers();
Users getUsersByUid(int uid);
void updateUsers(Users u);
void deleteUsersByUid(int uid);
}
5.UserServiceImpl.class
```java
package com.qfedu.service.impl;
import java.util.List;
import javax.annotation.Resource;
import com.qfedu.dao.IUserDao;
import com.qfedu.pojo.Users;
import com.qfedu.service.IUserService;
import org.springframework.stereotype.Service;
/**
* 注意Service的实现类之上一定要添加service注解
*/
@Service
public class UserServiceImpl implements IUserService {
/**
* 动态注入dao组件
*/
@Resource
private IUserDao UsersDao;
@Override
public List<Users> getAllUsers() {
return UsersDao.getAllUsers();
}
@Override
public Users getUsersByUid(int uid) {
return UsersDao.getUserByUid(uid);
}
@Override
public void updateUsers(Users u) {
UsersDao.updateUser(u);
}
@Override
public void deleteUsersByUid(int uid) {
UsersDao.deleteUserByUid(uid);
}
}
6.Env.class
设置一个工具类用来加载db.properties文件
package com.qfedu.util;
import java.io.IOException;
import java.util.Properties;
public class Env extends Properties {
private static Env instance;
private Env(){
try {
load(getClass().getResourceAsStream("/db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Env getInstance(){
if(instance == null){
instance = new Env();
}
return instance;
}
}
7.最后在测试类中进行测试
spring的单元测试有时间在写
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-mybatis.xml")
public class TestUserService {
@Resource
private IUserService userService;
@Test
public void testGetAllUsers(){
List<Users> list = userService.getAllUsers();
for (Users u : list) {
System.out.println(u);
}
}
}
完啦