Mybatis realizes the addition, deletion, modification and query of brand data

The project directory is shown in the figure below. The Mapper package is used to store the Mapper interface files that operate on the database. In this article, the sql statement is written in the form of comments. The entity class file is stored in the pojo package, which contains the definition of the relevant fields of the Brand object and the get, set, and toString methods. The service package stores the service layer files, and calls the mapper file to perform operations such as adding, deleting, modifying, and checking the database. The servlet.java file is stored in the web package, which receives data from the front-end interface, encapsulates the data, and transmits it to the service layer. The tool class is stored in the util package. The SqlSessionFactoryUtils file here extracts the SqlSessionFactory method to avoid its repeated definition.
insert image description here
database information
insert image description here
insert image description here

Brand Mapper.java
is used to define the interface function for manipulating the database. The interface function can be implemented in two ways (annotation and xml file). Simple sql statements can be implemented through annotations, and more complex functions need to be implemented through xml for implementation.

package com.wu.mapper;
import com.wu.pojo.Brand;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface BrandMapper {
    
    

    /**
     * 查询所有
     *
     * @return
     */
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    /**
     * 添加品牌
     *
     * @param brand
     */
    @Insert("insert into tb_brand values (null, #{brandName}, #{companyName}, #{ordered}, #{description}, #{status})")
    void addBrand(Brand brand);

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Select("select * from tb_brand where id = #{id}")
    @ResultMap("brandResultMap")
    Brand selectById(int id);

    /**
     * 更新品牌信息
     *
     * @param brand
     */
    @Update("update tb_brand set brand_name = #{brandName}, company_name = #{companyName}, " +
            "ordered = #{ordered}, description =#{description}, status = #{status} " +
            "where id = #{id}")
    void updateBrand(Brand brand);

    /**
     * 删除品牌
     *
     * @param id
     */
    @Delete("delete from tb_brand where id = #{id}")
    void deleteById(int id);
}

Brand.java
Brand entity class file, which defines the related fields and methods of the Brand object.

package com.wu.pojo;

public class Brand  {
    
    
    private Integer id;
    private String brandName;
    private String companyName;
    private Integer ordered;
    private String description;
    private Integer status;

    public Integer getId() {
    
    
        return id;
    }

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

    public String getBrandName() {
    
    
        return brandName;
    }

    public void setBrandName(String brand_name) {
    
    
        this.brandName = brand_name;
    }

    public String getCompanyName() {
    
    
        return companyName;
    }

    public void setCompanyName(String company_name) {
    
    
        this.companyName = company_name;
    }

    public Integer getOrdered() {
    
    
        return ordered;
    }

    public void setOrdered(int ordered) {
    
    
        this.ordered = ordered;
    }

    public String getDescription() {
    
    
        return description;
    }

    public void setDescription(String description) {
    
    
        this.description = description;
    }

    public Integer getStatus() {
    
    
        return status;
    }

    public void setStatus(int status) {
    
    
        this.status = status;
    }

    @Override
    public String toString() {
    
    
        return "Brand{" +
                "id=" + id +
                ", brand_name='" + brandName + '\'' +
                ", company_name='" + companyName + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}

BrandService.java
Service layer file, by defining sqlSessionFactory to call the method in brandMapper, so as to realize the related operations on the database.

package com.wu.service;
import com.wu.mapper.BrandMapper;
import com.wu.pojo.Brand;
import com.wu.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;

public class BrandService {
    
    

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 查询所有成员
     * @return
     */
    public List<Brand> selectAll() {
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//true事务的自动提交
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = brandMapper.selectAll();
        sqlSession.close();
        return brands;
    }

    /**
     * 添加成员
     */
    public void addBrand(Brand brand){
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.addBrand(brand);
        sqlSession.close();
    }

    /**
     * 根据id查询
     * @return
     */
    public Brand selectById(int id) {
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        Brand brand = brandMapper.selectById(id);
        sqlSession.close();
        return brand;
    }

    /**
     * 修改品牌信息
     * @param brand
     */
    public void update(Brand brand){
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.updateBrand(brand);
        sqlSession.close();
    }

    /**
     * 删除品牌
     * @param id
     */
    public void deleteById(int id){
    
    
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
        brandMapper.deleteById(id);
        sqlSession.close();
    }
}

SqlSessionFactoryUtils.java

package com.wu.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    
    

    private static SqlSessionFactory sqlSessionFactory;

    static {
    
    
        // 静态代码块会随着类的加载而自动执行,且只执行一次
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
    
    
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSessionFactory getSqlSessionFactory() {
    
    
        return sqlSessionFactory;
    }
}

AddServlet.java
receives the parameters passed by the front-end interface, encapsulates them as Brand objects, and implements the adding operation by calling the method of the service layer.

package com.wu.web;
import com.wu.pojo.Brand;
import com.wu.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet( "/addServlet")
public class AddServlet extends HttpServlet {
    
    

    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        // 处理POST请求的乱码问题
        request.setCharacterEncoding("utf-8");

        // 接收表单提交的数据
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        // 封装为Brand对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        // 调用service完成添加
        brandService.addBrand(brand);

        request.getRequestDispatcher("/selectAllServlet").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

DeleteByIdServlet.java
receives the id passed by the front-end interface, calls the deleteById method of the service layer, passes in the id, and realizes the operation of deleting according to the id.

package com.wu.web;
import com.wu.service.BrandService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
    
    

    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String id = request.getParameter("id");
        brandService.deleteById(Integer.parseInt(id));
        request.getRequestDispatcher("/selectAllServlet").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

SelectAllServlet.java
invokes the selectAll method of the service layer to query all data, and encapsulates the data as Attribute for forwarding.

package com.wu.web;
import com.wu.pojo.Brand;
import com.wu.service.BrandService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    
    

    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        //1. 调用BrandService完成查询
        List<Brand> brands = brandService.selectAll();
        //2. 将brands存入request域中
        request.setAttribute("brands", brands);
        //3. 转发到brand.jsp页面
        request.getRequestDispatcher("/brand.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

SelectByIdServlet.java
receives the id passed by the front-end interface, calls the selectById method of the service layer, realizes the query based on the id, encapsulates the query result as an attribute, and forwards it to the update.jsp page.

package com.wu.web;
import com.wu.pojo.Brand;
import com.wu.service.BrandService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {
    
    

    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        // 接收id
        String id = request.getParameter("id");
        // 调用service查询
        Brand brand = brandService.selectById(Integer.parseInt(id));
        request.setAttribute("brand", brand);
        request.getRequestDispatcher("/update.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

UpdateServlet.java
receives the parameters passed by the front-end interface, encapsulates them as brand objects, calls the update method of the service layer, and implements the update operation.

package com.wu.web;
import com.wu.pojo.Brand;
import com.wu.service.BrandService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
    
    

    private BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        request.setCharacterEncoding("utf-8");//解决乱码问题

        String id = request.getParameter("id");
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        Brand brand = new Brand();
        brand.setId(Integer.parseInt(id));
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        brandService.update(brand);

        request.getRequestDispatcher("/selectAllServlet").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request, response);
    }
}

BrandMapper.xml
resultMap is used to solve the problem of matching failure caused by different database field names and object names

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
    namespace:名称空间
-->
<mapper namespace="com.wu.mapper.BrandMapper">
    <resultMap id="brandResultMap" type="brand">
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>
</mapper>

Mybatis-config.xml
database connection and other related operations

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--包扫描-->
    <typeAliases>
        <package name="com.wu.pojo"/>  <!--包扫描 给pojo下的实体类起了别名,默认为类名,不区分大小写-->
    </typeAliases>
    <!--
    environments:配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment
    -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false&amp;userServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql的映射文件-->
<!--        <mapper resource="com/wu/mapper/UserMapper.xml"/>-->
        
        <!--Mapper代理方式-->
        <package name="com.wu.mapper"/>
    </mappers>
</configuration>

addBrand.jsp
add brand interface

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>addBrand</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="/jsp-demo/addServlet" method="post"><br>
    品牌名称:<input name="brandName"><br>
    企业名称:<input name="companyName"><br>
    排序:<input name="ordered"><br>
    描述信息:<textarea rows="5" cols="20" name="description"></textarea><br>
    状态:<input type="radio" name="status" value="0">禁用
    <input type="radio" name="status" value="1">启用<br>
    <input type="submit" value="提交">
    <input type="reset" value="重置">
</form>
</body>
</html>

insert image description here

brand.jsp
displays all brand interfaces

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>brand</title><br>
</head>
<body>
<input type="button" value="新增" id="add">
<table border="1" cellpadding="0" width="800">
    <tr>
        <th>序号</th>
        <th>品牌名称</th>
        <th>企业名称</th>
        <th>排序</th>
        <th>品牌介绍</th>
        <th>状态</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${brands}" var="brand" varStatus="status">
        <tr align="center">
            <td>${
    
    status.count}</td>
            <td>${
    
    brand.brandName}</td>
            <td>${
    
    brand.companyName}</td>
            <td>${
    
    brand.ordered}</td>
            <td>${
    
    brand.description}</td>
            <c:if test="${brand.status == 1}">
                <td>启用</td>
            </c:if>
            <c:if test="${brand.status != 1}">
                <td>禁用</td>
            </c:if>
            <td><a href="/jsp-demo/selectByIdServlet?id=${brand.id}">修改</a>
                <a href="/jsp-demo/deleteByIdServlet?id=${brand.id}">删除</a></td>
        </tr>
    </c:forEach>
</table>

<script>
    document.getElementById('add').onclick = function (){
    
    
        location.href = "/jsp-demo/addBrand.jsp"
    }
</script>
</body>
</html>

insert image description here
index.html
initial interface, only contains select all hyperlinks

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="/jsp-demo/selectAllServlet">select all</a>
</body>
</html>

update.jsp
updates the interface, receives the parameters queried according to the id, and displays them on the interface. Modify it, and update the modified parameters.

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>update</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="/jsp-demo/updateServlet" method="post"><br>
    <%--隐藏域 提交id--%>
    <input type="hidden" name="id" value="${brand.id}">
    品牌名称:<input name="brandName" value="${brand.brandName}"><br>
    企业名称:<input name="companyName" value="${brand.companyName}"><br>
    排序:<input name="ordered" value="${brand.ordered}"><br>
    描述信息:<textarea rows="5" cols="20" name="description">${
    
    brand.description}</textarea><br>
    状态:
    <c:if test="${brand.status == 1}">
        <input type="radio" name="status" value="0">禁用
        <input type="radio" name="status" value="1" checked>启用<br>
    </c:if>
    <c:if test="${brand.status == 0}">
        <input type="radio" name="status" value="0" checked>禁用
        <input type="radio" name="status" value="1">启用<br>
    </c:if>

    <input type="submit" value="提交">
    <input type="reset" value="重置">
</form>
</body>
</html>

insert image description here

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wu</groupId>
  <artifactId>jsp-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>jsp-demo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
  </dependencies>

  <build>
      <plugins>
        <plugin>
          <groupId>org.apache.tomcat.maven</groupId>
          <artifactId>tomcat7-maven-plugin</artifactId>
          <version>2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
  </build>
</project>

Guess you like

Origin blog.csdn.net/WuwuwuH_/article/details/131415526