使用Spring boot整合MyBatis,实现根据用户id查询用户信息功能

1、使用Spring boot整合MyBatis,实现根据用户id查询用户信息功能。

1.1、在springboot数据库中,使用tb_user.sql创建数据表tb_user。

1.2、创建initialize工程

1.3、所需依赖如下,请将新建工程里没有的依赖补充进pom文件中,注意别放重了。

mysql mysql-connector-java 8.0.32 runtime

org.mybatis.spring.boot mybatis-spring-boot-starter 3.0.3

com.alibaba druid-spring-boot-3-starter 1.2.20

org.projectlombok lombok true org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test
1.4、创建实体类User

package com.my.yanli.entity;
import lombok.Data;
@Datapublic
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的值要和你的接口的全路径相同。



select * from tb_user where id=#{id}
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、如果成功启动,输入访问地址:

声明:文中观点不代表本站立场。本文传送门:http://eyangzhen.com/422192.html

(0)
联系我们
联系我们
分享本页
返回顶部