Mybatis实现品牌数据的增删改查

news/2024/11/25 5:24:28/

项目目录如下图所示。Mapper包用于存储对数据库进行操作的Mapper接口文件,本文中通过注释的方式对sql语句进行编写。pojo包中存放实体类文件,文件中包含Brand对象相关字段的定义以及get、set、toString方法。service包中存放service层文件,调用mapper文件对数据库进行增删改查等操作。web包中存放servlet.java文件,接收来自前端界面的数据,将数据封装,传入service层中。util包中存放工具类,此处的SqlSessionFactoryUtils文件抽取了SqlSessionFactory方法,避免了其重复定义。
在这里插入图片描述
数据库信息
在这里插入图片描述
在这里插入图片描述

Brand Mapper.java
用于定义操纵数据库的接口函数,可以通过两种方式对接口函数进行实现(注解以及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
Brand实体类文件,定义了Brand对象的相关字段及方法。

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;}@Overridepublic String toString() {return "Brand{" +"id=" + id +", brand_name='" + brandName + '\'' +", company_name='" + companyName + '\'' +", ordered=" + ordered +", description='" + description + '\'' +", status=" + status +'}';}
}

BrandService.java
Service层文件,通过定义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对象,通过调用service层的方法实现添加操作。

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();@Overrideprotected 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);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}

DeleteByIdServlet.java
接收前端界面传递的id,调用service层的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();@Overrideprotected 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);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}

SelectAllServlet.java
调用service层selectAll方法,查询所有数据,并将数据封装为Attribute进行转发。

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();@Overrideprotected 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);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}

SelectByIdServlet.java
接收前端界面传递的id,调用service层selectById方法,实现根据id查询,并将查询结果封装为attribute,转发到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();@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 接收idString id = request.getParameter("id");// 调用service查询Brand brand = brandService.selectById(Integer.parseInt(id));request.setAttribute("brand", brand);request.getRequestDispatcher("/update.jsp").forward(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}

UpdateServlet.java
接收前端界面传递来的参数,将其封装为brand对象,调用service层的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();@Overrideprotected 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);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}

BrandMapper.xml
resultMap用于解决数据库字段名和对象名称不同而导致的匹配失败问题

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//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 configurationPUBLIC "-//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
初始界面,仅包含select all超链接

<!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>

http://www.ppmy.cn/news/629085.html

相关文章

学习Kotlin~函数

有名函数 函数参数 不打算传入值参&#xff0c;可以预先给参数指定默认值 //如果不打算传入值参&#xff0c;可以预先给参数指定默认值private fun fix(name: String, age: Int 2) {println(name age);}//调用的时候fix("hhhh");fix("hasee", 30);有名的…

《计算机系统与网络安全》 第六章 密钥管理

&#x1f337;&#x1f341; 博主 libin9iOak带您 Go to New World.✨&#x1f341; &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33…

天狼星-冬季大三角最亮的一颗星

冬季夜晚星空主要景象。由大犬座的天狼星、小犬座的南河三及猎户座的参宿四所形成的三角形。这三颗星所形成的三角形位于天球的赤道上&#xff0c;所以世界各地都可以看见。 天狼星 它是夜空中最亮的恒星&#xff0c;其视星等为-1.47&#xff0c;几乎为第二亮恒星老人星的两倍…

球半足球分析,竞彩瑞典超:天狼星VS哥德堡 06月28日

竞彩瑞典超&#xff1a;天狼星VS哥德堡 06月28日 01:00 周一 003 主队天狼星本赛季以4胜2平的战绩在联赛中排名第11&#xff0c;期间进12球失17球。球队方式能力较差&#xff0c;主场作战表现还不错&#xff0c;过去4场有3场取胜。上一场天狼星 主场3:3踢平已经连续三场没有…

(Note)卫星接收天线的朝向

我国很多大楼顶部都装有“铁锅”状卫星接收天线&#xff0c;卫星接收天线大多需要朝向南方或偏南方。 Reason&#xff1a; 同步电视卫星等所有的通讯卫星都位于地球赤道的上空&#xff0c;只是经度位置不同。 而我国在北半球&#xff0c;因此&#xff0c;卫星接收天线为了指向…

最新天狼星网络验证系统源码+功能非常强大

正文: 这源码之前发过很多次&#xff0c;但是多多少少都有些问题&#xff0c;最近花了点时间给大家找到了个可以用的&#xff0c;程序是PHP开发的&#xff0c;这程序如何搭建想必大家都知道&#xff0c;用过这网络验证程序的都还觉得不错。 天狼星网络验证:一个可以添加远程分…

最新天狼星网络验证完整源码+功能强大/UI也不错

正文: 最新天狼星网络验证完整源码功能强大/UI也不错&#xff0c;程序是通过PHP开发的&#xff0c;功能方面真心没得说&#xff0c;程序的搭建很简单&#xff0c;就正常搭建就行了&#xff0c;用过这网络验证程序的都还觉得不错。 天狼星网络验证:一个可以添加远程分享弹窗的…