It seems like your message got cut off. How can I assist you today?
User
code
Assistant
It looks like you're still trying to send something, but I'm not receiving any content. If you have a question or need assistance, please type it out, and I'll be happy to help!
User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
## Instruction to developer: save this file as .cursorrules and place it on the root project directory
AI Persona:
You are an experienced Senior Java Developer, You always adhere to SOLID principles, DRY principles, KISS principles and YAGNI principles. You always follow OWASP best practices. You always break task down to smallest units and approach to solve any task in step by step manner.
Technology stack:
Framework: Java Spring Boot 3 Maven with Java 17 Dependencies: Spring Web, Spring Data JPA, Thymeleaf, Lombok, PostgreSQL driver
Application Logic Design:
1. All request and response handling must be done only in RestController.
2. All database operation logic must be done in ServiceImpl classes, which must use methods provided by Repositories.
3. RestControllers cannot autowire Repositories directly unless absolutely beneficial to do so.
4. ServiceImpl classes cannot query the database directly and must use Repositories methods, unless absolutely necessary.
5. Data carrying between RestControllers and serviceImpl classes, and vice versa, must be done only using DTOs.
6. Entity classes must be used only to carry data out of database query executions.
Entities
1. Must annotate entity classes with @Entity.
2. Must annotate entity classes with @Data (from Lombok), unless specified in a prompt otherwise.
3. Must annotate entity ID with @Id and @GeneratedValue(strategy=GenerationType.IDENTITY).
4. Must use FetchType.LAZY for relationships, unless specified in a prompt otherwise.
5. Annotate entity properties properly according to best practices, e.g., @Size, @NotEmpty, @Email, etc.
Repository (DAO):
1. Must annotate repository classes with @Repository.
2. Repository classes must be of type interface.
3. Must extend JpaRepository with the entity and entity ID as parameters, unless specified in a prompt otherwise.
4. Must use JPQL for all @Query type methods, unless specified in a prompt otherwise.
5. Must use @EntityGraph(attributePaths={"relatedEntity"}) in relationship queries to avoid the N+1 problem.
6. Must use a DTO as The data container for multi-join queries with @Query.
Service:
1. Service classes must be of type interface.
2. All service class method implementations must be in ServiceImpl classes that implement the service class,
3. All ServiceImpl classes must be annotated with @Service.
4. All dependencies in ServiceImpl classes must be @Autowired without a constructor, unless specified otherwise.
5. Return objects of ServiceImpl methods should be DTOs, not entity classes, unless absolutely necessary.
6. For any logic requiring checking the existence of a record, use the corresponding repository method with an appropriate .orElseThrow lambda method.
7. For any multiple sequential database executions, must use @Transactional or transactionTemplate, whichever is appropriate.
Data Transfer object (DTo):
1. Must be of type record, unless specified in a prompt otherwise.
2. Must specify a compact canonical constructor to validate input parameter data (not null, blank, etc., as appropriate).
RestController:
1. Must annotate controller classes with @RestController.
2. Must specify class-level API routes with @RequestMapping, e.g. ("/api/user").
3. Class methods must use best practice HTTP method annotations, e.g, create = @postMapping("/create"), etc.
4. All dependencies in class methods must be @Autowired without a constructor, unless specified otherwise.
5. Methods return objects must be of type Response Entity of type ApiResponse.
6. All class method logic must be implemented in a try..catch block(s).
7. Caught errors in catch blocks must be handled by the Custom GlobalExceptionHandler class.
ApiResponse Class (/ApiResponse.java):
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResponse<T> {
private String result; // SUCCESS or ERROR
private String message; // success or error message
private T data; // return object from service class, if successful
}
GlobalExceptionHandler Class (/GlobalExceptionHandler.java)
@RestControllerAdvice
public class GlobalExceptionHandler {
public static ResponseEntity<ApiResponse<?>> errorResponseEntity(String message, HttpStatus status) {
ApiResponse<?> response = new ApiResponse<>("error", message, null)
return new ResponseEntity<>(response, status);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ApiResponse<?>> handleIllegalArgumentException(IllegalArgumentException ex) {
return new ResponseEntity<>(ApiResponse.error(400, ex.getMessage()), HttpStatus.BAD_REQUEST);
}
}
Đây là rules dành cho cursor. Giúp tôi custom nó lại sao cho phù hợp với Java Spring Framework Maven with Java 17 Dependencies: Multi-Module Project with Maven,Spring beans, mybatis, JUnit, hamcrest, mockito, PlantUML .v.v.không dùng spring-boot, spring-web, spring-batch). Tôi đang thực hiện di chuyển tập script perl cũ sang java spring framework. tôi nghĩ cũng không cần DTO và app dụng tiếp cận gần với domain driven design principles
Assistant
Certainly! To adapt your cursor rules for a Java Spring framework (without Spring Boot) and a multi-module project structure, while incorporating MyBatis, JUnit, Hamcrest, Mockito, and PlantUML, we can redefine the principles and structures based on your existing requirements while eliminating the need for DTOs and aligning closer to Domain Driven Design (DDD).
Here's how you can structure the new set of rules:
Updated Rules for Cursor in Java Spring Framework (No Spring Boot)
General Principles
Domain-Driven Design (DDD): Prioritize domain entities and services, focusing on business logic and domain complexities rather than technical constraints.
SOLID Principles: Continue to follow SOLID principles.
DRY, KISS, YAGNI: Continue to adhere to these principles to keep your code clean and maintainable.
Test-Driven Development: Ensure that all new features are written with tests using JUnit, Hamcrest, and Mockito.
Technology Stack
Framework: Java Spring (without Spring Boot), using MyBatis for persistence
Testing Libraries: JUnit, Hamcrest, Mockito
Documentation Tools: PlantUML
Application Logic Design
Request Handling: All request and response handling should take place in Spring Controllers.
Database Operations: All interaction with the database must be done through MyBatis mappers.
Direct Interactions: Controllers should not directly access the MyBatis mappers. Logic should be encapsulated within domain services.
Entities: Use domain entities directly without DTOs for carrying data to and from controllers.
Service Design: Services should manage the lifecycle and interactions of domain entities.
Entities
Entity Annotations: Use appropriate mappings for entities with MyBatis, e.g., @Table.
Data Classes: Utilize Java classes to represent domain models, ensuring they encapsulate both data and behavior.
Validation: Use Java Bean Validation for constraints and validation rules directly within domain entities.
Repository (DAO)
Mapper Interfaces:
Declare mapper interfaces for data access using MyBatis, without needing a separate repository layer.
User
câu này đâu rồi You are an experienced Senior Java Developer, You always adhere to SOLID principles, DRY principles, KISS principles and YAGNI principles. You always follow OWASP best practices. You always break task down to smallest units and approach to solve any task in step by step manner.
Assistant
Certainly! Here's the revised ruleset including that introductory statement:
Updated Rules for Cursor in Java Spring Framework (No Spring Boot)
AI Persona:
You are an experienced Senior Java Developer. You always adhere to SOLID principles, DRY principles, KISS principles, and YAGNI principles. You always follow OWASP best practices. You always break tasks down into the smallest units and approach solving any task in a step-by-step manner.
General Principles
Domain-Driven Design (DDD): Prioritize domain entities and services, focusing on business logic and domain complexities rather than technical constraints.
SOLID Principles: Continue to follow SOLID principles.
DRY, KISS, YAGNI: Continue to adhere to these principles to keep your code clean and maintainable.
Test-Driven Development: Ensure that all new features are written with tests using JUnit, Hamcrest, and Mockito.
Technology Stack
Framework: Java Spring (without Spring Boot), using MyBatis for persistence
Testing Libraries: JUnit, Hamcrest, Mockito
Documentation Tools: PlantUML
Application Logic Design
Request Handling: All request and response handling should take place in Spring Controllers.
Database Operations: All interaction with the database must be done through MyBatis mappers.
Direct Interactions: Controllers should not directly access the MyBatis mappers. Logic should be encapsulated within domain services.
Entities: Use domain entities directly without DTOs for carrying data to and from controllers.
Service Design: Services should manage the lifecycle and interactions of domain entities.
Entities
Entity Annotations: Use appropriate mappings for entities with MyBatis, e.g., @Table.
Data Classes: Utilize Java classes to represent domain models, ensuring they encapsulate both data and behavior.
Validation: Use Java Bean Validation for constraints and validation rules directly within domain entities.
Repository (DAO)
Mapper Interfaces:
Declare mapper interfaces for data access using MyBatis, without needing a separate repository layer.
User
app của tôi không phải là api nên không cần thêm vào rule
Assistant
Được rồi! Nếu ứng dụng của bạn không phải là API và không cần thêm các yếu tố liên quan đến RESTful API, chúng ta có thể điều chỉnh lại các quy tắc để phù hợp hơn. Dưới đây là phiên bản cập nhật mà không bao gồm các yếu tố liên quan đến API:
Cập nhật Quy tắc cho Cursor trong Java Spring Framework (Không phải Spring Boot)
AI Persona:
Bạn là một Nhà Phát Triển Java Senior có kinh nghiệm. Bạn luôn tuân thủ các nguyên tắc SOLID, nguyên tắc DRY, nguyên tắc KISS và nguyên tắc YAGNI. Bạn luôn theo đuổi các thực tiễn tốt nhất của OWASP. Bạn luôn phân chia công việc thành các đơn vị nhỏ nhất và tiếp cận giải quyết bất kỳ công việc nào theo cách từng bước.
Nguyên tắc Tổng quát
Domain-Driven Design (DDD): Ưu tiên các thực thể miền và dịch vụ, tập trung vào logic kinh doanh và các phức tạp của miền hơn là các rào cản kỹ thuật.
Nguyên tắc SOLID: Tiếp tục tuân theo các nguyên tắc SOLID.
DRY, KISS, YAGNI: Tiếp tục tuân thủ các nguyên tắc này để giữ cho mã nguồn sạch sẽ và dễ bảo trì.
Phát triển Dựa trên Kiểm thử: Đảm bảo rằng tất cả các tính năng mới đều được viết với kiểm thử sử dụng JUnit, Hamcrest, và Mockito.
Công nghệ
Framework: Java Spring (không sử dụng Spring Boot), sử dụng MyBatis cho việc truy cập cơ sở dữ liệu.
Thư viện Kiểm thử: JUnit, Hamcrest, Mockito.
Công cụ Tài liệu: PlantUML.
Thiết kế Logic Ứng Dụng
Xử lý Yêu cầu: Tất cả các xử lý yêu cầu và phản hồi sẽ được thực hiện trong các Controller của Spring.
Hoạt động Cơ sở dữ liệu: Tất cả các tương tác với cơ sở dữ liệu phải được thực hiện thông qua các mapper của MyBatis.
Tương tác Trực tiếp: Các Controller không nên truy cập trực tiếp vào các mapper của MyBatis. Logic phải được đóng gói trong các dịch vụ miền.
Thực thể: Sử dụng các thực thể miền trực tiếp mà không cần DTO để truyền dữ liệu đến và đi từ các controller.
Thiết kế Dịch vụ: Các dịch vụ phải quản lý vòng đời và các tương tác của các thực thể miền.
Thực thể
Chú thích Thực thể: Sử dụng các ánh xạ phù hợp cho các thực thể với MyBatis, ví dụ: @Table.
Lớp Dữ liệu: Sử dụng các lớp Java để đại diện cho các mô hình miền, đảm bảo chúng bao gồm cả dữ liệu và hành vi.
Xác thực: Sử dụng Java Bean Validation cho các ràng buộc và quy tắc xác thực trực tiếp trong các thực thể miền.
User
thêm log4j2
Assistant
Chắc chắn rồi! Khi thêm Log4j2 vào ứng dụng Java Spring của bạn, chúng ta cần cập nhật các quy tắc để phản ánh việc sử dụng logging. Dưới đây là phiên bản cập nhật với các quy tắc cho Log4j2:
Cập nhật Quy tắc cho Cursor trong Java Spring Framework (Không phải Spring Boot)
AI Persona:
Bạn là một Nhà Phát Triển Java Senior có kinh nghiệm. Bạn luôn tuân thủ các nguyên tắc SOLID, nguyên tắc DRY, nguyên tắc KISS và nguyên tắc YAGNI. Bạn luôn theo đuổi các thực tiễn tốt nhất của OWASP. Bạn luôn phân chia công việc thành các đơn vị nhỏ nhất và tiếp cận giải quyết bất kỳ công việc nào theo cách từng bước.
Nguyên tắc Tổng quát
Domain-Driven Design (DDD): Ưu tiên các thực thể miền và dịch vụ, tập trung vào logic kinh doanh và các phức tạp của miền hơn là các rào cản kỹ thuật.
Nguyên tắc SOLID: Tiếp tục tuân theo các nguyên tắc SOLID.
DRY, KISS, YAGNI: Tiếp tục tuân thủ các nguyên tắc này để giữ cho mã nguồn sạch sẽ và dễ bảo trì.
Phát triển Dựa trên Kiểm thử: Đảm bảo rằng tất cả các tính năng mới đều được viết với kiểm thử sử dụng JUnit, Hamcrest và Mockito.
Công nghệ
Framework: Java Spring (không sử dụng Spring Boot), sử dụng MyBatis cho việc truy cập cơ sở dữ liệu.
Thư viện Kiểm thử: JUnit, Hamcrest, Mockito.
Công cụ Tài liệu: PlantUML.
Logging: Log4j2 cho việc ghi log.
Thiết kế Logic Ứng Dụng
Xử lý Yêu cầu: Tất cả các xử lý yêu cầu và phản hồi sẽ được thực hiện trong các Controller của Spring.
Hoạt động Cơ sở dữ liệu: Tất cả các tương tác với cơ sở dữ liệu phải được thực hiện thông qua các mapper của MyBatis.
Tương tác Trực tiếp: Các Controller không nên truy cập trực tiếp vào các mapper của MyBatis. Logic phải được đóng gói trong các dịch vụ miền.
Thực thể: Sử dụng các thực thể miền trực tiếp mà không cần DTO để truyền dữ liệu tới và đi từ các controller.
Thiết kế Dịch vụ: Các dịch vụ phải quản lý vòng đời và các tương tác của các thực thể miền.
Thực thể
Chú thích Thực thể: Sử dụng các ánh xạ phù hợp cho các thực thể với MyBatis, ví dụ: @Table.
Lớp Dữ liệu: Sử dụng các lớp Java để đại diện cho các mô hình miền, đảm bảo chúng bao gồm cả dữ liệu và hành vi.
Xác thực: Sử dụng Java Bean Validation cho các ràng buộc và quy tắc xác thực trực tiếp trong các thực thể miền.
User
Đây là nội dung countTokenStockQuantities.pl
code
#!/usr/bin/perl -X
package countTokenStockQuantities;
#ライブラリ共通パスの設定ファイル読み込み
BEGIN {
require "uselibidtool.conf";
require "libDebug.pl";
}
use utf8;
use itj_config;
use AC004_Utility;
use AC004_Utility_config;
use DB_MANAGEMENT::TokenStockManagement;
Log::Log4perl::init($itj_config::log4conf); #初期設定
my $logger = Log::Log4perl::get_logger("jp1bat"); #logger取得
# プログラム名
my $pgname = 'countTokenStockQuantities';
# プログラムID
my $pgid = 'countTokenStockQuantities';
my $schema = $itj_config::DB_Schema;
my @aryerr = ( '', '', '', '', '', '' ); #エラー情報配列
my $rtnCd_OK = $itj_config::EXIT_SUCCESS; #正常終了時戻り値
my $rtnCd_NG = $itj_config::EXIT_FAILURE; #異常終了時戻り値
#排他実施フラグ(&err_Proc用)
my $lockExecFlag = $AC004_Utility_config::LOCK_EXEC_NONE;
#排他チェックエラー(&err_Proc用)
my $exclusion = $AC004_Utility_config::EXCLUSION_NONE;
# 更新ユーザID
my $system_user_id = $itj_config::UPDATE_ID;
sub main {
$logger->info('===== 月初トークン在庫数計算処理バッチ 開始 =====');
unless (
DB_MANAGEMENT::TokenStockManagement::countTokenStock( $pgid, $system_user_id, $logger, \@aryerr )
)
{
# 結果がエラーだった場合
&Utility::err_Proc( \@aryerr, $pgname, $logger, $lockExecFlag, $exclusion );
return $rtnCd_NG;
}
$logger->info('===== 月初トークン在庫数計算処理バッチ 終了 =====');
return ($rtnCd_OK);
}
if ( $0 eq __FILE__ ) {
# このファイルが直接実行された場合
exit( main() );
}
1;
Đây là nội dung TokenStockMail.pl
code
Assistant
Cấu trúc dự án của bạn trông rất hợp lý và chia sẻ rõ ràng giữa các thành phần chính của ứng dụng. Dưới đây là một số điểm nhấn và khuyến nghị để đảm bảo rằng cấu trúc này hoạt động hiệu quả:
Điểm Mạnh của Cấu Trúc
Chia Tách Module Rõ Ràng:
Cấu trúc của bạn đã tách biệt các phần như ứng dụng (counttokenstock) và phần chung (core). Điều này giúp dễ dàng theo dõi các thành phần khác nhau và cho phép quản lý phiên bản độc lập.
Thực Thể và Repository Tách Biệt:
Đặt các thực thể (entity) trong một thư mục con riêng và tương ứng với các repository. Điều này làm cho mã nguồn dễ đọc hơn và giúp quản lý các lớp liên quan đến cơ sở dữ liệu một cách hiệu quả.
Utilization of Infrastructure and Domain Layers:
Việc phân chia logic kinh doanh (domain) và logic liên quan đến việc truy xuất dữ liệu (infrastructure) giúp giữ cho mã nguồn sạch, dễ bảo trì và tuân theo nguyên tắc Single Responsibility.
Logging và Mail Service Tách Riêng:
Việc thiết lập các dịch vụ ghi log và gửi mail trong các thư mục riêng biệt giúp dễ dàng sửa đổi hoặc thay thế chúng mà không làm ảnh hưởng đến các phần khác của ứng dụng.
Thư viện Tài nguyên (Resources):
Đặt các tệp cấu hình và tài nguyên khác (như cấu hình mapper cho MyBatis) trong thư mục resources rất tốt cho sự rõ ràng và giúp tránh nhầm lẫn.
Một Số Khuyến Nghị
Cần Đảm Bảo Các Dependency Được Định Nghĩa Rõ Ràng:
Đảm bảo rằng các phụ thuộc giữa các module được xác định rõ ràng trong file pom.xml (nếu bạn đang sử dụng Maven). Điều này sẽ giúp quản lý các phiên bản thư viện dễ dàng hơn.
Kế Hoạch Cho Unit Testing:
Bạn đã lên kế hoạch cho các bài kiểm thử cho các thành phần của ứng dụng. Đảm bảo rằng các test case được xây dựng cho các chức năng và lớp chính sẽ giúp duy trì chất lượng mã nguồn.
Dùng Kiến Trúc DDD (Domain-Driven Design):
Nếu bạn định sử dụng kiến trúc DDD, hãy đảm bảo rằng các lớp trong domain layer không chỉ có cấu trúc mà còn thể hiện rõ ràng các hành vi (behaviors) và quy tắc nghiệp vụ (business rules).
Ghi Log Chặt Chẽ:
Hãy chắc chắn rằng việc ghi log được thực hiện tại các điểm quan trọng trong ứng dụng để dễ dàng theo dõi và xử lý sự cố.
User
Technology stack: Java Spring Framework Maven with Java 17 Dependencies: Spring beans, mybatis, JUnit, hamcrest, mockito, PlantUML .v.v.
Assistant
Dựa trên công nghệ mà bạn đã xác định cho dự án chuyển đổi từ Perl sang Java Spring Framework, hãy xem xét cách bạn có thể cấu hình cấu trúc dự án của mình với sự chú trọng vào từng thành phần của công nghệ bạn đã chọn, bao gồm:
Công Nghệ và Cấu Trúc Dự Án
Java 17:
Đảm bảo rằng môi trường phát triển của bạn hỗ trợ Java 17.
Cấu hình Maven để sử dụng Java 17 trong file pom.xml:
MyBatis Configuration: Use XML or annotations to configure MyBatis mappers without specifying database operations as separate repository classes.
Services
Service Interfaces: Define service interfaces for business operations, which will be implemented by service classes.
Service Implementation: Each service implementation should encapsulate the logic that operates on domain entities.
Dependency Injection: Use field injection for dependencies within service classes if necessary.
Controllers
Spring Controllers: Ensure controllers are annotated with @Controller or @RestController depending on the needs of the application.
Request Mapping: Use @RequestMapping annotations to define the API routes.
Handle Responses: Return domain entities directly if appropriate, otherwise use response objects for error handling.
Error Handling: Implement a global error handling mechanism using a centralized exception handler.
Error Handling
Global Exception Handling:
Create a class to handle exceptions globally, similar to the GlobalExceptionHandler in your initial prompt.
java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<?>> handleGlobalException(Exception ex) {
ApiResponse<?> response = new ApiResponse<>("error", ex.getMessage(), null);
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Testing
Unit Tests: Write unit tests for service methods using JUnit and Mockito.
Integration Tests: Write integration tests to confirm the interaction between the Spring framework and MyBatis.
Assertions: Use Hamcrest assertions for more readable test conditions.
Documentation
PlantUML: Utilize PlantUML for diagramming system architecture and design documentation.
Notes
Elimination of DTOs: Given the decision to eliminate DTOs, ensure that the domain entities are designed to be serializable or have appropriate methods for conversion to/from web representations.
Avoid Over-Engineering: Embrace simplicity in design and implementation, always assess the need for complex architectures versus straightforward solutions.
This revised version aligns with your requirements of moving from Perl scripts to a Java Spring architecture without the need for Spring Boot. It emphasizes direct interaction through domain entities and the flexibility of MyBatis for ORM mapping, while ensuring that best practices in object-oriented design principles are upheld. Additionally, it provides a focus on testing and documentation which is essential for any robust software development practice.
MyBatis Configuration: Use XML or annotations to configure MyBatis mappers without specifying database operations as separate repository classes.
Services
Service Interfaces: Define service interfaces for business operations, which will be implemented by service classes.
Service Implementation: Each service implementation should encapsulate the logic that operates on domain entities.
Dependency Injection: Use field injection for dependencies within service classes if necessary.
Controllers
Spring Controllers: Ensure controllers are annotated with @Controller or @RestController depending on the needs of the application.
Request Mapping: Use @RequestMapping annotations to define the API routes.
Handle Responses: Return domain entities directly if appropriate, otherwise use response objects for error handling.
Error Handling: Implement a global error handling mechanism using a centralized exception handler.
Error Handling
Global Exception Handling:
Create a class to handle exceptions globally, similar to the GlobalExceptionHandler in your initial prompt.
java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<?>> handleGlobalException(Exception ex) {
ApiResponse<?> response = new ApiResponse<>("error", ex.getMessage(), null);
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Testing
Unit Tests: Write unit tests for service methods using JUnit and Mockito.
Integration Tests: Write integration tests to confirm the interaction between the Spring framework and MyBatis.
Assertions: Use Hamcrest assertions for more readable test conditions.
Documentation
PlantUML: Utilize PlantUML for diagramming system architecture and design documentation.
Notes
Elimination of DTOs: Given the decision to eliminate DTOs, ensure that the domain entities are designed to be serializable or have appropriate methods for conversion to/from web representations.
Avoid Over-Engineering: Embrace simplicity in design and implementation, always assess the need for complex architectures versus straightforward solutions.
This complete version incorporates your specified introductory statement, emphasizing best practices in software development while adapting to the requirements of your Java Spring application using MyBatis. Let me know if you need further modifications or additional information!
Repository (DAO)
Giao diện Mapper:
Định nghĩa các giao diện mapper cho việc truy cập dữ liệu bằng MyBatis, không cần một lớp repository riêng biệt.
Cấu hình MyBatis: Sử dụng XML hoặc chú thích để cấu hình các mapper của MyBatis mà không cần chỉ định các hoạt động cơ sở dữ liệu như các lớp repository riêng biệt.
Dịch vụ
Giao diện Dịch vụ: Định nghĩa các giao diện dịch vụ cho các hoạt động kinh doanh, sẽ được thực hiện bởi các lớp dịch vụ.
Triển khai Dịch vụ: Mỗi triển khai dịch vụ phải đóng gói logic hoạt động trên các thực thể miền.
Tiêm Phụ thuộc: Sử dụng tiêm phụ thuộc cho các phụ thuộc trong các lớp dịch vụ nếu cần.
Xử lý Lỗi
Xử lý Lỗi Toàn cục:
Tạo một lớp để xử lý ngoại lệ toàn cục.
java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<?>> handleGlobalException(Exception ex) {
ApiResponse<?> response = new ApiResponse<>("error", ex.getMessage(), null);
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Kiểm thử
Kiểm thử Đơn vị: Viết các bài kiểm thử đơn vị cho các phương thức dịch vụ bằng JUnit và Mockito.
Kiểm thử Tích hợp: Viết các bài kiểm thử tích hợp để xác nhận sự tương tác giữa framework Spring và MyBatis.
Khẳng định: Sử dụng các khẳng định Hamcrest cho các điều kiện kiểm thử dễ đọc hơn.
Tài liệu
PlantUML: Sử dụng PlantUML để phác thảo kiến trúc hệ thống và tài liệu thiết kế.
Ghi chú
Loại bỏ DTO: Bởi vì quyết định loại bỏ DTO, hãy đảm bảo rằng các thực thể miền được thiết kế để có thể tuần tự hóa hoặc có các phương thức phù hợp cho việc chuyển đổi đến và đi từ các biểu diễn web.
Tránh Cung cấp Quá nhiều: Áp dụng sự đơn giản trong thiết kế và triển khai, luôn đánh giá nhu cầu về các kiến trúc phức tạp so với các giải pháp đơn giản.
Phiên bản này không bao gồm các yếu tố liên quan đến API và tập trung vào logic kinh doanh cùng với các thực thể miền trên nền tảng Java Spring với MyBatis. Nếu bạn cần thêm bất kỳ điều chỉnh nào khác, hãy cho tôi biết!
Repository (DAO)
Giao diện Mapper:
Định nghĩa các giao diện mapper cho việc truy cập dữ liệu bằng MyBatis, không cần một lớp repository riêng biệt.
Cấu hình MyBatis: Sử dụng XML hoặc chú thích để cấu hình các mapper của MyBatis mà không cần chỉ định các hoạt động cơ sở dữ liệu như các lớp repository riêng biệt.
Dịch vụ
Giao diện Dịch vụ: Định nghĩa các giao diện dịch vụ cho các hoạt động kinh doanh, sẽ được thực hiện bởi các lớp dịch vụ.
Triển khai Dịch vụ: Mỗi triển khai dịch vụ phải đóng gói logic hoạt động trên các thực thể miền.
Tiêm Phụ thuộc: Sử dụng tiêm phụ thuộc cho các phụ thuộc trong các lớp dịch vụ nếu cần.
Sử dụng Log4j2: Sử dụng Log4j2 để ghi log trong các lớp dịch vụ và controller. Cấu hình log cần phải có trong file log4j2.xml hoặc log4j2.properties.
java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MyServiceImpl implements MyService {
private static final Logger logger = LogManager.getLogger(MyServiceImpl.class);
public void someMethod() {
logger.info("Executing someMethod");
// Logic here
}
}
Xử lý Lỗi
Xử lý Lỗi Toàn cục:
Tạo một lớp để xử lý ngoại lệ toàn cục. Sử dụng log để ghi lại các lỗi.
java
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<?>> handleGlobalException(Exception ex) {
logger.error("An error occurred: ", ex);
ApiResponse<?> response = new ApiResponse<>("error", ex.getMessage(), null);
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Kiểm thử
Kiểm thử Đơn vị: Viết các bài kiểm thử đơn vị cho các phương thức dịch vụ bằng JUnit và Mockito.
Kiểm thử Tích hợp: Viết các bài kiểm thử tích hợp để xác nhận sự tương tác giữa framework Spring và MyBatis.
Khẳng định: Sử dụng các khẳng định Hamcrest cho các điều kiện kiểm thử dễ đọc hơn.
Tài liệu
PlantUML: Sử dụng PlantUML để phác thảo kiến trúc hệ thống và tài liệu thiết kế.
Ghi chú
Loại bỏ DTO: Bởi vì quyết định loại bỏ DTO, hãy đảm bảo rằng các thực thể miền được thiết kế để có thể tuần tự hóa hoặc có các phương thức phù hợp cho việc chuyển đổi đến và đi từ các biểu diễn web.
Tránh Cung cấp Quá nhiều: Áp dụng sự đơn giản trong thiết kế và triển khai, luôn đánh giá nhu cầu về các kiến trúc phức tạp so với các giải pháp đơn giản.
Phiên bản này đã được điều chỉnh để bao gồm các quy tắc sử dụng Log4j2 cho việc ghi log trong ứng dụng của bạn. Nếu bạn cần thêm thông tin chi tiết hoặc điều chỉnh thêm, hãy cho tôi biết!
#!/usr/bin/perl -X
BEGIN {
require "uselibidtool.conf";
}
use strict;
use warnings;
use utf8;
use open IN => ":encoding(utf8)";
use open OUT => ":encoding(utf8)";
use libMailCommon;
use Log::Log4perl;
use Oraperl;
use DB::CTOKEN_STOCK_MANAGEMENT;
use AC004_Utility;
my $pgid = 'TokenStockMail'; #プログラムID
my $schema = $itj_config::DB_Schema; #DBスキーマ
my $logger = ''; #ロガー
my @aryerr = (); #エラー情報配列
my $txtOutputPath = ''; #txtファイル格納ディレクトリ
my $txtFileName = ''; #txtファイル名称
my $pgname = '月初トークン在庫数メール送信処理(TokenStockMail)'; #プログラム名称
exit( &main() );
sub main {
#戻り値初期化
my $retCode = $itj_config::EXIT_SUCCESS;
#初期処理
if ( &initProcess() ) {
#月初トークン在庫数メール送信処理
unless ( &exTokenStockProcess() ) {
#月初トークン在庫数メール送信処理異常
$retCode = $itj_config::EXIT_FAILURE;
&Utility::err_Proc( \@aryerr, $pgname, $logger );
}
} else {
#初期処理異常
$retCode = $itj_config::EXIT_FAILURE;
&Utility::err_Proc( \@aryerr, $pgname, $logger );
}
#終了処理
&endProcess();
return $retCode;
}
sub exTokenStockProcess {
#月初トークン在庫数リスト
my @tokenStockList = ();
#月初トークン在庫数取得処理
unless ( &getTokenStockList( \@tokenStockList ) ) {
return 0;
}
#txtファイル作成処理
unless ( &createTxtFile( \@tokenStockList, $txtOutputPath . $txtFileName ) ) {
return 0;
}
#メール送信処理
unless ( &sendMailWithAttach( $txtOutputPath, $txtFileName ) ) {
return 0;
}
return 1;
}
sub initProcess {
#ロガーの初期化
Log::Log4perl::init($itj_config::log4conf);
$logger = Log::Log4perl::get_logger("counttokenstock");
#ログの出力
$logger->info("======================================================================");
$logger->info( $pgname . " 処理開始" );
$logger->info("======================================================================");
$logger->info("");
$txtOutputPath = $itj_config::TOKENSTOCK_OUTPUT_PATH; #txtファイル格納ディレクトリ
$txtFileName
= $itj_config::TOKENSTOCK_OUTPUT_FILENAME
. &Utility::get_Datetime("%04d%02d%02d")
. ".txt"; #txtファイル名称
return 1;
}
sub getTokenStockList {
my ($refTokenStockList) = @_; #引数取得
my $stock_date = &Utility::get_Datetime("%04d%02d"); #在庫月
# トークン在庫数リスト(参照渡し)初期化
@$refTokenStockList = ();
$logger->info("----------------------------------------------------------------------");
$logger->info("トークン在庫数取得処理 開始");
# DBインスタンス(トークン在庫管理)
my $db_stock_management = DB::CTOKEN_STOCK_MANAGEMENT->new($schema);
#既登録レコード
my $row = {};
unless ( $db_stock_management->select_token_stock_management( $stock_date, \$row, \@aryerr ) ) {
# 既存レコードの取得でエラーになった場合
return 0;
}
#トークン在庫数設定
@$refTokenStockList = "\"$row->{ 'STOCK_DATE' }\",\"$row->{ 'STOCK_SWT' }\",\"$row->{ 'STOCK_HWT' }\"";
$logger->info("トークン在庫数取得処理 終了");
$logger->info("----------------------------------------------------------------------");
return 1;
}
sub createTxtFile {
$logger->info("----------------------------------------------------------------------");
$logger->info("txtファイル作成 開始");
#引数取得
my $token_stock_list = $_[0]; #月初トークン在庫数情報リスト
my $path = $_[1]; #保存先ファイル(パス付)
#保存先ファイル(パス付)オープン
my $opn_ret = open( my $out_hd, '>', "$path" );
unless ($opn_ret) {
#失敗する場合
&Utility::err_Set( \@aryerr, '', '', $pgname, '', '',
"指定したパスが存在しません。($path)" );
return 0;
}
#保存先ファイル(パス付)へ月初トークン在庫数情報を書込
foreach my $data (@$token_stock_list) {
print( $out_hd $data . "\n" );
}
#保存先ファイル(パス付)クローズ
close($out_hd);
$logger->info("txtファイル作成 終了");
$logger->info("----------------------------------------------------------------------");
return 1;
}
sub sendMailWithAttach {
$logger->info("----------------------------------------------------------------------");
$logger->info("メール送信処理 開始");
my $ftxtpath = $_[0]; #添付ファイル格納ディレクトリ
my $ftxtname = $_[1]; #添付ファイル名称
my $fname = $ftxtpath . $ftxtname; #添付ファイル名(パス付)
my $from = $itj_config::TOKENSTOCK_SEND_MAIL_FROM; #差出人メールアドレス
my $to = $itj_config::TOKENSTOCK_SEND_MAIL_TO; #送信先メールアドレス
my $txtOutDate = &Utility::get_Datetime("%04d/%02d"); #出力年/月
my $subject = sprintf( $itj_config::TOKENSTOCK_SEND_MAIL_title, $txtOutDate ); #件名
my %data = (); # メール本文作成用データ
my $err; # メール本文作成時エラー文字列
my @header = (); # ヘッダー情報リスト
my $body
= &Utility::subTempleteToRetern( \%data, $itj_config::TOKENSTOCK_SEND_MAIL_TEMPLATE, \$err ); #本文
#添付ファイルオープン
my $opn_ret = open( my $in_hd, '<', "$fname" );
unless ($opn_ret) {
&Utility::err_Set( \@aryerr, '', '', $pgname, '', '',
"添付対象のファイルのオープンができませんでした。($fname)" );
return 0;
}
#添付ファイルを読込
my $filebody; #添付ファイル
my $filesize = -s $fname; #添付ファイルサイズ
my $readsize = read( $in_hd, $filebody, $filesize ); #添付ファイルサイズ読込サイズ
#添付ファイルクローズ
close($in_hd);
unless ( &MailCommon::SendAttachedMail( $to, $from, $subject, $body, {}, $ftxtname, $filebody, @header ) )
{
&Utility::err_Set( \@aryerr, '', '', $pgname, '', '',
"sendmailの実行に失敗しました。($MailCommonConfig::SENDMAIL)" );
$logger->error("メール送信処理 エラー終了");
$logger->error("Subject: $subject");
$logger->error("From: $from");
$logger->error("To: $to");
$logger->error("添付ファイル名: $ftxtname");
$logger->error(" ---- メール本文 ---- ");
$logger->error("$body");
$logger->error(" ---- メール本文終了 ---- ");
# 添付ファイル出力用のファイル名を作成
$ftxtname =~ s/\.txt//;
my $ftxt_pid = $ftxtname . '_' . $$ . '.txt'; #PID付き 添付ファイル出力用のファイル名
$logger->error("保存された添付ファイル: $ftxt_pid");
MailCommon::outputFile( 'log', $ftxt_pid, $filebody );
return 0;
}
$logger->info("メール送信処理 終了");
$logger->info("----------------------------------------------------------------------");
return 1;
}
sub endProcess {
$logger->info("======================================================================");
$logger->info( $pgname . " 処理終了" );
$logger->info("======================================================================");
$logger->info("");
return;
}
Đây là file TokenStockManagement.pm
code
use strict;
use warnings;
use Carp;
use utf8;
use Oraperl;
use itj_config;
use RAP_DB::CRAS_CARD_MASTER;
use RAP_DB::CTOKEN_STOCK_MANAGEMENT;
use CRAS_CARD_MASTERConfig;
# DBスキーマ
my $DB_SCHEMA = $itj_config::DB_Schema;
sub _getStockDate {
# 現在日取得
my ( $sec, $min, $hour, $mday, $mon, $year ) = localtime();
return sprintf( '%04d%02d', $year + 1900, $mon + 1 );
}
sub countTokenStock {
my ( $program_id, $update_id, $logger, $ref_aryerr ) = @_;
$logger->info("トークン在庫数計算処理 開始");
# DBインスタンス(セキュアIDカードマスタ)
my $db_card_master = DB::CRAS_CARD_MASTER->new($DB_SCHEMA);
# 在庫月取得
# 在庫月
my $stock_date = _getStockDate();
$logger->debug( "在庫月:" . $stock_date ) if $logger->is_debug();
# ソフトウェアトークン在庫数取得
# ソフトウェアトークン在庫数
my $stock_swt = 0;
unless (
$db_card_master->get_stock_quantity(
$CRAS_CARD_MASTERConfig::KIND_SWT, \$stock_swt, $ref_aryerr
)
)
{
# 在庫数取得でエラーだった場合
return 0;
}
$logger->debug( "在庫数(ソフトウェア)::" . $stock_swt ) if $logger->is_debug();
# ハードウェアトークン在庫数取得
# ハードウェアトークン在庫数
my $stock_hwt = 0;
unless (
$db_card_master->get_stock_quantity(
$CRAS_CARD_MASTERConfig::KIND_HWT, \$stock_hwt, $ref_aryerr
)
)
{
# 在庫数取得でエラーだった場合
return 0;
}
$logger->debug( "在庫数(ハードウェア)::" . $stock_hwt ) if $logger->is_debug();
# トークン在庫管理テーブル登録
my %data = (
STOCK_DATE => $stock_date,
STOCK_SWT => $stock_swt,
STOCK_HWT => $stock_hwt,
PROGRAM_ID => $program_id,
UPDATE_ID => $update_id
);
# DBインスタンス(トークン在庫管理)
my $db_stock_management = DB::CTOKEN_STOCK_MANAGEMENT->new($DB_SCHEMA);
# 既登録レコード
my $row = {};
unless ( $db_stock_management->select_token_stock_management( $stock_date, \$row, $ref_aryerr ) ) {
# 既存レコードの取得でエラーになった場合
return 0;
}
if ($row) {
# 既登録レコードが存在する
unless ( $db_stock_management->update_token_stock_management( \%data, $ref_aryerr ) ) {
# 更新に失敗した場合
return 0;
}
} else {
# 既登録レコードが存在しない
unless ( $db_stock_management->insert_token_stock_management( \%data, $ref_aryerr ) ) {
# 登録に失敗した場合
return 0;
}
}
$logger->info("トークン在庫数計算処理 終了");
return 1;
}
package DB::CTOKEN_STOCK_MANAGEMENT;
use strict;
use warnings;
use Carp;
use utf8;
use Oraperl;
use Ora_r_pre;
use Ora_r;
use DB::CDB;
use CDBConfig;
our @ISA = qw(DB::CDB);
sub new {
my ( $class, $schema, $lda ) = @_;
# スーパークラスのnewを呼び出す
my $self = $class->SUPER::new( $schema, $lda );
return bless $self, $class;
}
sub select_token_stock_management {
my ( $self, $stock_date, $ref_result, $ref_aryerr ) = @_;
# このメソッド名
my $method_name = ( caller 0 )[3];
# パラメータチェック(シリアル番号)
if ( $self->SUPER::empty($stock_date) ) {
$self->SUPER::err_Set( $ref_aryerr, "", "", $method_name, $main::g_appnum, "",
"パラメータチェックエラー(在庫月未指定)" );
return 0;
}
# SQLテンプレート
my $sql_template = <<SQL;
SELECT
*
FROM
TOKEN_STOCK_MANAGEMENT
WHERE
STOCK_DATE = '%s'
SQL
# SQL
my $sql = sprintf( $sql_template, $stock_date );
# 検索結果
my $ref_row = $self->SUPER::ora_r_select_hashref($sql);
if ($main::gs_OrarErrParameter) {
# エラーの場合
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum, '',
"トークン在庫管理情報取得にてエラー発生\n" . $sql );
return 0;
}
# 結果格納
$$ref_result = $ref_row;
return 1;
}
sub insert_token_stock_management {
my ( $self, $ref_data, $ref_aryerr, $commit_prev ) = @_;
# このメソッド名
my $method_name = ( caller 0 )[3];
# パラメータチェック(シリアル番号)
if ( $self->SUPER::empty( $ref_data->{STOCK_DATE} ) ) {
$self->SUPER::err_Set( $ref_aryerr, "", "", $method_name, $main::g_appnum, "",
"パラメータチェックエラー(在庫月未指定)" );
return 0;
}
# 登録用SQLテンプレート
my $sql_template = <<SQL;
INSERT INTO
TOKEN_STOCK_MANAGEMENT (
STOCK_DATE,
STOCK_SWT,
STOCK_HWT,
PROGRAM_ID,
UPDATE_ID,
UPDATE_TIME
) VALUES (
'%s', -- STOCK_DATE
%s, -- STOCK_SWT
%s, -- STOCK_HWT
'%s', -- PROGRAM_ID
'%s', -- UPDATE_ID
sysdate -- UPDATE_TIME
)
SQL
# 登録用SQL
my $sql = sprintf( $sql_template,
$$ref_data{STOCK_DATE}, $$ref_data{STOCK_SWT}, $$ref_data{STOCK_HWT},
$$ref_data{PROGRAM_ID}, $$ref_data{UPDATE_ID} );
$self->SUPER::ora_r_do($sql);
if ($main::gs_OrarErrParameter) {
# SQL実行に失敗した場合
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum,
$$ref_data{ID},
"トークン在庫管理テーブル登録処理にてエラー発生\n" . $sql );
return 0;
}
if ( !defined($commit_prev) || $commit_prev == $CDBConfig::FLAG_TO_COMMIT ) {
# コミット抑制フラグが未定義もしくは1の場合コミットを実行する
$self->SUPER::ora_r_commit();
if ($main::gs_OrarErrParameter) {
# コミットに失敗した場合
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum, '',
"トークン在庫管理テーブル登録処理にてエラー発生(コミット)" );
return 0;
}
}
return 1;
}
sub update_token_stock_management {
my ( $self, $ref_data, $ref_aryerr, $commit_prev ) = @_;
# このメソッド名
my $method_name = ( caller 0 )[3];
# パラメータチェック(シリアル番号)
if ( $self->SUPER::empty( $ref_data->{STOCK_DATE} ) ) {
$self->SUPER::err_Set( $ref_aryerr, "", "", $method_name, $main::g_appnum, "",
"パラメータチェックエラー(在庫月未指定)" );
return 0;
}
# SQLテンプレート
my $sql_template = <<SQL;
UPDATE
TOKEN_STOCK_MANAGEMENT
SET
STOCK_SWT = %s,
STOCK_HWT = %s,
PROGRAM_ID = '%s',
UPDATE_ID = '%s',
UPDATE_TIME = sysdate
WHERE
STOCK_DATE = '%s'
SQL
# SQL
my $sql = sprintf( $sql_template,
$$ref_data{STOCK_SWT}, $$ref_data{STOCK_HWT}, $$ref_data{PROGRAM_ID},
$$ref_data{UPDATE_ID}, $$ref_data{STOCK_DATE} );
$self->SUPER::ora_r_do($sql);
if ($main::gs_OrarErrParameter) {
# SQL実行に失敗した場合
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum,
$$ref_data{ID},
"トークン在庫管理テーブル更新処理にてエラー発生\n" . $sql );
return 0;
}
if ( !defined($commit_prev) || $commit_prev == $CDBConfig::FLAG_TO_COMMIT ) {
# コミット抑制フラグが未定義もしくは1の場合コミットを実行する
$self->SUPER::ora_r_commit();
if ($main::gs_OrarErrParameter) {
# コミットに失敗した場合
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum, '',
"トークン在庫管理テーブル更新処理にてエラー発生(コミット)" );
return 0;
}
}
return 1;
}
sub commit {
my ( $self, $ref_aryerr ) = @_;
# このメソッド名
my $method_name = ( caller 0 )[3];
$self->SUPER::ora_r_commit();
# コミットに失敗した場合
if ($main::gs_OrarErrParameter) {
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum, '',
"トークン在庫管理テーブルのコミット処理にてエラー発生" );
return 0;
}
return 1;
}
sub rollback {
my ( $self, $ref_aryerr ) = @_;
# このメソッド名
my $method_name = ( caller 0 )[3];
$self->SUPER::ora_r_rollback();
# ロールバックに失敗した場合
if ($main::gs_OrarErrParameter) {
$self->SUPER::err_Set( $ref_aryerr, $ora_errno, $ora_errstr, $method_name, $main::g_appnum, '',
"トークン在庫管理テーブルのロールバック処理にてエラー発生" );
return 0;
}
return 1;
}
1;
đây là CDB.pm
code
package DB::CDB;
use strict;
use warnings;
use Carp;
use utf8;
use Oraperl;
use Ora_r_pre;
use Ora_r;
use libMailCommon;
sub new {
my ( $class, $schema, $lda ) = @_;
my $self = {};
# DB初期化
# DBハンドラが引数で未指定の場合初期化する。
unless ($lda) {
$lda = &main::ora_r_init($schema);
}
# DBハンドラ
$self->{lda} = $lda;
return bless $self, $class;
}
sub DESTROY {
my $self = shift;
# DB切断
&ora_r_term($self);
}
sub err_Set {
my ( $self, $ref_aryerr, $ora_err, $ora_errst, $errplace, $appnum, $id, $note, $title ) = @_;
#エラー情報格納
&MailCommon::err_Set( $ref_aryerr, $ora_err, $ora_errst, $errplace, $appnum, $id, $note, $title );
}
sub empty {
my ( $self, $val ) = @_;
return ( !defined $val ) || $val eq '';
}
sub ora_r_open {
my ( $self, $sql ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_open( $self->{lda}, $sql );
}
sub ora_r_close {
my ( $self, $csr ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_close($csr);
}
sub ora_r_term {
my $self = shift;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_term( $self->{lda} );
}
sub ora_r_fetch {
my ( $self, $csr ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_fetch($csr);
}
sub ora_r_select {
my ( $self, $sql ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_select( $self->{lda}, $sql );
}
sub ora_r_select_hashref {
my ( $self, $sql ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_select_hashref( $self->{lda}, $sql );
}
sub ora_r_titles {
my ( $self, $csr ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_titles($csr);
}
sub ora_r_fetchrow_hashref {
my ( $self, $csr ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_fetchrow_hashref($csr);
}
sub ora_r_do {
my ( $self, $sql ) = @_;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_do( $self->{lda}, $sql );
}
sub ora_r_commit {
my $self = shift;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_commit( $self->{lda} );
}
sub ora_r_rollback {
my $self = shift;
$main::gs_OrarCtrlParameter = 1;
return &main::ora_r_rollback( $self->{lda} );
}
sub _err_place {
# 呼び出し元(一つ前)
my $method_name = ( caller 1 )[3];
# 呼び出し元(二つ前)
my $caller_name = ( caller 2 )[3];
return "$method_name called by $caller_name";
}
sub select {
my ( $self, $sql, $ref_result, $ref_aryerr ) = @_;
# 結果格納領域の初期化
@$ref_result = ();
#カーソルオープン
my $csr = $self->ora_r_open($sql);
# オープンに失敗した場合
if ($main::gs_OrarErrParameter) {
$self->err_Set( $ref_aryerr, $ora_errno, $ora_errstr, _err_place(),
$main::g_appnum, "", "カーソル取得エラー\n" . $sql );
return 0;
}
#データ取得
while ( my $ref_row = $self->ora_r_fetchrow_hashref($csr) ) {
#データ取得に失敗した場合
if ($main::gs_OrarErrParameter) {
$self->err_Set( $ref_aryerr, $ora_errno, $ora_errstr, _err_place(),
$main::g_appnum, "", "フェッチエラー\n" . $sql );
return 0;
}
push( @$ref_result, $ref_row );
}
#カーソルクローズ
$self->ora_r_close($csr);
#クローズに失敗した場合
if ($main::gs_OrarErrParameter) {
$self->err_Set( $ref_aryerr, $ora_errno, $ora_errstr, _err_place(),
$main::g_appnum, "", "カーソルクローズエラー\n" . $sql );
return 0;
}
return 1;
}
1;
Đây là table data
code
CREATE TABLE TOKEN_STOCK_MANAGEMENT(
STOCK_DATE VARCHAR2(6) NOT NULL,
STOCK_SWT NUMBER(10) NOT NULL,
STOCK_HWT NUMBER(10) NOT NULL,
PROGRAM_ID VARCHAR2(50),
UPDATE_ID VARCHAR2(32),
UPDATE_TIME DATE DEFAULT SYSDATE,
CONSTRAINT TOKEN_STOCK_MANAGEMENT_PK PRIMARY KEY (
STOCK_DATE
)
CREATE TABLE RAS_CARD_MASTER(
SERIAL VARCHAR2(12) NOT NULL,
BUY_DATE DATE,
PIN VARCHAR2(32),
TERM DATE,
LOST_FLAG NUMBER(1) DEFAULT 0,
PROGRAM_ID VARCHAR2(50),
UPDATE_ID VARCHAR2(32),
UPDATE_TIME DATE,
CONSTRAINT RAS_CARD_MASTER_PK PRIMARY KEY (
SERIAL
)
Project perl cũ của tôi có rất nhiều script và nhiều tính năng khác nhau, nhưng hiện giờ chỉ cần quan tâm đến hai chức năng chính countTokenStockQuantities.pl và TokenStockMail.pl. Bây giờ tôi đang lên kế hoạch di chuyển các tập lệnh Perl countTokenStockQuantities.pl, TokenStockMail.pl v.v.. sang Java Spring Framework (không dùng spring-boot, spring-web, spring-batch) và đặt tên app là counttokenstock
The `core` **module** has been provisionally included in the project structure. However, at this stage, we are not actively developing or integrating any components into the `core` module. Our rationale is as follows:
- The `core` module is intended to house **common processing systems** and reusable components that can be shared across multiple applications.
- Premature abstraction into the `core` module may lead to unnecessary complexity and over-engineering.
- By focusing solely on the `counttokenstock`application, we can streamline development and ensure that the application meets its functional and non-functional requirements.
Once the `counttokenstock`application is stable and functional, we will conduct a thorough review to identify reusable components. These components will then be refactored into the `core` module if they meet the criteria for reusability and commonality.
Bạn xem qua cấu trúc counttokenstock có hợp lý chưa và tôi chỉ tập trung counttokenstock
Tài Liệu Mã Nguồn:
Khi di chuyển mã từ Perl sang Java, hãy đảm bảo rằng mã nguồn Java được tài liệu hóa và comment hợp lý để người khác (hoặc bạn trong tương lai) dễ hiểu.
Xem Xét Tính Tái Sử Dụng:
Khi bạn nhận thấy những thành phần cần thiết hoặc có thể được sử dụng trong ứng dụng khác, hãy xem xét việc chuyển chúng vào module core trước khi đi vào phát triển sâu hơn trong module này.
Theo Dõi Agile hoặc Kanban cho Phát Triển:
Nếu bạn làm việc trong một đội ngũ phát triển, hãy sử dụng các phương pháp Agile, Scrum, hoặc Kanban để theo dõi tiến độ phát triển và điều phối tốt hơn giữa các thành viên.
Kết Luận
Tóm lại, cấu trúc của bạn có vẻ ổn và hợp lý cho ứng dụng counttokenstock. Để làm cho dự án phát triển mạnh mẽ hơn, tập trung vào sự rõ ràng trong mã nguồn, quản lý các phụ thuộc và lập kế hoạch cho kiểm thử sẽ là những yếu tố rất quan trọng. Nếu bạn cần hỗ trợ thêm về một phần cụ thể nào đó trong cấu trúc hoặc mã nguồn, đừng ngần ngại hỏi!
Logging: Sử dụng Log4j2 đã được cấu hình trong tệp log4j2.xml để ghi log cho các service và application. Đảm bảo rằng các thông báo log có đủ mức độ chi tiết để hỗ trợ trong việc gỡ lỗi và kiểm tra.
Thực thi Migrations: Nếu bạn cần quản lý thay đổi trong cơ sở dữ liệu, hãy xem xét sử dụng một công cụ như Flyway hoặc Liquibase để quản lý các migration scripts.
Cấu hình Thư viện Phụ thuộc: Đảm bảo rằng tất cả các thư viện phụ thuộc cho Java Spring, MyBatis, JUnit, Hamcrest, Mockito và PlantUML được khai báo đúng trong pom.xml.
Tài liệu: Hãy tạo tài liệu chi tiết về cấu trúc dự án, hướng dẫn sử dụng và bất kỳ chi tiết nào khác có liên quan đến việc phát triển cũng như vận hành ứng dụng.
Mong rằng những thông tin trên có thể giúp bạn tổ chức và triển khai dự án của mình một cách dễ dàng và hiệu quả hơn! Nếu bạn cần thêm thông tin chi tiết nào khác, hãy hỏi nhé!