Mybatis与Springboot的整合

1.导入sprinboot依赖,数据库连接依赖,mybatis依赖,junit依赖



        org.springframework.boot
        spring-boot-starter-parent
        2.7.10
         




    org.mybatis.spring.boot
    mybatis-spring-boot-starter


		
			org.springframework.boot
			spring-boot-starter
		
    
            mysql
            mysql-connector-java
            5.1.47 
        
         
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

2.编写mybatis核心配置文件(yml)

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 3237never
    url: jdbc:mysql://localhost:3306/greatecommunity
  #配置映射文件位置,相当于在xml中的
  mybatis:
    mapper-locations: classpath:com/duhong/mapper/*.xml

3.配置mapper映射文件,注意namespace 必须指定对应mapper接口的权限定类名,而且映射文件目录结构要与mapper接口一致,映射文件去掉xml的名称与mapper接口名称一致。

 
        
        

4.编写mapper接口

@Mapper
public interface UserMapper {
    int insertUser(User user);
    List selectAll();
}

5.测试

@SpringBootTest
public class Maintest {
    @Autowired
    private UserMapper userMapper;
    @Test
    void testinsertUser(){

        List users = userMapper.selectAll();
        System.out.println(users);
    }
}

你可能感兴趣的:(mybatis,spring,boot,后端)