创建项目



springboot anli springboot案例工程_java


第一步:在New Project下选择创建Spring工程,如下图所示


springboot anli springboot案例工程_spring boot_02


第二步:Project Metadata 设置项目坐标及项目名称


springboot anli springboot案例工程_springboot anli_03


第三步:Dependencies 初始化依赖,添加选中如下4个依赖。注意版本的选择


springboot anli springboot案例工程_java_04


第四步:完成配置


springboot anli springboot案例工程_spring boot_05


将java版本全部改为8


springboot anli springboot案例工程_springboot anli_06


springboot anli springboot案例工程_springboot anli_07


修改maven目录


springboot anli springboot案例工程_spring boot_08


这样,一个新的SpringBoot项目就创建完成了,项目结构如下:


springboot anli springboot案例工程_springboot anli_09


初始化配置

pom.xml配置

为了代码的简介,省略重复步骤,这里在依赖中添加了lombok。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>nj.zb.kb21</groupId>
    <artifactId>springbootexam</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootexam</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置完成之后,我们尝试运行程序,发现应用程序启动失败。

错误原因:Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

这是由于启动的时候加载数据库,我们还没有对数据库文件进行配置


springboot anli springboot案例工程_springboot anli_10


resources下配置application.properities

# 指定数据库名
spring.datasource.name=school
#数据库驱动类
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123123
spring.datasource.url=jdbc:mysql://192.168.153.134:3306/school


springboot anli springboot案例工程_java_11


配置完成之后再运行,数据库加载成功


springboot anli springboot案例工程_springboot anli_12


项目结构配置

SpringbootdemoApplication.java要求必须为一级目录,所以需要创建其他类时,必须在该目录下新建一个包。

在SpringbootdemoApplication.java同级目录下创建controller包,并新建一个index.html页面用于测试。添加mapping映射,代码如下。

package nj.zb.kb21.springbootdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="/hello")
public class TestController {

    @RequestMapping(value="/index")
    public String test(){
        return "index";
    }
}


springboot anli springboot案例工程_springboot anli_13


测试

默认跳转index页面

http://localhost:8080


springboot anli springboot案例工程_spring_14


通过映射进行访问

http://localhost:8080/hello/index


springboot anli springboot案例工程_spring boot_15


代码模板

数据库结构

数据库结构如下:

Student表


springboot anli springboot案例工程_spring boot_16


pojo层

作用:存放实体类,与数据库中的属性基本保持一致,一般包括getter、setter、toString方法(未使用插件lombok的情况下)。

package nj.zb.kb21.springbootdemo.pojo;

import lombok.*;

import java.sql.Time;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {
    private Integer Sid;
    private String Sname;
    private String Sage;
    private String Ssex;
}

dao层

也可以称为Mapper层,是数据库CRUD的接口,只有方法名,具体实现在mapper.xml文件中,对数据库进行数据持久化操作(把数据放到持久化的介质中,同时提供CRUD操作)

@Repository标注在Dao层接口上,作用是将接口的一个实现类交给Spring管理。Spring扫描到Dao接口的信息后,会将接口中的信息放到仓库,在其他地方可以直接调用。

package nj.zb.kb21.springbootdemo.dao;
import nj.zb.kb21.springbootdemo.pojo.Student;
import java.util.List;

@Repository
public interface StudentDao {
//    获取所有学生信息
    List<Student> getAllStudent();
//    通过id查询学生信息
    Student getStudentById(Integer id);

//    新增学生
    Integer saveStudent(Student student);

//    根据id删除学生
    Integer delStudent(Integer id);

//    根据学生id修改学生信息
    Integer modStudent(Student student,Integer id);
}


springboot anli springboot案例工程_spring boot_17


但是需要注意的是,标记@Repository注解之后,需要在SpringbootdemoApplication启动项中添加MapperScan,指向dao包。这样在使用时会扫描到@Repository注解,并放到仓库中。

package nj.zb.kb21.springbootdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("nj.zb.kb21.springbootdemo.dao")
public class SpringbootdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}


springboot anli springboot案例工程_java_18


mapper层(resoueces资源目录)

<!-- 第一步:添加头文件 -->
<?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="nj.zb.kb21.springbootdemo.dao.StudentDao">

    <!-- 获取所有学生信息 -->
    <select id="getAllStudent" resultType="nj.zb.kb21.springbootdemo.pojo.Student">
        select Sid,Sname,Sage,Ssex from student;
    </select>

    <!-- 通过学生id获取所有学生信息 -->
    <select id="getStudentById" resultType="nj.zb.kb21.springbootdemo.pojo.Student">
        select Sid,Sname,Sage,Ssex from student where Sid=#{id};
    </select>

</mapper>

application.properities

指定resources目录下的mapper路径

# 指定数据库名
spring.datasource.name=school
#数据库驱动类
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123123
spring.datasource.url=jdbc:mysql://192.168.153.134:3306/school


# StudentDao.xml也可以用*.xml
mybatis.mapper-locations=classpath:/mapper/StudentDao.xml

Service层

作用:Service层存放业务逻辑处理,有一些关于数据库处理的操作,但是不是直接和数据库打交道,有接口,也有接口的实现方法,在impl实现接口类中需要导入mapper类,mapper层是直接与数据库进行操作的

StudentService接口:

package nj.zb.kb21.springbootdemo.Server;
import nj.zb.kb21.springbootdemo.pojo.Student;
import java.util.List;

public interface StudentService {
    public List<Student> showAllStudents();
    public Student showStudent(Integer id);
}

StudentServiceInfo实现类:

package nj.zb.kb21.springbootdemo.Server;
import nj.zb.kb21.springbootdemo.dao.StudentDao;
import nj.zb.kb21.springbootdemo.pojo.Student;
import java.util.List;

@Service
@Transactional
public class StudentServiceInfo implements StudentService{

    @Autowired
    private StudentDao studentDao;
    
    @Override
    public List<Student> showAllStudents() {
        return studentDao.getAllStudent();
    }

    @Override
    public Student showStudent(Integer id) {
        return studentDao.getStudentById(id);
    }
}

Controller层

控制层,控制业务逻辑service,控制请求和响应,负责前后端交互controller层主要调用Service层里面的接口控制具体的业务流程,控制的配置也要在配置文件中进行。

package nj.zb.kb21.springbootdemo.controller;

import nj.zb.kb21.springbootdemo.Server.StudentService;
import nj.zb.kb21.springbootdemo.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;

@Controller
@RequestMapping(value="/stu")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/allstu")
    @ResponseBody
    public List<Student> showAllStudents2(){
        List<Student> students = studentService.showAllStudents();
        return students;
    }

    @GetMapping("/stuid")
    @ResponseBody
    public Student showStudents2(Integer id){
        Student student = studentService.showStudent(id);
        return student;
    }
}

页面访问

localhost:8080/stu/allstu


springboot anli springboot案例工程_spring_19


localhost:8080/stu/stuid?id=2


springboot anli springboot案例工程_Powered by 金山文档_20