Many To Many JSF and JPA

0

Dear friends, I ask you to help me solve the following question: I have two entities in a many-to-many relationship

@Entity
public class Livro implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Long id;

    @NotBlank
    @Column (nullable = false)
    private String titulo;

    @Column (nullable = true)
    private String subtitulo;

    @NotEmpty
    @ManyToMany (mappedBy = "livros", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Autor> autores;
    private Integer anoLancamento;
    private String isbn;
    private Integer numeroEdicao;
    private boolean disponivel;

    @NotNull
    private Integer copias;
    private Date dataCadastro;

    @NotNull
    @ManyToOne
    @JoinColumn (name = "categoria_livro_id", nullable = false)
    private CategoriaLivro categoriaLivro;

    public Livro() {
    }
    //getters e setters, equals e hashCode

@Entity
public class Autor implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Long id;
    private String nome;

    @ManyToMany (cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    @JoinTable(name = "autor_livro", joinColumns = { @JoinColumn(name = "autor_id") }, inverseJoinColumns = {
            @JoinColumn(name = "livro_id") })
    private List<Livro> livros;

    @NotEmpty
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "data_cadastro", nullable = false)
    private Date dataCadastro;

In Managed Bean I have the following:

@Named
@ViewScoped
public class LivroBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private Livro livro = new Livro();

    private List<Autor> todosAutores;

    private List<CategoriaLivro> todasCategorias;

    private List<Autor> autoresEscolhidos;

    @Inject
    private Autores autores;

    @Inject
    private LivroCategorias livroCategorias;

    @Inject
    private LivroService livroService;

    public void guardar() {
        FacesContext context = FacesContext.getCurrentInstance();

        try {
            if (autoresEscolhidos != null && autoresEscolhidos.size() > 0) {
                livro.setAutores(autoresEscolhidos);

                for (Autor a : autoresEscolhidos) {
                    a.getLivros().add(livro);
                }
            }

            livroService.guardar(livro);
            context.addMessage(null, new FacesMessage("Livro cadastrado com sucesso"));
        } catch (Exception e) {
            FacesMessage mensagem = new FacesMessage(e.getMessage());
            mensagem.setSeverity(FacesMessage.SEVERITY_ERROR);
            context.addMessage(null, mensagem);
        }
    }

In Author Converter I have the following:

@FacesConverter(forClass = Autor.class)
public class AutorConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
        if (value == null || value.isEmpty())
            return null;

        Long id = Long.valueOf(value);
        EntityManager manager = JpaUtil.getEntityManager();
        //Autores autores = new Autores(manager);
        Autor autor = manager.find(Autor.class, id);

        return autor;
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
        Autor autor = (Autor) value;
        if (autor == null || autor.getId() == null)
            return null;

        return String.valueOf(autor.getId());
    }

In XHTML I have the following:

<p:outputLabel value="Autor(es)" />
                <p:selectManyMenu value="#{livroBean.autoresEscolhidos}" label="Autor(es)" filter="true"
                    filterMatchMode="contains" showCheckbox="true">
                    <f:selectItems value="#{livroBean.todosAutores}" var="autor"
                        itemValue="#{autor}" itemLabel="#{autor.nome}" />
                </p:selectManyMenu>

<p:commandButton value="Cadastrar" action="#{livroBean.guardar()}" update="@form" />

When I click on the Register button it shows the following message on the page:

  

java.lang.String can not be cast to mz.co.mu.org.biblioteca.model.Autor.

Here is the pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>mz.co.muianga.biblioteca</groupId>
    <artifactId>biblioteca-jsf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Projecto Biblioteca</name>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.glassfish/javax.faces -->
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.faces</artifactId>
            <version>2.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.17.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.primefaces/primefaces -->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>6.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.10.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.primefaces.themes/casablanca -->
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>bootstrap</artifactId>
            <version>1.0.10</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.weld.servlet</groupId>
            <artifactId>weld-servlet-core</artifactId>
            <version>3.0.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.omnifaces/omnifaces -->
        <dependency>
            <groupId>org.omnifaces</groupId>
            <artifactId>omnifaces</artifactId>
            <version>1.14.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.jboss/jandex -->
        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.3.Final</version>
        </dependency>

    </dependencies>

    <properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

The Servlet Container is Tomcat 9.

    
asked by anonymous 01.06.2018 / 11:11

0 answers