1.在pom.xml引入依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.配置文件application.properties,进行数据库配置
#mysql
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3.编写model数据库对应实体,以及Mapper接口
public interface UserMapper {
@Insert("insert into user (name) values (#{name})")
void insertUser(@Param("name")String name);
@Select("select * from user where id = #{id}")
User selectUserById(@Param("id") Integer id);
}
4.在主程序中,使用@MapperScan注解进行Mapper扫描
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.fong.controller")
@MapperScan(basePackages = "com.fong.mapper")
public class App {
public static void main(String [] args) throws Exception{
SpringApplication.run(App.class,args);
}
}
5.编写Controller
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("user-detail")
public User selectUserById(Integer id){
return userMapper.selectUserById(id);
}
@RequestMapping("insert-user")
public String insertUser(){
userMapper.insertUser("zansan");
return "success";
}
}