栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1. springboot整合mybatis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1. springboot整合mybatis

一、搭建一个简单的springboot工程

二、引入相关依赖
  1. pom.xml
	
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.0
        
三、使用配置文件的方式 1. 准备工作
  1. 实体类
@Data
public class User {

    @Id
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  1. UserMapper
@Mapper
public interface UserMapper {

    public User getUser(String username);
}

  1. UserService
@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public User getUserByName(String username){
        return userMapper.getUser(username);
    }
}
2. 配置相应的xml
  1. 创建配置文件mybatis-config.xml,从 XML 中构建 SqlSessionFactory这里可以参考官网的说明 https://mybatis.org/mybatis-3/zh/getting-started.html.



    




  1. 创建UserMapper.xml,探究已映射的 SQL 语句



    
        select * from User where username = #{username}
    

  1. 配置mybatis规则,application.yaml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    # url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    username: root
    password: 2550
    driver-class-name: com.mysql.cj.jdbc.Driver
# 配置mybatis规则
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
3. 测试
	@ResponseBody
    @GetMapping("/user")
    public User getUserByName(@RequestParam("username") String username) {
        return userService.getUserByName(username);
    }

四、使用注解

添加依赖 参考第二步

1. 数据准备
  1. 创建一张表
  2. 创建实体类City
@Data
public class City {

    private Long id;
    private String name;
    private String state;
    private String country;
}
  1. 创建CityMapper
@Mapper
public interface CityMapper {

    @Select("select * from city where id = #{id} ")
    public City getById(Long id);
}
2. 测试方法
  1. 创建CityService
@Service
public class CityService {

    @Autowired
    CityMapper cityMapper;

    public City getCityById(Long id) {
        return cityMapper.getById(id);
    }
}
  1. 测试方法
	@Autowired
    CityService cityService;

    @ResponseBody
    @GetMapping("/city")
    public City getCityById(@RequestParam("id")Long id) {
        return cityService.getCityById(id);
    }
  1. 测试
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/868290.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号