SpringBoot 集成 Mybatis

用 Interllij IDEA 创建项目就不贴了

  1. 添加相关依赖

pom 文件中依赖



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.4
         
    
    com.example
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-data-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        
        
            com.alibaba
            druid
            1.0.29
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                src/main/java
                
                    **/*.properties
                    **/*.xml
                
                false
            
        
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                    true
                
            
        


    



  1. 编写 mapper

LoginMapper

@Mapper
public interface LoginMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectUser(int id);

    User selectUserOnly(Long id);
}

LoginMapper.xml





    


  1. 编写 Controller
@RestController
public class UserControl {

    @Autowired
    LoginMapper loginMapper;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public User addNewArticle(@RequestParam(value = "user_id", defaultValue = "1")Integer id) {
        User user = loginMapper.selectUser(id);
        return user;
    }

    @RequestMapping(value = "/user_only", method = RequestMethod.GET)
    public User selectUserOnly(@RequestParam(value = "user_id", defaultValue = "1")Long id) {
        User user = loginMapper.selectUserOnly(id);
        return user;
    }
}

  1. 配置文件
    application.properties
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.url=jdbc:mysql://120.79.214.74/vueblog2?useUnicode=true&characterEncoding=UTF-8
spring.datasource.url=jdbc:mysql:///vueblog2?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
mybatis.config-location=classpath:/mybatis-config.xml
#jdbc:mysql://localhost:3306/heima
server.port=8088
logging.level.org.springframework.security=info
  1. 文件目录
image.png

你可能感兴趣的:(SpringBoot 集成 Mybatis)