文章参考https://blog.csdn.net/Winter_chen001/article/details/77249029
1.接着上篇文章,需要引入mybatis的依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.4</version>
</dependency>

2.修改配置文件
因为我在本地测试时发现,连接报错,所以对url做了修改jdbc:mysql://127.0.0.1:3306/mytest?useSSL=false
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mytest?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
建表语句
CREATE DATABASE mytest;
USE mytest;
CREATE TABLE t_user(
id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
3.创建实体类,映射对象User
private Integer id;
private String name;
private String password;
private String phone;
---省略get,set方法---

4.创建User映射的操作UserMapper
package com.wy.news.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.wy.news.model.User;
@Mapper
public interface UserMapper {
@Insert("INSERT INTO T_USER(NAME, PASSWORD, PHONE) VALUES(#{name}, #{password}, #{phone})")
int insert(@Param("name") String name, @Param("password") String password, @Param("phone") String phone);
@Select("SELECT * FROM T_USER WHERE PHONE = #{phone}")
User findUserByPhone(@Param("phone") String phone);
}
5.创建controller
package com.wy.news.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wy.news.mapper.UserMapper;
import com.wy.news.model.User;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/findUser")
public User getUserNameByPhone() {
userMapper.insert("winterchen", "123456", "12345678910");
User u = userMapper.findUserByPhone("12345678910");
return u;
}
}
6.启动服务,访问http://localhost:8080/findUser

网友评论