简体   繁体   中英

spring entity update query check result

I have entity class accountant. I am trying save updated values of it. I am unable to do it.

I dont see any error logs . How do I check if the update query executed successfully or not

@Repository("accountantRepository")
@Transactional
public interface AccountantRepository extends JpaRepository<Accountant, Long> {

     public final static String UPDATE_ACCOUNTANT = "update Accountant acct SET acct.password =:password, acct.phoneNumber =:phoneNumber,"
            + " acct.state =:state, acct.postCode =:postCode, acct.country =:country where acct.id =:accountantId ";

@Query(UPDATE_ACCOUNTANT)
 @Modifying
 void updateAccountant(@Param("password") String password, @Param("phoneNumber") String phoneNumber,
         @Param("state") String state, @Param("postCode") String postCode, @Param("country") String country,
         @Param("accountantId") String accountantId);
}

In my accountantServiceImpl.java class I do

public void updateAccountant(Accountant acct) {

    accountantRepository.updateAccountant(acct.getPassword(), acct.getPhoneNumber(), acct.getState(),
            acct.getPostCode(), acct.getCountry(), acct.getId());       
}

hibernet save() will update only when primary key (most of the cases it is "id" field) is set in the object which you passing to save() method. If it does not find, it tries to insert a new record, which will succeed incase you don't have any DB level constraints.

JPD also provides to have your own custom implementation. You can do this.

  1. Create an interface AccountantRepositoryCustom and add the method you want eg updateAccountant .

    public interface AccountantRepositoryCustom { void updateAccountant(); }

  2. Extend your repository with this customer interface

public interface AccountantRepository extends JpaRepository<Accountant, Long> , AccountantRepositoryCustom

  1. Create an implementation class AccountantRepositoryImpl for AccountantRepositoryCustom

public class AccountantRepositoryImpl implements AccountantRepositoryCustom { @Override public void updateAccountant () { // you code here }

NOTE : The name of custom interface and implementation class are importantant as JPA follows some convesation to detent the mapping. So custom repository must ends with Custom and name of implementation class should end with Impl (you can override this settings, but its default which will do in most of the cases)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM