spring boot 整合mybatis

前言

前面已经完成了分模块的spring boot项目搭建,现在开始加入数据库,我这里用的数据是mysql,dao层框架也是比较常用的mybatis

1、pom添加依赖

在pom中添加mysql mybatis依赖,在主pom文件中添加下面依赖,在需要的子pom中引入就可以了

<!--数据库及mybatis依赖 begin-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql-connect-java-version}</version>
</dependency>

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${spring-mybatis-verison}</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>${spring-mybatis-verison}</version>
</dependency>
<!--数据库及mybatis依赖 end-->

2、application.properties添加数据库配置

application.properties为spring boot默认加载的配置文件,默认路径是

resources/application.properties

在配置文件中添加mysql相关配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=admin
spring.datasource.password=12345
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3、启动类添加mapper扫包配置

spring boot启动类上添加mapper扫包配置

@SpringBootApplication(scanBasePackages = "com.clockbone") 
@MapperScan("com.clockbone.dao")
public class ApplicationBoot {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(ApplicationBoot.class, args);
    }
}

4、mapper类

@Mapper
public interface UserMapper {
    @Select("SELECT ID,USER_ID as userId,USER_NAME as userName FROM USER where id=#{id}")
    User getUserInfo(long id);
}

5、测试类

@Service(value = "userService")
@Slf4j
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public User getUserInfo(Long id) {
        return userMapper.getUserInfo(id);
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ApplicationBoot.class, //启动类
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public  class ApplicationBaseBootTest{
     @Resource
     private UserService userService;
     @Test
     public void userServiceTest(){
         long id = 10;
         User user = userService.getUserInfo(id);
         System.out.println(user);
     }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lh87270202/article/details/79961616
文章标签: spring boot
个人分类: java spring
上一篇spring-boot异常配置,Whitelabel Error Page处理方式
下一篇spring boot 加入库连接池(alibaba druid 数据)及分页插件
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭