简体   繁体   中英

JPA, Can not delete record

I'm trying to delete multiple rows(if any) using JPA, and I get nullpointer exception. The parameter and the entity manager is not null. Any ideas what might be causing this exception?

PS The class is annotated @Transactional

@Override
public void removeAccount(String id) {
    try {

        int deleteRecords = entityManager.createQuery("DELETE from bankaccount b where b.accountNumber = ?1", BankAccount.class)
                .setParameter(1, accountNumber)
                .executeUpdate();

    } catch (Exception ex) {
        ex.getMessage();
    }
}

You don't have to put second parameter, also i put class name in query. BankAccount and String id is never used in the method.

int deleteRecords = entityManager.createQuery("DELETE from BankAccount b where b.accountNumber = ?1")
                .setParameter(1, accountNumber)
                .executeUpdate();

To delete an entity you should first query it and then pass it to the remove method.

For example if accountNumber is the BankAccounts primary key:

BankAccount account = entityManager.find(BankAccount.class, accountNumber);
entityManager.remove(account);

Update

If you can not use primary key and need to delete multiple entries you can use the code you provided, but do not make a typed query:

int numberOfRecords = entityManager
    .createQuery("DELETE from bankaccount b where b.accountNumber = ?1")
    .setParameter(1, accountNumber)
    .executeUpdate();

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