Spring Boot应用连接数据库MySQL、及一个简单的demo

一、修改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=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=
spring.datasource.max-wait=
spring.datasource.min-idle=
spring.datasource.initial-size=
server.port=
server.servlet.session.timeout=
server.tomcat.uri-encoding=UTF-

三、分层业务逻辑

Spring Boot应用连接数据库MySQL、及一个简单的demo

  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,但是代码结构大部分如此

上一篇:yum卸载失败Error in PREUN scriptlet in rpm package postgresql-server


下一篇:tomcat 控制台乱码问题