Springboot集成mybatis

1.在pom.xml引入依赖

 
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.1.1
        
        
            mysql
            mysql-connector-java
        

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";
    }
}

你可能感兴趣的:(Springboot集成mybatis)