本文主要講解如何在Springboot中逐步實(shí)現(xiàn)對(duì)MyBatis的集成應(yīng)用。
1、引入依賴
在pom.xml文件中引入mybatis依賴。
// pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
2、參數(shù)配置
在Application.yml配置文件中寫入mybatis相關(guān)配置。
mybatis:
mapper-locations: classpath:mybatis/mapper/**/*.xml #注意:一定要對(duì)應(yīng)mapper映射xml文件的所在路徑
type-aliases-package: com.knight.ygtcloud.base.entity # 注意:對(duì)應(yīng)實(shí)體類的路徑
# spring boot集成mybatis的方式打印sql
configuration:
log-impl: org.Apache.ibatis.logging.nologging.NoLoggingImpl #不打印SQL
map-underscore-to-camel-case: true #開啟自動(dòng)下劃線格式轉(zhuǎn)駝峰格式
3、mapper文件
編寫mapper文件如下:
public interface SysUserMapper {
int deleteByPrimaryKey(Long id);
int insert(SysUser record);
int insertSelective(SysUser record);
SysUser selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(SysUser record);
int updateByPrimaryKey(SysUser record);
}
4、MapperScan注解
在主應(yīng)用Application上通過@MapperScan注解指定mapper文件的掃描路徑。
@MapperScan("com.myApp.dao")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication .class, args);
}
}
5、xml映射文件
在配置文件指定路徑(classpath:mybatis/mapper/**/*.xml)下編寫mapper對(duì)應(yīng)的xml映射文件,參考內(nèi)容如下:
<?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.knight.ygtcloud.base.dao.SysUserMapper">
<resultMap id="BaseResultMap" type="com.knight.ygtcloud.base.entity.SysUser">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="login_name" jdbcType="VARCHAR" property="loginName" />
<result column="mix_pd" jdbcType="VARCHAR" property="mixPd" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<
</resultMap>
<sql id="Base_Column_List">
id, login_name, mix_pd, user_name, user_type, user_code, sex, note, mobile, dept_first_id,
dept_first_name, dept_second_id, dept_second_name, org_id, org_name, email, state,
openId, userId, create_time, create_id, create_name, head_image, phone_image, lock_times,
lock_time, account_type, tech_title_key, tech_title_value, is_expert, sickness_id_list,
sickness_name_list, duty_key, duty_value, education_key, education_value, create_org_id,
create_org_name, wx_nick_name, wx_country, wx_province, wx_city, belong_org_province_id,
belong_org_province_name, belong_org_city_id, belong_org_city_name, belong_org_county_id,
belong_org_county_name, belong_org_town_id, belong_org_town_name, belong_org_village_id,
belong_org_village_name, online_state
</sql>
<select id="selectByPrimaryKey" parameterType="JAVA.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_user
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from sys_user
where id = #{id,jdbcType=BIGINT}
</delete>
</mapper>