MyBatis和Spring整合
Categories: MyBatis
MyBatis和Spring整合的完整案例
文章目录[隐藏]
1.导入jar包
<dependencies>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!--日志包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<!--spring数据库-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<!--spring-mybatis整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--spring MVC相关包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
<!--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>
<!-- json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<!-- 文件上传所依赖的jar包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<!--配置资源文件扫描,否则Mapper-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
2.配置文件
创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库?characterEncoding=utf-8
jdbc.username=用户名
jdbc.password=密码
创建spring-config.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<!--读取配置文件-->
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--spring管理session工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/ssm/club/dao/mapper/*.xml"/>
<!--扫描实体类包,mapper中不用写全路径-->
<property name="typeAliasesPackage" value="com.ssm.club.pojo"/>
</bean>
<!--批量扫描生成bean(Service)-->
<context:component-scan base-package="com.ssm.club.service">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<!--扫描dao所在包,生成代理实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.club.dao"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--如何进行事务增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" rollback-for="Exception"/>
<tx:method name="update*" rollback-for="Exception"/>
<tx:method name="delete*" rollback-for="Exception"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<!--定义需要增强的方法-->
<aop:pointcut id="adviceMethod" expression="execution(* com.ssm.club.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="adviceMethod"/>
</aop:config>
</beans>
创建springMVC-servlet.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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.ssm.club.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
配置web.xml文件
<?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">
<!--加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--加载springMVC配置文件-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--跟随tomcat启动同时加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.html</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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>/list.html</welcome-file>
</welcome-file-list>
</web-app>
3.创建实体类
public class ClubUser {
private Integer id;
private String name;
private Integer sex;
private Integer age;
private String address;
private String email;
}
public class ClubUserCriteria extends ClubUser {
private Integer maxAge;
private Integer minAge;
private Integer offset;
private Integer pageSize;
}
public class PageInfo<T> {
private Integer totalCount;
private Integer totalPage;
private Integer pageNum;
private Integer pageSize;
private List<T> result;
}
4.创建dao
注:接口由spring管理,所以不用实现类
dao里的方法名与mapper中的语句对应
public interface ClubUserDAO {
List<ClubUser> getUserList(ClubUserCriteria user);
ClubUser getUserById(Integer id);
void updateUser(ClubUser user);
int getUserCount(ClubUserCriteria user);
}
5.Mapper文件
mapper文件的namespace对应dao
<?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.ssm.club.dao.ClubUserDAO">
<resultMap id="userMap" type="ClubUser">
<id property="id" column="ID"/>
<result property="address" column="ADDRESS"/>
<result property="name" column="NAME"/>
<result property="sex" column="SEX"/>
<result property="age" column="AGE"/>
<result property="email" column="EMAIL"/>
</resultMap>
<sql id="select-user">
select ID,NAME,SEX,AGE,ADDRESS,EMAIL
from CLUB_USER
</sql>
<sql id="where-user">
<where>
<if test="name !=null and name!=''">and NAME LIKE concat('%',#{name},'%')</if>
<if test="address !=null and address!=''">and address LIKE concat('%',#{address},'%')</if>
<if test="email !=null and email!=''">and EMAIL=#{email}</if>
<if test="sex!=null">and sex=#{sex}</if>
<if test="maxAge !=null">and age <=#{maxAge}</if>
<if test="minAge !=null">and age >=#{minAge}</if>
</where>
</sql>
<select id="getUserList" parameterType="ClubUserCriteria" resultMap="userMap">
<include refid="select-user"/>
<include refid="where-user"/>
limit #{offset},#{pageSize}
</select>
<select id="getUserCount" parameterType="ClubUserCriteria" resultType="int">
select count(id) from CLUB_USER
<include refid="where-user"/>
</select>
<select id="getUserById" parameterType="int" resultMap="userMap">
<include refid="select-user"/>
where id=#{id}
</select>
<update id="updateUser" parameterType="ClubUser">
update CLUB_USER
<set>
<if test="name !=null and name!=''">NAME =#{name},</if>
<if test="address !=null and address!=''">address =#{address},</if>
<if test="email !=null and email!=''">EMAIL=#{email},</if>
<if test="sex!=null">sex=#{sex},</if>
<if test="age!=null">age=#{age},</if>
</set>
where ID=#{id}
</update>
</mapper>
5.service
public interface ClubUserService {
PageInfo<ClubUser> getUserList(ClubUserCriteria user,int pageNum,int pageSize);
ClubUser getUserById(Integer id);
void updateUser(ClubUser user);
}
@Service
public class ClubUserServiceImpl implements ClubUserService {
@Autowired
private ClubUserDAO clubUserDAO;
@Override
public ClubUser getUserById(Integer id) {
return clubUserDAO.getUserById(id);
}
@Override
public void updateUser(ClubUser user) {
clubUserDAO.updateUser(user);
}
@Override
public PageInfo<ClubUser> getUserList(ClubUserCriteria user, int pageNum, int pageSize) {
Integer count = clubUserDAO.getUserCount(user);
PageInfo<ClubUser> pageInfo = new PageInfo<>();
pageInfo.setTotalCount(count);
pageInfo.setPageSize(pageSize);
pageInfo.setPageNum(pageNum);
if (count > 0) {
user.setPageSize(pageSize);
user.setOffset((pageNum - 1) * pageSize);
List<ClubUser> users = clubUserDAO.getUserList(user);
pageInfo.setResult(users);
}
return pageInfo;
}
}
6.controller
@Controller
public class UserController {
@Autowired
private ClubUserService clubUserService;
@RequestMapping("/list.html")
public String list(ClubUserCriteria clubUserCriteria, @RequestParam(defaultValue = "1") Integer pn, Model model) {
if (pn < 1) {
pn = 1;
}
PageInfo<ClubUser> users = clubUserService.getUserList(clubUserCriteria, pn, 3);
model.addAttribute("pageInfo", users);
return "list";
}
@RequestMapping("/go_update.html")
public ModelAndView goUpdate(Integer id) {
ClubUser clubUser = clubUserService.getUserById(id);
return new ModelAndView("update", "clubUser", clubUser);
}
@RequestMapping("/update.html")
public String update(ClubUser user, HttpServletRequest request) {
try {
clubUserService.updateUser(user);
request.setAttribute("message", "修改成功");
return "forward:/list.html";
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "修改失败");
return "update";
}
}
}