JavaWebアプリケーションのCRUD操作とデータ管理実装

システム要件

  • ブランドデータの基本CRUD操作実装
  • 一括削除機能の実装
  • ページング機能によるデータ表示
  • 条件指定検索機能の実装

環境設定

プロジェクト構成

Maven依存関係設定 (pom.xml):

<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>5.1.46</version>
  </dependency>
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
  </dependency>
</dependencies>

データベース設定

テーブル作成SQL:

CREATE TABLE product_brands (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(20),
  company VARCHAR(20),
  sort_order INT,
  details VARCHAR(100),
  active_status INT
);

データ取得機能

永続層実装

public interface ProductMapper {
  @Select("SELECT * FROM product_brands")
  List<Brand> fetchAllBrands();
}

サービス層実装

public class ProductServiceImpl implements ProductService {
  public List<Brand> getAllBrands() {
    try(SqlSession session = sqlFactory.openSession()) {
      ProductMapper mapper = session.getMapper(ProductMapper.class);
      return mapper.fetchAllBrands();
    }
  }
}

コントローラ最適化

public abstract class CoreServlet extends HttpServlet {
  protected void service(HttpServletRequest req, HttpServletResponse res) 
      throws ServletException, IOException {
      
    String path = req.getRequestURI();
    String methodName = path.substring(path.lastIndexOf('/') + 1);
    
    try {
      Method action = this.getClass().getMethod(methodName, 
          HttpServletRequest.class, HttpServletResponse.class);
      action.invoke(this, req, res);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

データ追加機能

サービス層実装

public boolean createBrand(Brand newBrand) {
  try(SqlSession session = sqlFactory.openSession(true)) {
    ProductMapper mapper = session.getMapper(ProductMapper.class);
    return mapper.insertBrand(newBrand) > 0;
  }
}

フロントエンド処理

addProduct() {
  axios.post('/brand-case/addBrand', this.productData)
    .then(response => {
      this.dialogVisible = false;
      this.loadProducts();
    });
}

一括削除機能

<!-- バックエンド処理 -->
public void removeMultiple(HttpServletRequest req, HttpServletResponse res) {
  int[] ids = JSON.parseObject(req.getReader(), int[].class);
  productService.deleteMultiple(ids);
}

<!-- フロントエンド -->
deleteSelected() {
  axios.post('/brand-case/deleteMultiple', this.selectedIds)
    .then(() => this.loadProducts());
}

ページネーション機能

public class PaginationResult<T> {
  private int totalRecords;
  private List<T> currentPageData;
  
  // getters/setters省略
}

public PaginationResult<Brand> getBrandsByPage(int page, int size) {
  int start = (page - 1) * size;
  List<Brand> items = mapper.fetchPage(start, size);
  int total = mapper.countAll();
  
  PaginationResult<Brand> result = new PaginationResult<>();
  result.setCurrentPageData(items);
  result.setTotalRecords(total);
  return result;
}

条件検索機能

<select id="searchByCriteria" resultMap="brandMap">
  SELECT * FROM product_brands
  <where>
    <if test="name != null">
      name LIKE CONCAT('%', #{name}, '%')
    </if>
    <if test="company != null">
      AND company LIKE CONCAT('%', #{company}, '%')
    </if>
  </where>
  LIMIT #{start}, #{size}
</select>

タグ: MyBatis Servlet vue.js ElementUI Axios

8月9日 17:03 投稿