SpringBoot中配置使用Mybatis

在SpringBoot项目中使用mybatis操作数据库有两种方式:一种是使用注释的方式来对数据库进行操作;另一种方式是使用xml配置文件的方式来操作数据库。一般常用的是使用xml文件的方式来配置使用MyBatis

注解方式:

1.定义一个接口例如:

@Mapper

public interface DepartmentMapper {}

2.定义对应的方法:

@Select("select * from department where id=#{id}")

public Department getDeptById(Integer id);

这样就可以在Controller中调用对应的方法了。

这里主要和Mybatis有关的的是Mapper注释也可以在配置文件中加上@MapperScan(value = "com.bicheng.learn.mapper")

就不需要每一个接口一一添加Mapper了。

xml文件配置方式:

使用配置文件方式需要创建一个MyBatis的一个全局的配置文件。来需要创建一个接口创建一个对应的Mapper配置文件中配置文件中写对应的SQL。然后需要在SpringBoot的配置文件中指定配置文件的位置和mapper的xml的位置。

mybatis:

config-location: classpath:mybatis/mybatis-config.xml

mapper-locations: classpath:mybatis/mapper/*.xml

mybatis的全局配置文件中MyBatis官网中就有:SpringBoot中配置使用Mybatis

对应接口的配置文件模板:

SpringBoot中配置使用Mybatis

 

相关文章:

  • 2022-12-23
  • 2021-04-19
  • 2022-12-23
  • 2021-07-27
  • 2021-10-28
  • 2021-05-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-12
  • 2021-12-20
  • 2022-12-23
  • 2021-10-24
  • 2021-06-22
  • 2022-12-23
相关资源
相似解决方案