详情可以参考Mybatis官方文档 http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
(1)、引入Mybatis针对SpringBoot制作的Starter依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
(2)、配置Mybatis设置
package cn.coreqi.config; import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class MybatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true); //开启驼峰命名
}
};
}
}
(3)、编写Mapper接口
package cn.coreqi.mapper; import cn.coreqi.entities.User;
import org.apache.ibatis.annotations.*; //@Mapper 告诉SpringBoot这是一个操作数据库的mapper
@Mapper
public interface UserMapper {
@Select("select * from users where Id = #{id}")
public User getUserById(Integer id); @Insert("insert into users(UserName,PassWord,Enabled) values(#{UserName},#{PassWord},#{Enabled})")
@Options(useGeneratedKeys = true,keyProperty = "Id") //使用自增主键,并指定主键的列名称
public int addUser(User user); @Update("update users set UserName = #{UserName},PassWord = #{PassWord},Enabled = #{Enabled} where Id = #{Id}")
public int modifyUser(User user); @Delete("delete from users where Id = #{id}")
public int delUserById(Integer id); }
(4)、扫描所有的Mapper接口
package cn.coreqi; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
@MapperScan(value = "cn.coreqi.mapper") //扫描指定路径下所有的Mapper接口
public class SpringbootjdbcApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootjdbcApplication.class, args);
} }