整合MyBatis操作 注解模式 混合模式

注解模式

先创建表

create TABLE city
(
id 		int(11) primary key auto_increment,
name 	VARCHAR(30),
state 	VARCHAR(30),
country VARCHAR(30)
);

实体类

@Data
public class City {
    
    

    private Long id;
    private String name;
    private String state;
    private String country;
}

mapper接口 用注解方式查询

@Mapper
public interface CityMapper {
    
    

    @Select("select * from city  where id = #{id}")
    public City getById(Long id);
}

编写service

@Service
public class CityService {
    
    

    @Autowired
    CityMapper cityMapper;

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

编写controller


	@Autowired
    CityService cityService;

    @ResponseBody
    @GetMapping("city")
    public City getById(@RequestParam("id") Long id) {
    
    

        return cityService.getById(id);
    }

测试结果

在这里插入图片描述

保存数据

mapper接口

@Mapper
public interface CityMapper {
    
    

    @Select("select * from city  where id = #{id}")
    public City getById(Long id);

    public void insert(City city);
}

CityMapper.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">
<mapper namespace="com.wenliang.admin.mapper.CityMapper">

<!--    public void insert(City city);-->
    <insert id="insert">
        insert into city(`name`,`state`,`country`) values (#{
    
    name},#{
    
    state},#{
    
    country})
    </insert>

</mapper>

CityService

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

controller

@ResponseBody
    @PostMapping("/city")
    public City saveCity(City city) {
    
    
        cityService.saveCity(city);
        return city;
    }

在这里插入图片描述

上面和下面的的效果是一样的

在这里插入图片描述

测试结果

在这里插入图片描述
最佳实战:

  • 引入mybatis-starter
  • 配置application.yaml中,指定mapper-location位置即可
  • 编写Mapper接口并标注@Mapper注解
  • 简单方法直接注解方式
  • 复杂方法编写mapper.xml进行绑定映射
  • @MapperScan(“com.atguigu.admin.mapper”) 简化,其他的接口就可以不用标注@Mapper注解

猜你喜欢

转载自blog.csdn.net/weixin_51600120/article/details/114888323