简单的实现了增删改查,我自己也是刚学,算是初学者,如由错误欢迎指出谢谢!
注意点是本人踩过的坑,希望对其他初学者有所帮助。
项目结构图:
第一步 (新建项目)
创建springboot项目,在idea中创建很多情况都是连接失败的,我是在官网创建springboot项目网址进行创建的压缩包然后解压相应的文件夹中用idea打开,不想下载的可以用我在官网创建的:链接:https://pan.baidu.com/s/16EnNoyp3HjfCvru16HaXkg
提取码:1234
第二步(pom.xml文件)
配置pom.xml文件
<?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>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.shp</groupId>
<artifactId>student</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>power</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!--thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
第三步(创建数据库,数据表)
创建数据库,数据表(我的mysql数据库版本是5.5)(首次使用数据库需要连接,不会的自行百度)
create database student;
create table user
(
id int not null
primary key,
name varchar(25) null,
password varchar(25) null,
number varchar(25) null
);
在数据库中创建student表再准备一些数据:(可根据情况自行添加数据,注意id为主键不可重复,不能为空)
insert into user values(0,"张三","111","00");
insert into user values(1,"李四","112","01");
insert into user values(2,"王五","113","02");
第四步(application.propertise文件)
配置rssources文件夹下面的application.properties配置文件
数据库连接配置和mybatis配置
注意点:
如果mysql数据库版本是5.7及以上
spring.datasource.url= jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTC
需要修改为(5.7以上版本保护机制更好了,需要在url中添加相应参数才能连接成功):
spring.datasource.url= jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTCuseUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.url= jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTC
spring.datasource.username= root
spring.datasource.password= 自己mysql数据库的密码
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
mybatis.mapper-locations= classpath:mapper/*.xml
第五步(实体类User)
在com.shp.student包下新建entity包<存放实体类的包>,再在这个包下面新建一个User实体类。
Serializable是一个对象序列化的接口,一个类只有实现了Serializable接口,它的对象才是可序列化的。具体可看:Serializable详解
package com.shp.student.entity;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String name;
private String password;
private String number;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", number='" + number + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
第六步(dao层接口UserMapper)
在com.shp.student包下新建mapper包<dao层,用于映射数据库>,在这个包新建UserMapper接口(我的说法可能不太对,应该叫dao层接口)
注意点:
1.这里需要注意的是@Mapper这个注解必须要写,不然后面会报错Mapper注解的理解
2.注意理解这里方法的类型,因为dao层是跟数据库打交道,插入删除修改的都是一条一条的记录,数据库改动的是行数,所以应该使用int类型。
package com.shp.student.mapper;
import com.shp.student.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
List<User> findUserById(int id);
public List<User> ListUser();
public int insertUser(User user);
public int delete(int id);
public int Update(User user);
}
第七步(服务层接口UserService)
在com.shp.student包下新建service包<服务层>,在这个包下面新建一个UserService服务接口(不明白位置的可以看一下前面的项目结构)
package com.shp.student.service;
import com.shp.student.entity.User;
import java.util.List;
public interface UserService {
List<User> findUserById(int id);
public List<User> ListUser();
public int insertUser(User user);
public int delete(int id);
public int Update(User user);
}
第八步(服务层的服务类UserServiceImpl)
在com.shp.student.service包下新建一个impl包(存放服务类的包),在这个包下面新建UserServiceImpl服务类,需要继承UserService接口(实现接口中的所有方法),注入UserMapper接口,跟数据库映射
package com.shp.student.service.impl;
import com.shp.student.entity.User;
import com.shp.student.mapper.UserMapper;
import com.shp.student.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
public UserMapper userMapper;
public List<User> findUserById(int id) {
return userMapper.findUserById(id);
}
public int insertUser(User user) {
return userMapper.insertUser(user);
}
public List<User> ListUser(){
return userMapper.ListUser();
}
public int Update(User user){
return userMapper.Update(user);
}
public int delete(int id){
return userMapper.delete(id);
}
}
第九步(控制层UserController)
在com.shp.student包下新建一个controller包<控制层>,在这个包下面新建一个UserController类(用户控制器)
注意点:这里所有方法里面的id都是Integer类型,之前用的int一直报错,好像是因为json数据最好不要使用原始的数据类型,否则会报错,不过还是看自己版本支持的问题
package com.shp.student.controller;
import com.shp.student.entity.User;
import com.shp.student.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/crud", method = { RequestMethod.GET, RequestMethod.POST })
public class UserController {
@Autowired
private UserService userservice;
@RequestMapping("/ListUser")
@ResponseBody
public List<User> ListUser(){
return userservice.ListUser();
}
@RequestMapping("/ListUserById/{id}")
@ResponseBody
public List<User> ListUserById(@PathVariable("id") Integer id){
return userservice.findUserById(id);
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public String delete(@PathVariable("id") Integer id) {
List<User> user = userservice.findUserById(id);
int result = userservice.delete(id);
if (result >= 1) {
return "删除成功,删除的数据为:"+user;
} else {
return "删除失败,数据库中没有对应的id数据";
}
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public String update(User user) {
int result = userservice.Update(user);
if (result >= 1) {
return "修改成功,修改后的数据为"+user;
} else {
return "修改失败";
}
}
@RequestMapping(value = "/insert", method = RequestMethod.POST)
@ResponseBody
public String insert(User user) {
int result = userservice.insertUser(user);
if (result>=1){
return "插入数据成功";
}
else {
return "插入数据失败,请检查sql语句是否正确!";
}
}
}
第十步(映射文件UserMapper.xml)
在recourses文件夹下新建mapper文件夹,在这个包下面新建UserMapper.xml文件,然后配置这个.xml文件(与前面的UserMapper接口映射,以及数据库里面的增删改查语句)
注意点:
1.namespace:或后面跟的是绑定的dao层(我这里是写UserMapper)
2.UserMapper(dao层)中的方法方法名要跟UserMapper.xml中的id一样
3.UserMapper.xml中数据操作的时候需要使用#{},否则会报错
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD com.example.Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shp.student.mapper.UserMapper">
<resultMap id="result" type="com.shp.student.entity.User">
<result property="name" column="name" />
<result property="password" column="password" />
<result property="number" column="number"/>
</resultMap>
<select id="ListUser" resultMap="result">
SELECT * FROM user
</select>
<select id="findUserById" resultMap="result">
SELECT * FROM user where id=#{id}
</select>
<insert id="insertUser" parameterType="com.shp.student.entity.User"
keyProperty="id" useGeneratedKeys="true">
INSERT INTO user
(
id,name,password,number
)
VALUES (
#{id},
#{name, jdbcType=VARCHAR},
#{password, jdbcType=VARCHAR},
#{number}
)
</insert>
<delete id="delete" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="Update" parameterType="com.shp.student.entity.User">
update user set user.name=#{name},user.password=#{password},user.number=#{number} where user.id=#{id}
</update>
</mapper>
运行结果
程序运行成功之后在浏览器地址栏中输入(网络问题接不了图)
1.查询所有数据:http://localhost:8080/crud/ListUser
2.通过id(id=0)查询数据:http://localhost:8080/crud/ListUserById/0
3.通过id(id=1)删除数据:http://localhost:8080/crud/delete/1
4.通过id(id=2)更新数据(我这里仅仅修改了name):
http://localhost:8080/crud/update?id=2&name=吕布&password=112&number=02
5.向数据表中插入数据:
http://localhost:8080/crud/insert?id=3&name=貂蝉&password=113&number=03
转载请注明出处,支持原创,谢谢!