MyBatis快速入门——第五章、maven整合Mybatis&Servlet

MyBatis快速入门——第五章、maven整合Mybatis&Servlet,第1张

MyBatis快速入门——第五章、maven整合Mybatis&Servlet_tomcat 创建maven项目并引入mybatis、tomcat、servlet、

目录

        1、创建maven病引入mybatis的包

        2、添加JavaEE包

        3、配置tomcat

        4、引入servlet包

        5、配置mybatis-config.xml

        6、配置ProductMapper.xml文件  

        7、创建【com.item.model.Product.java】文件

        8、创建【com.item.mapper.ProductMapper.java】文件        

        9、创建【com.item.common】下的【JDBC】常用工具类        

        10、创建【com.item.dao】下的【ProductDAO.java】文件

        11、完成【servlet】访问层的【GetInfoServlet.java】接口文件        

        12、编辑视图文件【GetInfo.jsp】

        查询效果: 


1、创建maven病引入mybatis的包

 

 

引入【mybaits】【log4j】【mysql】的【maven】包


  org.mybatis
  mybatis
  3.5.1


  org.slf4j
  slf4j-log4j12
  1.7.10


  mysql
  mysql-connector-java
  5.1.6

如果不刷新maven则会报错。

加载完成

当前包数量【5】,缺少【servlet】的包 

2、添加JavaEE包

出现web文件夹

3、配置tomcat

 如果端口号8080有冲突自行更换即可。

4、引入servlet包

添加点测试代码,执行【tomcat】测试一下

package com.item.servlet;

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("/GetInfo")
public class GetInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("访问测试");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
访问接口:

为了 *** 作方便,将默认浏览器改为谷歌。

5、配置mybatis-config.xml

基础配置,这里用到的表是【product】表,sql语句看下方。




    
        
    
    
        
    
    
        
            
            
                
                
                
                
            
        
    
    
        
    

数据库名称【mytest】,编码类型【utf8】

DROP TABLE IF EXISTS `product`;
CREATE TABLE `product`  (
  `id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `createDate` datetime(0) NOT NULL,
  `modifyDate` datetime(0) NOT NULL,
  `productName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `productTitle` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `productPrice` decimal(10, 2) NOT NULL,
  `productCount` int(8) NOT NULL,
  `productType` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `productColor` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `productWeight` double NULL DEFAULT NULL,
  `productStatus` int(1) NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
 
INSERT INTO `product` VALUES ('b383581fd20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', '外星人M15', '高端外星人', 13499.00, 299, '外星人', 'black', 3300, 1);
INSERT INTO `product` VALUES ('b3839547d20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', 'ThinkBook', '联想', 4599.00, 159, '联想', 'gray', 2250, 1);
INSERT INTO `product` VALUES ('b383d49dd20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', '戴尔G15', '戴尔', 7499.00, 179, '戴尔', 'gray', 2270, 1);
INSERT INTO `product` VALUES ('b384180cd20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', 'RedmiBook Pro15', '小米', 4499.00, 699, '小米', 'black', 2500, 1);
INSERT INTO `product` VALUES ('b38457bed20211ec84b500e070bfdb54', '2022-05-12 22:49:18', '2022-05-12 22:49:18', '华硕a豆', '华硕', 3699.00, 799, '华硕', 'pink', 2100, 1);
INSERT INTO `product` VALUES ('f6715eb2d20111ec84b500e070bfdb54', '2022-05-12 22:44:01', '2022-05-12 22:44:01', '拯救者Y7700P', '2022新品拯救者', 7399.00, 199, '联想', 'gray', 2200, 1);
6、配置ProductMapper.xml文件 



    
    
        update product set productTitle = "${productTitle}" where id=#{id}
    
7、创建【com.item.model.Product.java】文件

写入一下编码,【Getter】【Setter】【toString()】

package com.item.model;

import java.math.BigDecimal;
import java.util.Date;

public class Product {
    private String id;
    private Date createDate;
    private Date modifyDate;
    private String productName;
    private String productTitle;
    private BigDecimal productPrice;
    private int productCount;
    private String productType;
    private String productColor;
    private double productWeight;
    private int productStatus;

    @Override
    public String toString() {
        return "Product{" +
                "id='" + id + '\'' +
                ", createDate=" + createDate +
                ", modifyDate=" + modifyDate +
                ", productName='" + productName + '\'' +
                ", productTitle='" + productTitle + '\'' +
                ", productPrice=" + productPrice +
                ", productCount=" + productCount +
                ", productType='" + productType + '\'' +
                ", productColor='" + productColor + '\'' +
                ", productWeight=" + productWeight +
                ", productStatus=" + productStatus +
                '}';
    }

    public String getId() {
        return id;
    }

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

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getProductTitle() {
        return productTitle;
    }

    public void setProductTitle(String productTitle) {
        this.productTitle = productTitle;
    }

    public BigDecimal getProductPrice() {
        return productPrice;
    }

    public void setProductPrice(BigDecimal productPrice) {
        this.productPrice = productPrice;
    }

    public int getProductCount() {
        return productCount;
    }

    public void setProductCount(int productCount) {
        this.productCount = productCount;
    }

    public String getProductType() {
        return productType;
    }

    public void setProductType(String productType) {
        this.productType = productType;
    }

    public String getProductColor() {
        return productColor;
    }

    public void setProductColor(String productColor) {
        this.productColor = productColor;
    }

    public double getProductWeight() {
        return productWeight;
    }

    public void setProductWeight(double productWeight) {
        this.productWeight = productWeight;
    }

    public int getProductStatus() {
        return productStatus;
    }

    public void setProductStatus(int productStatus) {
        this.productStatus = productStatus;
    }
}
8、创建【com.item.mapper.ProductMapper.java】文件

这里用的是【interface】来修饰类

package com.item.mapper;

import com.item.model.Product;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface ProductMapper {
    List GetInfo(@Param("productName") String productName,
                          @Param("productType") String productType,
                          @Param("productColor") String productColor);

    /**
     *
     * @param productTitle
     * @param id
     * @return
     */
    int UpdateById(@Param("productTitle") String productTitle,
                   @Param("id") String id);
}
9、创建【com.item.common】下的【JDBC】常用工具类

编码如下:

package com.item.common;

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.Reader;

public class JDBC {
    public static SqlSessionFactory GetConn() {
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            return new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
10、创建【com.item.dao】下的【ProductDAO.java】文件
package com.item.dao;

import com.item.common.JDBC;
import com.item.mapper.ProductMapper;
import com.item.model.Product;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class ProductDAO {
    /**
     * 各类查询
     * @param productName (商品名称)
     * @param productType (商品类型)
     * @param productColor (商品颜色)
     * @return
     */
    public static List GetInfo(String productName,
                                        String productType,
                                        String productColor) {
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        ProductMapper db = session.getMapper(ProductMapper.class);
        List list = db.GetInfo(productName, productType, productColor);
        session.close();
        return list;
    }

    /**
     * 修改
     * @param productTitle
     * @param id
     * @return
     */
    public static boolean UpdateById(String productTitle,String id){
        SqlSessionFactory factory = JDBC.GetConn();
        SqlSession session = factory.openSession();
        ProductMapper db = session.getMapper(ProductMapper.class);
        int rows = db.UpdateById(productTitle, id);
        session.commit();
        session.close();
        return rows>0;
    }

    public static void main(String[] args) {
        List list = GetInfo(null, null, "gray");
        System.out.println(list);
    }
}
11、完成【servlet】访问层的【GetInfoServlet.java】接口文件
package com.item.servlet;

import com.item.dao.ProductDAO;
import com.item.model.Product;

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;
import java.util.List;

@WebServlet("/GetInfo")
public class GetInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List list = ProductDAO.GetInfo(null, null, "gray");
        request.setAttribute("lists",list);
        request.getRequestDispatcher("GetInfo.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
可以添加【UpdateByIdServlet】接口
package com.item.servlet;

import com.item.dao.ProductDAO;

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("/UpdateById")
public class UpdateByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean isf = ProductDAO.UpdateById("联想ThinkPad系列", "b3839547d20211ec84b500e070bfdb54");
        response.sendRedirect("GetInfo");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
12、编辑视图文件【GetInfo.jsp】

<%@ page import="java.util.List" %>
<%@ page import="com.item.model.Product" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/5/15 0015
  Time: 10:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    mybatis与servlet整合
    


<% List lists = (List) request.getAttribute("lists");%>

    <% for (Product p : lists) {
    %>
    
    <%
        }%>
编号 创建时间 修改时间 产品名称 产品标题 产品价格 产品数量 产品厂家 产品颜色 产品重量 产品状态
<%=p.getId()%> <%=p.getCreateDate()%> <%=p.getModifyDate()%> <%=p.getProductName()%> <%=p.getProductTitle()%> <%=p.getProductPrice()%> <%=p.getProductCount()%> <%=p.getProductType()%> <%=p.getProductColor()%> <%=p.getProductWeight()%> <%=p.getProductStatus()%>
查询效果: 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/921906.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存