spring-boot-mybatis搭建
写在开始
mybatis是一个持久化框架,支持手动sql、存储过程、高级映射。mybatis支持XML方式或注解方式将POJO与数据库表间建立映射。
maven依赖
spring-boot、mysql、mybatis
项目目录结构
整体配置
1 Entity实体;
2 Mapper接口;
3 基于XML的实体、表、接口映射表;
4 配置文件中的映射表位置指向。
第一部分 Entity实体
package com.example.demo.entity; /** * @Author:tianminghai * @Date:3:13 PM 2018/10/26 */ public class CarEntity { private int carId; private String carName; private int isDel; public int getCarId() { return carId; } public void setCarId(int carId) { this.carId = carId; } public String getCarName() { return carName; } public void setCarName(String carName) { this.carName = carName; } @Override public String toString() { return "CarEntity{" + "carId=" + carId + ", carName='" + carName + '\'' + ", isDel=" + isDel + '}'; } public int getIsDel() { return isDel; } public void setIsDel(int isDel) { this.isDel = isDel; } }
第二部分 Mapper接口
接口提供三个方法:
1根据车辆ID查询车辆;
2查询所有车辆;
3根据车辆ID批量删除车辆
package com.example.demo.mapper; import com.example.demo.entity.CarEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @Author:tianminghai * @Date:3:12 PM 2018/10/26 */ @Mapper public interface CarMapper { CarEntity selectByPrimaryKey(@Param("carId") Integer carId); List<CarEntity> selectAll(); boolean batchRemoveCarByPks(List<Integer> list); }
第三部分 基于XML的实体、表、接口映射表
resultMap 定义实体和表的映射关系
sql定义返回值
del定义删除语句,foreach用于循环列表
#{carId,jdbcType=INTEGER}代码段用于在sql中引入变量
<?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.example.demo.mapper.CarMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.CarEntity"> <id column="car_id" jdbcType="INTEGER" property="carId"/> <result column="car_name" jdbcType="VARCHAR" property="carName"/> <result column="is_del" jdbcType="INTEGER" property="isDel"/> </resultMap> <sql id="Base_Column_List"> car_id,car_name,is_del </sql> <!-- 通过主键集合批量删除记录 --> <delete id="batchRemoveCarByPks" parameterType="java.util.List"> DELETE FROM car WHERE car_id in <foreach collection="list" item="dataId" index="index" open="(" close=")" separator=","> #{dataId} </foreach> </delete> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from car where car_id = #{carId,jdbcType=INTEGER} </select> <select id="selectAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from car </select> </mapper>
第四部分 配置文件中的映射表位置指向
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=Aa123123
mybatis.mapper-locations=classpath:mapper/*.xml
到目前为止项目已经可以跑起来了~~~
关于@MapperScan注解
Application里的@MapperScan注解指定mybatis搜索的包名。XML中mapper可以指定mybatis中一个mapper的命名空间。当填写了XML之后可以不用添加注解,项目同样可以跑通
注意XML文件当中不能随意加空格和TAB,这两个符号可能导致接口发生错误