Springboot集成Mybatis创建接口
Springboot创建接口
主程序【SpringBootApplication.java】
package com.example.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
一、entity文件夹下存放数据库内对应的数据表文件
在与主程序同级目录下建一个entity文件,用于存放和数据库内数据表对应的文件目录
User.java
package com.example.springboot_vue.entity;
import lombok.Data;
@Data
public class User {
private Integer id;
private String username;
private String password;
private String nickname;
private String email;
private String phone;
private String address;
}
Word.java
package com.example.springboot_vue.entity;
import lombok.Data;
@Data
public class Word {
private Integer id;
private String word;
private String mean;
}
二、mapper文件夹下存放与entity中类文件对应的接口
在与主程序同级目录下建一个mapper文件,用于存放与entity中类文件对应的接口
UserMapper.java
package com.example.springboot_vue.entity;
import com.qingge.springboot.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 sys_user")
List<User> findAll();
}
WordMapper.java
package com.example.springboot_vue.mapper;
import com.example.springboot_vue.entity.Word;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface WordMapper {
@Select("SELECT * from sys_word")
List<Word> findAll();
}
三、controller层
controller控制层
UserController.java
package com.example.springboot_vue.mapper;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.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 {
@Autowired
private UserMapper userMapper;
@GetMapping("/")
public List<User> index() {
List<User> all = userMapper.findAll();
return all;
}
}
WordController.java
package com.example.springboot_vue.controller;
import com.example.springboot_vue.entity.Word;
import com.example.springboot_vue.mapper.WordMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/word")
public class WordController {
@Resource
WordMapper wordMapper;
@GetMapping
public List<Word> getWord(){
return wordMapper.findAll();
}
}
四、启动输出
启动项目
浏览器输出