Relationship between entities

1

I can not delete the selected object.

I have two classes, Autor and Livro , basic operating example, to learn how to use Java Server Faces, so far so good, working and so on. The problem is that in the @ManyToMany relation, when calling the function to delete the record, both author and book, throws a constraint violation exception.

Here is the part needed for evaluation:

Author Template

@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 template

@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 Author

@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 name book_author. When deleting, throw 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 you need 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, everything I did not think would add anything to the question.

EDITION

I was able 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 can not be deleted, if there is no linked book, the author can be excluded.

    
asked by anonymous 22.09.2014 / 14:34

1 answer

1

Solved. After asking the question here, the program ran the exclude function of livro , which had not happened before (sigh) . Even so, the exclude function of autor was giving the same error. I tried putting:

@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 Autor entity, thus:

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

It did not work, but changing CascadeType.ALL to CascadeType.REMOVE works.

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

    
22.09.2014 / 16:12