Relationship between entities

Asked

Viewed 756 times

1

I am unable to make the deletion of the selected object.

I have two classes, Autor and Livro, Basic example of working, to learn the use of Java Server Faces, so far everything well, functioning and etc. The problem is that in the relation @Manytomany, when called the function to delete the record, both author and book, launches a violation exception of Constraint.

Follows the part needed for evaluation:

Author Model

@Entity
public class Autor implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "autor_id", unique = true, nullable = false)
    private Integer id;

    @ManyToMany(mappedBy="autores")
    private List<Livro> livros;

    //Demais campos, getters e setters
}

Book Model

@Entity
public class Livro implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "livro_id", unique = true, nullable = false)
    private Integer id;

    @ManyToMany
    @JoinTable(name = "livro_autor", joinColumns = { 
        @JoinColumn(name = "livro_id", nullable = false, updatable = false) }, 
            inverseJoinColumns = { 
        @JoinColumn(name = "autor_id", nullable = false, updatable = false) })
    private List<Autor> autores = new ArrayList<Autor>();

    //Demais campos, getters e setters
}

Bean Autor

@ManagedBean
public class AutorBean {

    private Autor autor = new Autor();

    public void removeAutor(Autor autor){
        new DAO<Autor>(Autor.class).remove(autor);
    }

    //Demais métodos omitidos
}

Bean Book

@ManagedBean
@ViewScoped
public class LivroBean implements Serializable {

    private Livro livro = new Livro();
    private Integer autorId;
    public void removeLivro(Livro atualLivro){
        new DAO<Livro>(Livro.class).remove(atualLivro);     
    }

    //Demais métodos omitidos
}

DAO

public class DAO<T> {

    private final Class<T> classe;

    public DAO(Class<T> classe) {
        this.classe = classe;
    }

    public void remove(T t) {
        EntityManager em = new JPAUtil().getEntityManager();
        em.getTransaction().begin();
        em.remove(em.merge(t));

        em.getTransaction().commit();
        em.close();
    }
}

The relation creates a third table, expected, with the book_author name. When deleting, it throws this error:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
Cannot delete or update a parent row: a foreign key constraint fails (`banco`.`livro_autor`, CONSTRAINT `FK33E9E1BAF971CF8` FOREIGN KEY (`autor_id`) REFERENCES `autor` (`autor_id`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)

If necessary any other part of the code, just ask. The omitted methods are basic, other fields of the models, persistence, in the case of DAO, etc, all that I didn’t think would add anything to the question.

EDITION

I managed to get the field of the book deleted, what is happening now is that if there is a book for a given author, the author cannot be excluded, if there is no linked book, the author can be excluded.

1 answer

1


Solved. After asking the question here, the program executed the exclusion function of livro, what had not happened before to publish the question (Sigh). Even so, the exclusion function of autor I was making the same mistake. I tried to put:

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "livro_autor", joinColumns = { 
    @JoinColumn(name = "livro_id", nullable = false, updatable = false) }, 
        inverseJoinColumns = { 
    @JoinColumn(name = "autor_id", nullable = false, updatable = false) })
private List<Autor> autores = new ArrayList<Autor>();

...which also did not work.

I tried to pass Cascade to the entity of Autor, being like this:

@ManyToMany(mappedBy="autores", cascade = CascadeType.ALL)
private List<Livro> livros;

It didn’t work, but by changing CascadeType.ALL for CascadeType.REMOVE works.

The dissected error would be that it could not exclude a book that had bound book in the table livro_autor, and using Cascadetype.REMOVE, every time I remove an author, Hibernate automatically removes its linked books, which is expected of me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.