SpringMVC整合mybatis基于纯注解配置
Mybatis整合Spring配置
第一部分:配置Spring框架
配置SpringMVC的步骤
配置流程图
导入包(哪些包,基本包5个,1日志依赖包,2webmvc支持包)SpringMVC配置
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
- 构建一个请求
<form action="${pageContext.request.contextPath }/admin/addAdmin" method="post">
管理员名称:<input name="admin_name" type="text"><input type="submit" value="增加管理员">
</form>
编辑web.xml配置核心控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
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 ">
<!-- 编码支持过滤器 -->
<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>
<param-name>contextConfigLocation</param-name>
<param-value>cn.gzsxt.config</param-value>
</init-param>
<!-- 修改支持配置类的Spring容器 -->
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</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>
</web-app>
编写业务控制器
package cn.gzsxt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.annotation.SessionScope;
@Controller
@SessionScope
@RequestMapping(value="/admin")
public class AdminController {
@RequestMapping(value="/addAdmin")
public String addAdmin() {
System.out.println("-增加管理员-");
return "/addAdmin.jsp";
}
}
编写配置类
@Configuration
@ComponentScan(basePackages="cn.gzsxt")
public class ContextConfig {
}
--容器配置类
package cn.gzsxt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc //<mvc:annotation-driver>
public class MvcConfig extends WebMvcConfigurerAdapter {
//<mvc:default-servlet-handler>,放开静态资源访问
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
--SpringMVC配置类
- 编写返回的页面
《返回到请求页面就可以了》
第二部分:配置Mybatis框架
Mybatis配置流程图
导入包(JDBC驱动包,Mybatis框架包,Log4j)配置步骤说明
<!-- 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.47</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
创建一个总配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
<configuration>
<environments default="rbac">
<environment id="rbac">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/rbac-1227" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
</configuration>
创建一个帮助类获得会话对象
package cn.gzsxt.utils;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils {
public static final SqlSessionFactory SESSION_FACTORY=MybatisUtils.createSqlSessionFactory();
private static SqlSessionFactory createSqlSessionFactory() {
try {
//读取配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//创建会话工厂构建类对象
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//返回会话工厂
return builder.build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static SqlSession getSqlSession() {
return SESSION_FACTORY.openSession();
}
public static void main(String[] args) {
System.out.println(MybatisUtils.getSqlSession());
}
}
创建一个映射接口(包括操作SQL语句的)
package cn.gzsxt.mapper;
import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
/**
* 管理员映射接口,用于操作tb_admin表
*
* @author ranger
*
*/
public interface AdminMapper {
/**
* 增加管理员记录
*
* @param admin
* @return
*/
@Insert("INSERT INTO tb_admin(admin_name, admin_account, admin_pwd, admin_status, admin_create_date, role_id) VALUES (#{admin_name}, #{admin_account}, #{admin_pwd}, #{admin_status}, #{admin_create_date}, #{role_id})")
@Options(useGeneratedKeys = true, keyProperty = "admin_id")
int insert(Map<String, Object> admin);
}
在总配置文件加载该映射接口
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
<configuration>
<environments default="rbac">
<environment id="rbac">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="org.gjt.mm.mysql.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/rbac-1227" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="cn.gzsxt.mapper.AdminMapper"/>
</mappers>
</configuration>
编写一个测试类,测试插入数据
第三部分:整合这个两个框架
配置步骤:
- 导入包(哪些包)
(1)Mybatis-Spring整合包
(2)第三方数据源包(DBCP2)
(3)SpringJdbc+SpringTx (事务的支持)
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<!-- dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.2.0</version>
</dependency>
<!-- spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.16.RELEASE</version>
<scope>test</scope>
</dependency>
创建数据源
@Value("${db.driverClassName}")
private String driverClassName;
@Value("${db.url}")
private String url;
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
//第一步:创建一个数据源
@Bean
public DataSource getDataSource() {
BasicDataSource dataSource=new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
- 创建支持Spring数据源的会话工厂
//第二步:获得会话工厂
@Bean(name="sqlSessionFactory")
public SqlSessionFactory getSessionFactory() {
SqlSessionFactoryBean factoryBean=new SqlSessionFactoryBean();
//指定使用的数据源
factoryBean.setDataSource(this.getDataSource());
try {
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
扫描映射接口的动态对象到Spring容器里面
//扫描映射接口的动态对象到Spring容器
@MapperScan(basePackages="cn.gzsxt.mapper",annotationClass=Mapper.class)
配置事务代理
@EnableTransactionManagement //<tx:annotation-driver>
//第四步:配置事务代理
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager() {
DataSourceTransactionManager dstm=new DataSourceTransactionManager();
//指定需要事务代理的数据源
dstm.setDataSource(this.getDataSource());
return dstm;
}
删除之前Mybatis帮助类以及配置文件。因为Mybatis配置好整合以后,已经交由Spring管理了。所以不需要原来的配置文件以及帮助类了!!
- 修改映射接口增加@Mapper注解
package cn.gzsxt.mapper;
import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
/**
* 管理员映射接口,用于操作tb_admin表
*
* @author ranger
*
*/
@Mapper //增加扫描注解!!!
public interface AdminMapper {
/**
* 增加管理员记录
*
* @param admin
* @return
*/
@Insert("INSERT INTO tb_admin(admin_name, admin_account, admin_pwd, admin_status, admin_create_date, role_id) VALUES (#{admin_name}, #{admin_account}, #{admin_pwd}, #{admin_status}, #{admin_create_date}, #{role_id})")
@Options(useGeneratedKeys = true, keyProperty = "admin_id")
int insert(Map<String, Object> admin);
}
编写一个测试类测试
package cn.gzsxt.test.mapper;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import cn.gzsxt.config.ContextConfig;
import cn.gzsxt.config.DataConfig;
import cn.gzsxt.mapper.AdminMapper;
@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {ContextConfig.class,DataConfig.class})
@WebAppConfiguration //声明该单元测试在SpringMVC项目里面的
public class AdminMapperTest {
@Autowired
private AdminMapper adminMapper;
@Test
public void insert() {
Map<String, Object> admin=new HashMap<String, Object>();
admin.put("admin_name", "ranger");
admin.put("admin_create_date", new Date());
adminMapper.insert(admin);
System.out.println(admin.get("admin_id"));
}
}