一、修改pom.xml文件
在项目的pom.xml文件上增加如下代码,添加依赖文件。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二、设置全局配置文件
在src/main/resources/application.properties中设置数据源和jpa配置。标红处是自己建的库
spring.datasource.url=jdbc:mysql://123.207.46.41:3306/gwfdemo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=159753
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=1000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8080
server.servlet.session.timeout=10
server.tomcat.uri-encoding=UTF-8
三、分层业务逻辑
POJO:domain层
package com.example.demo.Domain;
public class Student {
private Integer id;
private String name;
private Integer age;
private String grade;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
service层:
package com.example.demo.Service;
import com.example.demo.Dao.StudentDao;
import com.example.demo.Domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired StudentDao studentDao;
public List<Student> getAll(){
return studentDao.getAll();
}
}
dao层:
package com.example.demo.Dao;
import com.example.demo.Domain.Student;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface StudentDao {
@Select("select * from student")
public List<Student> getAll();
}
Controller层:
package com.example.demo.controller;
import com.example.demo.Domain.Student;
import com.example.demo.Service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class StudentController {
@Autowired
StudentService studentService;
@ResponseBody
@RequestMapping("/student")
public List<Student> getStudents(){
return studentService.getAll();
}
}
然后运行,即可查出数据,很简单的一个demo,但是代码结构大部分如此