Spring Boot中Repository Void方法的Service层调用及字段硬编码问题
Let's break down your issue and fix it step by step:
First, Fix the Repository Method's Parameter Mismatch
Looking at your repository code, there's a critical inconsistency that'll break your intended logic:
@Transactional @Modifying @Query(value = "UPDATE pengajuan u set u.status_approval ='Komite' where u.id_pengajuan =:idPengajuan", nativeQuery = true) void updateStatusPengajuan(@Param("statusApproval") String statusApproval, @Param("idPengajuan") Integer idPengajuan);
You're accepting a statusApproval parameter but hardcoding 'Komite' in the SQL—this means the parameter is completely unused! Depending on your actual need:
- If you always want to set status to
'Komite', remove the redundantstatusApprovalparameter entirely:@Transactional @Modifying @Query(value = "UPDATE pengajuan u set u.status_approval ='Komite' where u.id_pengajuan =:idPengajuan", nativeQuery = true) void updateStatusPengajuan(@Param("idPengajuan") Integer idPengajuan); - If you want to pass dynamic status values, adjust the SQL to use the parameter properly:
@Transactional @Modifying @Query(value = "UPDATE pengajuan u set u.status_approval = :statusApproval where u.id_pengajuan =:idPengajuan", nativeQuery = true) void updateStatusPengajuan(@Param("statusApproval") String statusApproval, @Param("idPengajuan") Integer idPengajuan);
Now, Fix the Service Layer Implementation
Since your repository method returns void, you can't return its result directly in the service. Here are two practical solutions based on your needs:
Option 1: Change Service Method to Return Void
If you don't need to return the updated entity after the operation, simply adjust the service method's return type and call the repository directly:
public void update(String statusApproval, int idPengajuan) { pengajuanK3Repository.updateStatusPengajuan(statusApproval, idPengajuan); }
Option 2: Return the Updated Entity
If you need to return the updated PengajuanK3 instance, execute the update first, then fetch the entity from the database. Make sure your service method is annotated with @Transactional to ensure both operations run in the same transaction (so you get the latest updated data):
@Transactional public PengajuanK3 update(String statusApproval, int idPengajuan) { // Run the update query pengajuanK3Repository.updateStatusPengajuan(statusApproval, idPengajuan); // Fetch the updated entity (assuming your repo has a findById method) return pengajuanK3Repository.findById(idPengajuan) .orElseThrow(() -> new IllegalArgumentException("Pengajuan not found with ID: " + idPengajuan)); }
内容的提问来源于stack exchange,提问作者Ernesto

