1.导入sprinboot依赖,数据库连接依赖,mybatis依赖,junit依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.10</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--Mybatis-->
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!--springboot依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--Spring Boot Test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.编写mybatis核心配置文件(yml)
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 3237never
url: jdbc:mysql://localhost:3306/greatecommunity
#配置映射文件位置,相当于在xml中的<package name="com.duhong.dao"/>
mybatis:
mapper-locations: classpath:com/duhong/mapper/*.xml
3.配置mapper映射文件,注意namespace 必须指定对应mapper接口的权限定类名,而且映射文件目录结构要与mapper接口一致,映射文件去掉xml的名称与mapper接口名称一致。
<mapper namespace="com.duhong.mapper.UserMapper">
<!--id属性对应的名称要与mappe接口中的方法一致-->
<select id="selectAll" resultType="com.duhong.entity.User">
select * from users;
</select>
</mapper>
4.编写mapper接口
@Mapper
public interface UserMapper {
int insertUser(User user);
List<User> selectAll();
}
5.测试
@SpringBootTest
public class Maintest {
@Autowired
private UserMapper userMapper;
@Test
void testinsertUser(){
List<User> users = userMapper.selectAll();
System.out.println(users);
}
}