导包

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

配置

application.properties/yaml

在application中配置mapperlocation(使用xml的配置)

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/laptime_page?serverTimezone=Asia/Shanghai
    username: 
    password: 
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.roderick.pojo
  mapper-locations: classpath:mybatis/*.xml

Dao接口

如果打算sql打算使用注解完成就可以不写mapper的配置,但是接口上要使用@Mapper的注解(用xml写上也无妨)

@Mapper
@Repository
public interface VehicleDao {
    List<Vehicle> listVehicle();
}

Mapper

<?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.roderick.dao.VehicleDao">
    <select id="listVehicle" resultType="com.roderick.pojo.Vehicle">
        select * from vehicle
    </select>
</mapper>

parameterType有多个参数的解决办法

使用@param
Dao接口

@Mapper
@Repository
public interface ImageDao {

//    @Select("insert into image (vehicle_id,image_path) value (#{vehicle_id},#{image_path})")
    void insertImage(@Param("vehicle_id") int vehicle_id, @Param("image_path") String image_path);
}

Mapper配置文件就可以不用写parameterType

<?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.roderick.dao.ImageDao">
    <insert id="insertImage">
        insert into image (vehicle_id,image_path)
        value (#{vehicle_id},#{image_path})
    </insert>
</mapper>

还可以使用HashMap或者LIst进行封装

获取刚在数据库中主键自增生成的id(自增)

Dao接口:

void insertAuthor(Author author);

mybatis官方文档办法:
首先,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置为目标属性就 OK 了。例如,如果上面的 Author 表已经在 id 列上使用了自动生成,那么语句可以修改为:

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})
</insert>

获取id调用:

Author author = new Author;
insertAuthor(author);
int id = author.getId();

RoderickXiang
1 声望0 粉丝

菜鸡一枚