Spring
Spring

Reputation: 11865

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?

P.S 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();
    }
}

Upvotes: 0

Views: 2743

Answers (2)

nachokk
nachokk

Reputation: 14413

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();

Upvotes: 2

raeffs
raeffs

Reputation: 605

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();

Upvotes: 0

Related Questions