Warm tip: This article is reproduced from stackoverflow.com, please click
hibernate java spring-mvc

How to delete an entity by two attributes in Hibernate?

发布于 2020-03-27 10:26:13

i've come across a problem in these days, which would be simple for other languages, like php, but the project I'm doing is in Spring MVC. The question is: In Spring MVC, how can i delete an entity with two attributes ids coming from this entity?

Example: "Delete from Entity Where id1 =: id1 and id2 =: id2" (This is the query that i want)

Thanks for the attention.

What i was trying ...

public boolean remover(int idUsuario, int idCategoria) {

    EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
    EntityManager manager = factory.createEntityManager();


    String hqlStr = "delete from UsuarioEscolheCategoria where idUsuario = :idUsuario and idCategoria = :idCategoria";

    Query query = null; 


    try {

        query = manager.createQuery(hqlStr);

        query.setParameter("idUsuario", idUsuario);
        query.setParameter("idCategoria", idCategoria);

        query.executeUpdate();

        manager.close();
        factory.close();

        return true;

    }catch(Exception e) {
        return false;
    }

}

If i take the exception, it gives me:

Exception error

Questioner
Henrique N. Mendes
Viewed
65
83.9k 2019-07-05 13:07
String hqlStr = "delete from UsuarioEscolheCategoria where usuario.idUsuario = :idUsuario and categoria.idCategoria = :idCategoria";

The important part is usuario.idUsuario and categoria.idCategoria. That way you're making a reference to the attribute type Usuario, which is on your model class.