之前闲着没事,研究了下IntelliJ IDEA + Spring Boot + Mybatis的整合
http://blog.csdn.net/qq_33337504/article/details/77983793
由于最早使用的是注解的方式来连接数据库,所以比较简单,后来发行做后台的同事用的一般都是xml的形式,所以也跟着学习了下。发行mapper接口和xml配置sql,比较复杂,尤其是对我这种新手,研究了好久才配置成功。为了防止忘记,故写下来,也给准备学习的人当参考资料。
1.首先在配置文件application.properties中,写上相关的信息
mybatis.typeAliasesPackage
mybatis.mapperLocations
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=***
spring.datasource.password=***
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis.typeAliasesPackage:为实体对象所在的包,跟数据库表一一对应
#mybatis.mapperLocations:mapper文件的位置
mybatis.typeAliasesPackage=com.test.dailyreport.bean
mybatis.mapperLocations=classpath:mybatis/mapper/*Mapper.xml
#写法不同,不过结果一样
#mybatis.type-aliases-package=com.test.dailyreport.bean
#mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml
2.在启动类Application.java中写上配置信息
@SpringBootApplication
@MapperScan("com.test.dailyreport.dao") // mybatis扫描路径,针对的是接口Mapper类
public class DailyreportApplication{
public static void main(String[] args) {
SpringApplication.run(DailyreportApplication.class, args);
}
}
3.写mapper.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" >
<!--你接口的包名是com.abc.dao,接口名是NameMapper.java,那么你的mapper.xml的namespace应该是com.abc.dao.NameMapper-->
<mapper namespace="com.test.dailyreport.dao.UserMapper" >
<!--resultMap对应的是表与实体类的映射 - type 数据库表对应的实体类,别名或完整类名都可以-->
<resultMap id="BaseResultMap" type="com.test.dailyreport.bean.UserBean" >
<!-- 结果集的主键 -->
<id column="id" property="id" jdbcType="INTEGER" />
<!-- 普通的列 -column 是数据库中字段, property是实体类中字段-->
<result column="token" property="token" jdbcType="VARCHAR" />
<result column="account" property="account" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="department" property="department" jdbcType="VARCHAR" />
<result column="user_name" property="name" jdbcType="VARCHAR" />
</resultMap>
<!--parameterType(输入类型)、resultType(输出类型)-->
<select id="loginByAccount" parameterType="String" resultMap="BaseResultMap" resultType="com.test.dailyreport.bean.UserBean">
SELECT * FROM USER_DETAIL WHERE account = #{account,jdbcType=VARCHAR}
</select>
</mapper>
4.本人是用gradle配置文件的,如果没有写上依赖
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1")
compile('mysql:mysql-connector-java')
maven没有测试过,网上找了下
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
这样就成功的使用mapper接口和xml配置sql
参考资料http://www.cnblogs.com/yhzh/p/6674000.html
mapper.xml中常用的标签比较多,网上资料也很多,觉得这篇写的挺详细的,推荐下
http://blog.csdn.net/qq_29233973/article/details/51433924