回顾:在第一步中,我们实现了springmvc的hello world。这一部分,我们引入mybatis
第二步
修改build.gradle,引入mybatis相关包
group 'wantdoc'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
war.destinationDir = file("target")
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'org.springframework:spring-webmvc:4.3.5.RELEASE'
compile 'org.springframework:spring-jdbc:4.3.5.RELEASE'
compile 'mysql:mysql-connector-java:5.1.25'
compile 'org.mybatis:mybatis:3.4.2'
compile 'org.mybatis:mybatis-spring:1.3.1'
compile 'c3p0:c3p0:0.9.1.2'
}
添加spring-mybatis.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:conf/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${db.driver}"/>
<property name="jdbcUrl" value="${db.url}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="initialPoolSize" value="${pool.initialPoolSize}"/>
<property name="minPoolSize" value="${pool.minPoolSize}"/>
<property name="maxPoolSize" value="${pool.maxPoolSize}"/>
<property name="maxIdleTime" value="${pool.maxIdleTime}"/>
<property name="acquireIncrement" value="${pool.acquireIncrement}"/>
<property name="checkoutTimeout" value="${pool.checkoutTimeout}"/>
<property name="idleConnectionTestPeriod" value="5"/>
<property name="preferredTestQuery" value="select 1"/>
</bean>
<bean id="mybatisTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="mybatisTransactionManager"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 配置扫描Mapper XML的位置 -->
<property name="mapperLocations" value="classpath*:com/demo/mapper/*.xml"/>
</bean>
<!-- 配置扫描Mapper接口的包路径 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.demo.mapper"/>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory"/>
</bean>
</beans>
由第一项placceholder配置看出,db配置我们单独提出,内容如下
修改web.xml,加入如下代码
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-root.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
由第一个contextConfigLocation配置可见,新增了一个spring-root.xml配置文件,现阶段主要为了引入spring-mybatis.xml,后续我们引入security的时候,spring-security.xml也在spring-root.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-mybatis.xml"/>
</beans>
OK,mybatis配置工作告一段落。可以开始添加mapper映射文件
首先,我们新建一个interface
package com.demo.mapper;
import org.apache.ibatis.annotations.Param;
public interface DemoMapper {
int getB(@Param("a") int a);
}
然后新建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.demo.mapper.DemoMapper">
<select id="getB" resultType="java.lang.Integer">
select b from test1 where a=#{a}
</select>
</mapper>
到这里,读者应该有疑惑,未见mysql数据库安装配置步骤。这又是另一个话题了,这里省略不谈,只贴出建表sql
CREATE TABLE `test_account` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL COLLATE utf8mb4_unicode_ci,
`password` varchar(100) NOT NULL COLLATE utf8mb4_unicode_ci,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
controller中,我们新增个简单的db操作接口
package com.demo.controller;
import com.demo.mapper.DemoMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping(value = "/call")
public class DemoController {
@Resource
private DemoMapper demoMapper;
@RequestMapping(value = "/test")
public String test(){
return "hello wolrd";
}
@RequestMapping(value = "/testDb")
public String testDb(){
int b = demoMapper.getB(2);
return Integer.toString(b);
}
}
最终文件目录结构如下
运行测试
OK,第二步完
补充说明
说明一
新建mapper映射文件的时候,spring-mybatis.xml总是会提示找不到xml文件
并且,使用mapper接口的时候,会报异常
Caused by:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.demo.mapper.DemoMapper.getB
at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:230)
网上有类似的问题可查询,但大都是xml文件没有编译到war包,而我查过war包xml文件是在的,所以并不能解决我的问题,并且试过网上的方法也确实没有生效。相关资料如下
https://my.oschina.net/someok/blog/508643
https://youtrack.jetbrains.com/issue/IDEA-128273
之前是怀疑intellij idea对于interface和xml文件所在包名相同的情况下,检测xml文件有问题,因为在配置mapperlocations时自动补全com/demo/mapper后面的内容只有java文件
所以尝试修改xml的包名,如把com/demo/mapper改为com/demo/mappers,再修改mapperlocations,确实可以找到了。然后心念一动,把包名再改回com/demo/mapper,也可以找到了
奇怪,但解决了问题,这种方法也暂时成为了我解决这个问题的方法,哈哈
如果有读者知道这种情况何解,欢迎留言指教
说明二
下面这个映射是有隐患的,如果sql返回的b为空,然后null转换成int会报错。我这里是测试用例,用例使用的参数和数据库表里面的数据是可以保证传回的值不为空。但担心读者被误导,特此说明
public interface DemoMapper {
int getB(@Param("a") int a);
}
<select id="getB" resultType="java.lang.Integer">
select b from test1 where a=#{a}
</select>