Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Basic CRUD Operations in Java Web

Tech May 17 2

Implementation of basic CRUD operations in Java Web

Overview

After completing Java Web studies, its time to create a simple example of CRUD operations.

  1. What is pandas?

Example: Pandas is a tool based on NumPy, created to solve data analysis tasks.

  1. Usage Steps

1. Mapper Layer

package org.example.mapper;

import org.apache.ibatis.annotations.*;
import org.example.pojo.Brand;

import java.util.List;

public interface BrandMapper {

    /**
     * Retrieve all
     * @return
     */
    @Select("select * from tb_brand")
    List<Brand> selectAll();

    /**
     * Add data
     * @param brand
     */
    @Insert("insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    /**
     * Batch delete
     * @param ids
     */
    void deleteByIds(@Param("ids") int[] ids);

    /**
     * Single delete
     */
    @Delete("delete from tb_brand where id = #{id}")
    void deleteById(int id);

    /**
     * Update
     * @param brand
     */
    @Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}")
    void update(Brand brand);

    /**
     * Paginate query
     * @param begin
     * @param size
     * @return
     */
    @Select("select * from tb_brand limit #{begin},#{size}")
    List<Brand> selectByPage(@Param("begin") int begin,@Param("size") int size);

    /**
     * Count total records
     * @return
     */
    @Select("select count(*) from tb_brand")
    int selectTotalCount();

    /**
     * Paginate with condition query
     * @param begin
     * @param size
     * @param brand
     * @return
     */
    List<Brand> selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand);

    /**
     * Count total records with condition
     * @return
     */
    int selectTotalCountByCondition(Brand brand);

2. Pojo Layer

package org.example.pojo;

import java.sql.Date;

public class Brand {
    // ID primary key
    private Integer id;
    // Brand name
    private String brandName;
    // Company name
    private String companyName;
    // Sort field
    private Integer ordered;
    // Description information
    private String description;
    // Status: 0: disabled, 1: enabled
    private Integer status;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Date getBackdate() {
        return backdate;
    }

    public void setBackdate(Date backdate) {
        this.backdate = backdate;
    }

    private Date date;
    private Date backdate;


    public Integer getId() {
        return id;
    }

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

    public String getBrandName() {
        return brandName;
    }

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

    public String getCompanyName() {
        return companyName;
    }

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

    public Integer getOrdered() {
        return ordered;
    }

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

    public String getDescription() {
        return description;
    }

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

    public Integer getStatus() {
        return status;
    }
    // Logical view
    public String getStatusStr(){
        if (status == null){
            return "unknown";
        }
        return status == 0 ? "out of stock":"normal";
    }

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

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

PageBean Pojo for Pagination

package org.example.pojo;

import java.util.List;

// JavaBean for pagination query
public class PageBean<T> {
    // Total number of records
    private int totalCount;
    // Current page data
    private List<T> rows;

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

}

Service Layer

package org.example.service;

import org.example.mapper.BrandMapper;
import org.example.pojo.Brand;
import org.example.pojo.PageBean;
import org.example.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.pojo.PageBean;

import java.util.List;

public class BrandService {
    // 1. Create the corresponding SqlSessionFactory factory object
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * Query data
     * @return
     */
    public List<Brand> selectAll() {
        // 2. Get SqlSession object
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Call method
        List<Brand> brands = mapper.selectAll();

        // 5. Release resources
        sqlSession.close();

        return brands;
    }

    /**
     * Add data
     * @param brand
     */
    public void add(Brand brand){
        // 2. Get SqlSession object
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Call method
        mapper.add(brand);

        // Commit transaction
        sqlSession.commit();

        // 5. Release resources
        sqlSession.close();
    }

    /**
     * Batch delete
     * @param ids
     */
    public void deleteByIds(int[] ids){
        // 2. Get SqlSession object
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Call method
        mapper.deleteByIds(ids);

        // Commit transaction
        sqlSession.commit();

        // 5. Release resources
        sqlSession.close();
    }

    /**
     * Single delete
     * @param id
     */
    public void deleteById(int id){
        // 2. Get SqlSession object
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Call method
        mapper.deleteById(id);

        // Commit transaction
        sqlSession.commit();

        // 5. Release resources
        sqlSession.close();
    }

    /**
     * Update
     * @param brand
     */
    public void update(Brand brand){
        // 2. Get SqlSession
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Call method
        mapper.update(brand);

        // Commit transaction
        sqlSession.commit();

        // Release resources
        sqlSession.close();
    }

    /**
     * 
     * @param currentPage  Current page number
     * @param pageSize  Number of items per page
     * @return
     */
    public PageBean<Brand> selectByPage(int currentPage, int pageSize){
        // 2. Get SqlSession object
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Calculate start index
        int begin = (currentPage-1) * pageSize;
        // Calculate number of items to retrieve
        int size = pageSize;

        // 5. Retrieve current page data
        List<Brand> rows = mapper.selectByPage(begin, size);

        // 6. Retrieve total record count
        int totalCount = mapper.selectTotalCount();

        // 7. Encapsulate PageBean object
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        // 8. Release resources
        sqlSession.close();

        return pageBean;
    }

    /**
     * Paginate with condition query
     * @param currentPage
     * @param pageSize
     * @param brand
     * @return
     */
    public PageBean<Brand> selectByPageAndCondition(int currentPage,int pageSize,Brand brand){
        // 2. Get SqlSession object
        SqlSession sqlSession = factory.openSession();

        // 3. Get BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        // 4. Calculate start index
        int begin = (currentPage-1) * pageSize;
        // Calculate number of items to retrieve
        int size = pageSize;

        // Process brand condition for fuzzy query
        String brandName = brand.getBrandName();
        if(brandName != null && brandName.length()>0){
            brand.setBrandName("%"+brandName+"%");
        }

        String companyName = brand.getCompanyName();
        if(companyName != null && companyName.length()>0){
            brand.setCompanyName("%"+companyName+"%");
        }

        // 5. Retrieve current page data
        List<Brand> rows = mapper.selectByPageAndCondition(begin, size,brand);

        // 6. Retrieve total record count
        int totalCount = mapper.selectTotalCountByCondition(brand);

        // 7. Encapsulate PageBean object
        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        // 8. Release resources
        sqlSession.close();

        return pageBean;
    }

}

Servlet Layer

Link: https://pan.baidu.com/s/1nFJ-3mC5znfBFgTm-oAw6g Code: 1fka

Summary

When implementing basic CRUD operations, many issues may arise, such as filters preventing recognition of Vue, or SQL problems when adding data. Stay calm.

Tags: Java Webcrud

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.