springboot与mybatis整合的方法

整合MyBatis

新建Spring Boot项目,或以Chapter1为基础来操作

pom.xml中引入依赖

这里用到spring-boot-starter基础和spring-boot-starter-test用来做单元测试验证数据访问

引入连接mysql的必要依赖mysql-connector-java

引入整合MyBatis的核心依赖mybatis-spring-boot-starter

这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖

 org.springframework.boot spring-boot-starter-parent 1.3.2.RELEASE    org.springframework.boot spring-boot-starter   org.springframework.boot spring-boot-starter-test test   org.mybatis.spring.boot mybatis-spring-boot-starter 1.1.1   mysql mysql-connector-java 5.1.21 

登录后复制

同之前介绍的使用jdbc和spring-data连接数据库一样,在application.properties中配置mysql的连接配置

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

同其他Spring Boot工程一样,简单且简洁的的完成了基本配置,下面看看如何在这个基础下轻松方便的使用MyBatis访问数据库。

使用MyBatis

在Mysql中创建User表,包含id(BIGINT)、name(INT)、age(VARCHAR)字段。同时,创建映射对象User

public class User {  private Long id;  private String name;  private Integer age;  // 省略getter和setter}

登录后复制

创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作

@Mapperpublic interface UserMapper {  @Select("SELECT * FROM USER WHERE NAME = #{name}")  User findByName(@Param("name") String name);  @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")  int insert(@Param("name") String name, @Param("age") Integer age);}

登录后复制

创建Spring Boot主类

@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}

登录后复制

创建单元测试

测试逻辑:插入一条name=AAA,age=20的记录,然后根据name=AAA查询,并判断age是否为20
测试结束回滚数据,保证测试单元每次运行的数据环境独立

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = Application.class)public class ApplicationTests { @Autowired private UserMapper userMapper; @Test @Rollback public void findByName() throws Exception { userMapper.insert("AAA", 20); User u = userMapper.findByName("AAA"); Assert.assertEquals(20, u.getAge().intValue()); }}

登录后复制

以上就是springboot与mybatis整合的方法的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2626390.html

(0)
上一篇 2025年3月7日 00:52:18
下一篇 2025年3月7日 00:52:28

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论