Olá eu comprei o livro JAVA EE do Alberto Sousa e na parte de associação Book x Author fazemos um select dos autores para salvar um book. Mas ao invés de no html ter uma lista de autores para escolher eu gostaria de o usuario pudesse inserir o codigo do autor (que já esta em uma tabela author) eu conseguisse verificar se existe e salvar o book. Como posso conseguir incluir o autor correto no book? Segue o código que estou em duvida:
HTML
<div>
<h:outputLabel>Autores</h:outputLabel>
<h:selectManyListbox value="#{adminBooksBean.selectedAuthorsIds}">
<f:selectItems value="#{adminBooksBean.authors}" var="author"
itemLabel="#{author.name}" itemValue="#{author.id}" />
</h:selectManyListbox>
</div>
<h:commandButton value="Gravar" action="#{adminBooksBean.save}" />
public class AuthorDAO {
@PersistenceContext
private EntityManager manager;
public List<Author> list() {
return manager.createQuery(
"select a from Author a order by a.name asc", Author.class)
.getResultList();
}
}
@Model
public class AdminBooksBean {
private Book product = new Book();
@Inject
private BookDAO productDAO;
@Inject
private AuthorDAO authorDAO;
private List<Author> authors = new ArrayList<Author>();
private List<String> selectedAuthorsIds = new ArrayList<>();
@Transactional
public void save(){
populateBookAuthor();
productDAO.save(product);
}
private void populateBookAuthor() {
selectedAuthorsIds.stream().map( (strId) -> {
return new Author(Integer.parseInt(strId));
}).forEach(product :: add);
}
public void setSelectedAuthorsIds(List<String> selectedAuthorsIds) {
this.selectedAuthorsIds = selectedAuthorsIds;
}
public List<String> getSelectedAuthorsIds() {
return selectedAuthorsIds;
}
public Book getProduct() {
return product;
}
public List<Author> getAuthors() {
return authors;
}
@PostConstruct
private void loadObjects(){
this.authors = authorDAO.list();
}
}
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
/**
* Hibernate only
*/
private Author(){
}
public Author(Integer id) {
this.id = id;
}
@Entity
public class Book {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String description;
private int numberOfPages;
private BigDecimal price;
@ManyToMany
private List<Author> authors = new ArrayList<>();