springboot结合mybatis
Posted yanguobin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot结合mybatis相关的知识,希望对你有一定的参考价值。
idea中新建springboot项目
pom.xml依赖部分如下
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> </dependencies>
application.properties如下
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false spring.datasource.username=root spring.datasource.password=123 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
数据表内容如下
用户实体类如下
public class User private int id; private String name; @Override public String toString() return "User" + "id=" + id + ", name=‘" + name + ‘\\‘‘ + ‘‘; public int getId() return id; public void setId(int id) this.id = id; public String getName() return name; public void setName(String name) this.name = name;
dao层用户接口如下
@Mapper public interface UserDao @Select("select * from user where id = #id") public User hello(@Param("id")int id );
@Mapper和@Select等注解都在mybatis-3.5.2.jar包下
注意依赖中还引入了mybatis-spring-boot-starter依赖,它会提供如下功能:
- 自动检测现有的DataSource
- 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
- 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例
- 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中
测试
@Controller public class UserController @Autowired UserDao userDao; @RequestMapping("/get") @ResponseBody public String get() User user = userDao.hello(1); System.out.println(user); return "hello world";
可以成功获取
以上是关于springboot结合mybatis的主要内容,如果未能解决你的问题,请参考以下文章
mybatisSpring整合(eclipse)以及事务管理
Spring+SpringMVC+MybatisSpring+SpringMVC+Mybatis实现前端到后台完整项目