db.properties配置了数据库连接的相关信息
jdbc_driver=com.mysql.cj.jdbc.Driver jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai jdbc_username=root jdbc_password=root jdbc_initialSize=10 jdbc_maxActive=20 复制代码
2.4 MyBatis的配置
配置MyBatis全局配置文件mybatis-config.xml,只配置settings标签就可以,数据源、mapper等配置在Spring配置文件application.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"/> <!--开启懒加载--> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <!--开启二级缓存--> <setting name="cacheEnabled" value="true"/> </settings> </configuration> 复制代码
在Spring配置文件application.xml中将Myabtis整合到Spring中,需要先导入Mybatis-Spring的依赖
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> 复制代码
在application.xml中增加SqlSessionFactoryBean配置
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="mybatis-config.xml"></property> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:/mappers/*.xml"></property> </bean> 复制代码
将mapper包下的Mapper接口全部加入到Spring容器中
<!--持久层接口加入到Spring容器--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定接口所在的包--> <property name="basePackage" value="com.citi.mapper"></property> </bean> 复制代码
2.5 其他配置
mybatis日志配置logback.xml,放在resource目录下。可以在控制台打印出SQL
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>[%thread] %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="console"/> </root> </configuration> 复制代码
至此Spring、Spring MVC、MyBatis三个框架整合完成
3.测试
持久层Mapper接口测试
数据库表与上一篇QA 由浅入深持久层框架(七)- MyBatis Cache用到的是同一张表,即t_teacher,这里不再重复
新建entity包,增加Teacher实体类
@Data public class Teacher implements Serializable { private Integer id; private String teacherName; private String className; private String address; private Date birthDate; } 复制代码
新建mapper包,增加TeacherMapper接口,并增加一个根据id查询Teahcer的方法
public interface TeacherMapper { Teacher getTeacherById(Integer id); } 复制代码
在resources目录下新增mappers文件夹,用来存放Mapper接口的SQL映射文件,新建TeacherMapper接口的SQL映射文件TeacherMapper.xml
<?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.citi.mapper.TeacherMapper"> <!--开启二级缓存--> <cache></cache> <select id="getTeacherById" resultType="com.citi.entity.Teacher"> select * from t_teacher where id = #{id} </select> </mapper> 复制代码
在test包下新增TeacherMapper接口的测试类TeacherMapperTest,新增getTeacherById方法的测试方法
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:application.xml") public class TeacherMapperTest { @Autowired private TeacherMapper teacherMapper; @Test public void getTeacherById() { teacherMapper.getTeacherById(1); } } 复制代码
测试类中用到了Spring Test,主要不要忘记类上的两个注解
执行测试方法
成功查询到了id为2的Teacher对象
Service层测试
新建service包,在该包下新增TeacherService接口,新增一个根据id查找Teacher的方法
public interface TeacherService { Teacher findTeacherById(Integer id); } 复制代码
在service包下新增impl包,用来保存接口的实现类,在impl包中新增TeacherService接口的实现类TeacherServiceImpl
@Service public class TeacherServiceImpl implements TeacherService { @Autowired private TeacherMapper teacherMapper; @Override public Teacher findTeacherById(Integer id) { return teacherMapper.getTeacherById(id); } } 复制代码
增加TeacherService的测试类TeacherServiceTest
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:application.xml") public class TeacherServiceTest { @Autowired private TeacherService teacherService; @Test public void findTeacherById() { Teacher teacher = teacherService.findTeacherById(1); System.out.println(teacher); } } 复制代码
执行测试
控制台成功输出id为1的Teacher对象,说明service层调用mapper层成功
Controller层测试
配置Tomcat前,首先选中项目,点击IDEA菜单的File选项,点击Project Structure,左边选择Artifacts,在WEB-INF下新建一个lib目录,将右侧的jar包全部选中并导入lib文件夹中
配置Tomcat,点击IDEA的DEIT Configurations,配置一个本地的Tomcat
并将项目部署到Tomcat中
编写Controller层代码,新建controller包,增加TeacherController类
@Controller @RequestMapping("/teacher") public class TeacherController { @Resource public TeacherService teacherService; @RequestMapping("/{id}") public ModelAndView findTeacher(@PathVariable("id") Integer id){ Teacher teacher = teacherService.findTeacherById(id); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("teacher",teacher); modelAndView.setViewName("success"); return modelAndView; } } 复制代码
视图解析器已经配置了WEB-INF下的pages目录,所以在WEB-INF下新增pages目录并新增一个jsp文件success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>SUCCESS</h2> <h3>${teacher}</h3> </body> </html> 复制代码
启动Tomcat,浏览器输入地址http://localhost:8080/teacher/1, 查询id为1的Teacher的信息
Spring、Spring MVC、MyBatis整合成功!