Mybatisはブランドデータの追加・削除・変更・照会を実現します

プロジェクトディレクトリを下図に示します。Mapper パッケージはデータベース上で動作する Mapper インターフェイス ファイルを格納するために使用されますが、この記事では SQL ステートメントをコメント形式で記述します。エンティティ クラス ファイルは pojo パッケージに保存されます。このパッケージには、Brand オブジェクトの関連フィールドと get、set、toString メソッドの定義が含まれています。サービス パッケージはサービス レイヤー ファイルを保存し、マッパー ファイルを呼び出してデータベースの追加、削除、変更、確認などの操作を実行します。servlet.java ファイルは Web パッケージに保存され、フロントエンド インターフェイスからデータを受信し、そのデータをカプセル化し、サービス層に送信します。ツール クラスは util パッケージに保存されており、ここでの SqlSessionFactoryUtils ファイルは、定義の繰り返しを避けるために SqlSessionFactory メソッドを抽出します。
ここに画像の説明を挿入
データベース情報
ここに画像の説明を挿入
ここに画像の説明を挿入

Brand Mapper.java は
、データベースを操作するためのインターフェイス関数を定義するために使用されます。インターフェイス関数は 2 つの方法 (アノテーションと XML ファイル) で実装できます。単純な SQL ステートメントはアノテーションを通じて実装でき、より複雑な関数はアノテーションを通じて実装する必要があります。実装用のxml。

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
ブランド オブジェクトの関連フィールドとメソッドを定義するブランド エンティティ クラス ファイル。

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
サービス層ファイル。sqlSessionFactory を定義して brandMapper のメソッドを呼び出し、データベース上で関連する操作を実現します。

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 は、
フロントエンド インターフェイスから渡されたパラメータを受け取り、Brand オブジェクトとしてカプセル化し、サービス層のメソッドを呼び出して追加操作を実装します。

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は、
フロントエンドインターフェースから渡されたidを受け取り、サービス層のdeleteByIdメソッドを呼び出してidを渡し、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 は、
サービス層の selectAll メソッドを呼び出してすべてのデータをクエリし、転送用の属性としてデータをカプセル化します。

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 は、
フロントエンド インターフェイスによって渡された ID を受け取り、サービス層の selectById メソッドを呼び出し、ID に基づいてクエリを実現し、クエリ結果を属性としてカプセル化し、それを update.jsp ページに転送します。

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 は、
フロントエンド インターフェイスから渡されたパラメータを受け取り、それらをブランド オブジェクトとしてカプセル化し、サービス層の update メソッドを呼び出して、更新操作を実装します。

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 は、異なるデータベース フィールド名とオブジェクト名によって引き起こされるマッチング失敗の問題を解決するために使用されます。

<?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
データベース接続およびその他の関連操作

<?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
ブランドインターフェイスを追加します

<%@ 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>

ここに画像の説明を挿入

brand.jsp は
すべてのブランドのインターフェイスを表示します

<%@ 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>

ここに画像の説明を挿入
Index.html の
初期インターフェイスには、選択されたすべてのハイパーリンクのみが含まれます

<!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 は
インターフェイスを更新し、ID に従ってクエリされたパラメーターを受け取り、それらをインターフェイスに表示します。これを変更し、変更したパラメータを更新します。

<%@ 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>

ここに画像の説明を挿入

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>

おすすめ

転載: blog.csdn.net/WuwuwuH_/article/details/131415526