1. 创建springboot新项目
勾选mybatis
2. 配置application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/momo?characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
server:
port: 8000
准备mysql数据
image.png
3. 创建Img实体
package com.unik.entity;
public class Img {
private Integer id;
private String name;
private String url;
public Img(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "Img{" +
"id=" + id +
", name='" + name + '\'' +
", url='" + url + '\'' +
'}';
}
}
4. 创建ImgMapper
package com.unik.mapper;
import com.unik.entity.Img;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ImgMapper {
List<Img> findAll();
}
5. 创建ImgMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.unik.mapper.ImgMapper">
<select id="findAll" resultType="com.unik.entity.Img">
select * from bian
</select>
</mapper>
6. 创建ImgService
package com.unik.service;
import com.unik.entity.Img;
import com.unik.mapper.ImgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ImgService {
@Autowired
private ImgMapper imgMapper;
public List<Img> findAll(){
return imgMapper.findAll();
}
}
7. 创建ImgController
package com.unik.controller;
import com.unik.entity.Img;
import com.unik.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ImgController {
@Autowired
private ImgService imgService;
@RequestMapping(value = "/img")
public List<Img> listImg(){
return imgService.findAll();
}
}
8. 入口文件进行mapper扫描
package com.unik;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.unik.mapper")
@SpringBootApplication
public class LinkageApplication {
public static void main(String[] args) {
SpringApplication.run(LinkageApplication.class, args);
}
}
启动项目,访问localhost:8000/img
image.png