1.使用navicat创建一个mysql的连接
注:密码使用root(一开始配置mysql的时候你使用的密码)
2.创建数据库以及库里面的数据
创建对象
3.定义entity实体类包,里面定义实体类
类里面的属性与表里面属性一致
编写实体类:
package com.example.databaseconnect.entity;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
(可使用Alt+Insert快速编写)(我将快捷键更改为了Alt+0)
UserMapper接口类:
package com.example.databaseconnect.mapper;
import com.example.databaseconnect.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select *from user")//数据库语句自动查找数据库
public List<User> find();
}
UserController类:
package com.example.databaseconnect.controller;
import com.example.databaseconnect.entity.User;
import com.example.databaseconnect.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
//接口不可以new,方法进行声明
@Autowired //自动注入Usermapper
private UserMapper userMapper;
@GetMapping("/user")
public String query(){
List<User> list=userMapper.find();
System.out.println(list);
return "查询用户";
}
}
4.运行
若修改query方法的返回值为List,在前端页面中会自动返回Json
public List query(){
List<User> list=userMapper.find();
return list;
}