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接口文章来源:https://www.toymoban.com/news/detail-807783.html
@Mapper
public interface UserMapper {
int insertUser(User user);
List<User> selectAll();
}
5.测试文章来源地址https://www.toymoban.com/news/detail-807783.html
@SpringBootTest
public class Maintest {
@Autowired
private UserMapper userMapper;
@Test
void testinsertUser(){
List<User> users = userMapper.selectAll();
System.out.println(users);
}
}
到了这里,关于Mybatis与Springboot的整合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!