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官网中就有:
对应接口的配置文件模板: