Foreing key Book x Authors


#1

Hello all, i m new in Java and Hibernate and in my school we have learned how to create a foreign key but in the exercises we have a relation between a book and authors and a list of authors to choose in order to save a book . I appreciate if anyone coud explain me how can I, instead of select the authors, can insert author id in and save a book with the correct author. Following the codes i have:

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<>();

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}" />

#2

Check out the Hibernate User Guide for more details about how you can use this framework.

Without reading the official documentation, you are going to bump into many issues that can lead to countless hours of debugging.


#3

Thank you Vlad i took a look and probably the answer will be at the 9. JNDI chapter. Tks for help