Home > Java > javaTutorial > How to implement basic addition, deletion, modification and query in SpringBoot in Java

How to implement basic addition, deletion, modification and query in SpringBoot in Java

WBOY
Release: 2023-05-20 10:07:41
forward
1459 people have browsed it

How to implement basic addition, deletion, modification and query in SpringBoot in Java

As shown in the above figure, we have 7 more important modules in the idea that need to be built

(1) Controller package: If you learn Friends who have experienced or know something about SpringMVC must know that the controller is the control layer, which is equivalent to the place where we receive browser information and respond to send relevant information. Specifically, it also combines computer network related knowledge to understand how to use it in the browser. Receive information, and how to respond to the information. We implement relevant data manipulation under the controller control layer (here, I would like to express my special thanks to my senior brother during my graduate career for teaching me about Web programming for a long time, which has benefited me a lot. I hope everyone can use the relevant time. , check more information and related videos to learn);
(2) entity package: our entity classes are stored here, which is exactly the same as simply learning to create classes in java, there is no difference;
(3) mapper package: SpringMVC It is called the persistence layer in the DAO layer (DAO layer (data access object)). Here you can directly operate the database and is generally used in conjunction with the fifth package mapping package;
(4) service package: called in SpringMVC Business logic layer, so the classes stored here are all related to processing related business logic;
(5) mapping package: placed under resources as classpath, stored mybatis file, because the current SpringBoot is very integrated, many configurations The files can be put together, and even friends who don't have much mybatis foundation can learn it. The reason why the mapper package and the mapping package are used together is because they form a mapping relationship, and they are used in combination to access our database files;
(6) application.yml: As a global default configuration file, it applies to the entire Project, to integrate so much of our configuration information, this configuration file is definitely indispensable (it is best to use the yaml language to write the configuration file here, because the writing is relatively simple and clear);
(7) application-dev.yml : This is considered a configuration file for a specific environment, and it should be combined with our actual project. Because the project itself is not only a development environment, but also a series of environments such as testing and production. When we do development, we use the development environment to configure application-dev.yml. When we do testing, we use the testing environment to configure application-test.yml. When we do production, we use the production environment to configure application-pro. yml. At present, we are only talking about the development environment, so we only use one configuration file application-dev.yml. A specific environment configuration information will override the default configuration of application.yml when used, so there is no need to worry about the conflicts between the statements in the default configuration and the statements in the environment configuration.

(1) Program entrance

Every java program has a program entrance. DemoApplication itself already exists when we initialize SpringBoot. We do not need to do too much configuration here.

How to implement basic addition, deletion, modification and query in SpringBoot in Java

package com.example.demo;

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

@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Copy after login

●@SpringBootApplication annotation: It is used to indicate that this is the startup item class of a springboot project. The purpose is to enable automatic configuration (in fact, it is inherited from the Configuration configuration class. In-depth understanding requires everyone to analyze the principles of SpringBoot)
●@MapperScan ("com.example.demo.mapper") is to scan our mapper files and effectively access related database file URL mapping (this annotation is very useful !)

(2) Create database file

How to implement basic addition, deletion, modification and query in SpringBoot in Java

How to implement basic addition, deletion, modification and query in SpringBoot in Java

##●The corresponding sql creation table statement is as follows:

CREATE TABLE `water` (
  `id` int NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `salary` double(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8_unicode_ci;
Copy after login

(3) Create a User entity class

How to implement basic addition, deletion, modification and query in SpringBoot in Java

package com.example.demo.entity;

/**
 * @description:    实体类
 * @author: Fish_Vast
 * @Date: 2021/8/25
 * @version: 1.0
 */
public class User {
    private String name;
    private Integer id;
    private Double salary;

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", salary=" + salary +
                '}';
    }
}
Copy after login

●Everyone must be familiar with this. This is a class that can be written based on pure Java. Create Three private properties, a null parameter constructor, corresponding get and set methods, and an overridden toString() method. The point worth noting here is that when declaring properties, it is best to use a wrapper class for declaration.

●In the reading and input related to mybatis in Java, why try to use packaging classes instead of basic data types?
① If no value is assigned to a field in MySQL, the default value is null. When you check it from the database, it is also null. If the field is of int type in the corresponding Java code, null cannot correspond to the int type, because int represents the basic The data type can only be basic numbers.
②The attributes of the entity class can be assigned a value or not. When you do not assign a value to it, it has a default value. For example, the default value of int is 0. But actively setting the value to 0 and it defaulting to 0 are two different concepts. For example, the score of a class: 0 means that a certain student has a score of 0, and null means that the student has no score in the exam. These are two different concepts.

(4)建立UserMapper接口

How to implement basic addition, deletion, modification and query in SpringBoot in Java

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    //1.通过id查询用户信息
    User getUser(int id);
    //2.通过id删除用户信息
    int delete(int id);
    //3.更改用户信息
    int update(User user);
    //4.插入用户信息
    int save(User user);
    //5.查询所有用户信息
    List<User> selectAll();
}
Copy after login

●@Repository,注解它本身的作用便是标注数据访问组件,作为DAO对象,它将 DAO 导入 IoC 容器,并使未经检查的异常有资格转换为 Spring DataAccessException。通过这个注解能够报出更多发现不了的错误,更有利于对项目的维护和开发。其实@Repository不在接口上进行注明,我们的程序照样可以运行,因为在我们使用@MapperScan的时候,我们已经将我们的接口交给框架中的代理类,所以即便是我们不写,程序不会报错,只是我们在Service层写明接口的时候,IDEA会给出红色的波浪线。可以这样理解,标注@Repository是为了告诉编译器我将接口注入到了IoC容器了,你不要报错啦~
●相应地,写出增删查改和查询全部信息的五个方法。

(5)配置UserMapper.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.example.demo.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.entity.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="salary" jdbcType="DOUBLE" property="salary" />
    </resultMap>
    <!--查询用户信息-->
    <select id="getUser" resultType="com.example.demo.entity.User">
        select * from water where id = #{id}
    </select>
    <!--删除用户信息-->
    <delete id="delete" parameterType="int">
        delete from water where id=#{id}
    </delete>
    <!--返回所有用户信息-->
    <select id="selectAll"  resultType="com.example.demo.entity.User">
        select * from water
    </select>

    <!--增加用户信息-->
    <insert id="save" parameterType="com.example.demo.entity.User" >
        insert into water
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="name != null" >
                name,
            </if>
            <if test="salary != null" >
                salary,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null" >
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="salary != null" >
                #{salary,jdbcType=DOUBLE},
            </if>
        </trim>
    </insert>

    <!--根据id更改用户信息-->
    <update id="update" parameterType="com.example.demo.entity.User">
        update water
        <set >
            <if test="name != null" >
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="salary != null" >
                salary = #{salary,jdbcType=DOUBLE},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>
Copy after login

●mapper namespace用于绑定mapper接口的,当你的namespace绑定接口后,你可以不用写接口实现类,mybatis会通过该绑定自动帮你找到对应要执行的SQL语句(通过mapper方法名进行绑定);
●resultMap 定义了一个id为BaseResultMap的标识,type代表使用哪种类作为我们所要映射的类;