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.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"; } }
可以成功获取