Home > Mobile >  Cannot delete a database entry with a primary key of 0 using JPA (MySQL)
Cannot delete a database entry with a primary key of 0 using JPA (MySQL)

Time:07-31

I am trying to delete an element with primary key = 0 but nothing is happening. I have a set of test data that I uploaded in a data.sql file. I thought maybe there might some reference to this entry in another table that I overlooked, so I just dropped all other tables except element and it is still not deleting. I have successfully deleted all other rows, but zero just won't go.

To confirm this, I went into Sqlectron (sql client) and tried to run the statement there, and it works. It just doesn't work using JPA. What's going on here?

@Entity
@Table(name = "element")
@NamedEntityGraph(name = graph.element.accounts, attributeNodes = @NamedAttributeNode("accounts"))
public class Element extends Entry {

    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "name", nullable = false, unique = true)
    @NotBlank
    private String name;

    @OneToMany(mappedBy = "element", cascade = CascadeType.PERSIST)
    private List<Account> accounts;

    // constructor, getters, setters, equals, hashcode
}
@Service
public class ElementService {

    private final ElementDAO DAO;

    @Autowired
    public ElementService(ElementDAO DAO) {
        this.DAO = DAO;
    }

    public Element find(int id) {
        return DAO.findById(id).orElse(null);
    }

    public void delete(Element element) {
        DAO.delete(element);
    }
}
@Repository
public interface ElementDAO extends PagingAndSortingRepository<Element,Integer> {
}
@SpringBootTest
@ActiveProfiles("test")
class ElementServiceTests {

    @Autowired
    private ElementService svc;

    @Test
    public void test() {
        svc.delete(new Element(0, "Other"));
        assertNull(svc.find(0));
    }
}
org.opentest4j.AssertionFailedError: 
Expected :null
Actual   :Element{id=0, name='Other'}
INSERT INTO element
(id, name, created_at, created_by)
VALUES
(1, 'Asset', CURRENT_DATE, 'DBA'),
(2, 'Liability', CURRENT_DATE, 'DBA'),
(3, 'Equity', CURRENT_DATE, 'DBA'),
(4, 'Income', CURRENT_DATE, 'DBA'),
(5, 'Expense', CURRENT_DATE, 'DBA'),
(0, 'Other', CURRENT_DATE, 'DBA');
-- works in sqlectron
delete from element where id = 0;

CodePudding user response:

0 has the special meaning of unassigned identifier when the id type is a primitive. That's because is not possible to use null with primitive types.

Before deleting the entity, Spring checks if the id of the entity is assigned and - because your entity has id 0 - decides that it's not, it's a new entity and there's nothing to delete.

My suggestion is to avoid using primitive types as id, or make sure that an id is always bigger than 0.

  • Related