正文共:888 字 14 图 预估阅读时间:1 分钟
1、使用Spring boot整合MyBatis,实现根据用户id查询用户信息功能。
1.1、在springboot数据库中,使用tb_user.sql创建数据表tb_user。
1.2、创建initialize工程
1.3、所需依赖如下,请将新建工程里没有的依赖补充进pom文件中,注意别放重了。
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
<scope>runtime</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>1.2.20</version></dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope></dependency>
1.4、创建实体类User
package com.my.yanli.entity;
import lombok.Data;
class User {
private int id;
private String name;
private int age;
private String email;}
1.5、创建Mapper接口与映射文件
1.5.1、创建mapper接口
package com.my.yanli.mapper;
import com.my.yanli.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
public User getUserById(Integer id);}
1.5.2、创建映射文件
注意:namespace的值要和你的接口的全路径相同。
<mapper namespace="com.my.yanli.mapper.UserMapper">
<select id="getUserById" resultType="User" parameterType="int">
select * from tb_user where id=#{id}
</select></mapper>
1.6、创建服务层接口和实现类
1.6.1、创建服务层接口
package com.my.yanli.service;
import com.my.yanli.entity.User;
public interface UserService {
public User getUserById(Integer id);}
1.6.2、创建服务层实现类
1.7、创建控制类
import com.my.yanli.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/getUserById/{id}")
public User getUserById(@PathVariable Integer id){
return userService.getUserById(id);
}}
1.8、创建配置文件application.yml
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.my.yanli.entity
configuration: map-underscore-to-camel-case: true
1.9、启动启动类
观察控制台是否报错。
1.10、如果成功启动,输入访问地址:
长按二维码
关注我们吧