引入相关的依赖

引入mybatis-starter

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

操作MySQL数据库还需要引入MySQL驱动。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

编写实体类

@Data
public class City {
    private Long id;
    private String name;
    private String state;
    private String country;
}

编写数据库持久层

@Mapper
public interface CityMapper {

    @Select("select * from city")
    City getById(Long id);

    @Insert("insert into city(`name`, `state`, `country`) values(#{name},#{state},#{country})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(City city);
}

如果在主类中使用了@MapperScan("top.lukeewin.admin.mapper")注解,则不用在每个类中的使用@Mapper注解。

也可以编写Mapper.xml文件,如上面的例子就是纯注解开发,适合简单CRUD的开发,复杂场景中推荐编写对应的Mapper.xml文件。

编写映射文件

在resources目录下创建mybatis目录,并且在该目录下创建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="top.lukeewin.admin.mapper.CityMapper">
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into city(`name`, `state`, `country`) values(#{name},#{state},#{country})
    </insert>
</mapper>

编写业务逻辑

public interface CityService {

    City getById(Long id);

    void saveCity(City city);
}
@Service
public class CityServiceImpl implements CityService {

    @Autowired
    CityMapper cityMapper;

    @Override
    public City getById(Long id) {
        return cityMapper.getById(id);
    }

    @Override
    public void saveCity(City city) {
        cityMapper.insert(city);
    }

}

编写控制层

@ResponseBody
@GetMapping("/city")
public City getCityById(@RequestParam("id") Long id) {
    return cityService.getById(id);
}

Q.E.D.


热爱生活,热爱程序