Announcement Announcement Module
Collapse
No announcement yet.
Persist entity with one-to-many relationship Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Persist entity with one-to-many relationship

    Hi, if I have the following pojos:
    Code:
    @Entity
    @Table(name="authors")
    public class Author {
    
    	private Integer id;
    	private String name;
    	private List<Book> bibliography;
    
    	@Id
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	public Integer getId() {
    		return this.id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return this.name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	@OneToMany(mappedBy="author", cascade=CascadeType.ALL)
    	public List<Book> getBibliography() {
    		return this.bibliography;
    	}
    
    	public void setBibliography(List<Book> bibliography) {
    		this.bibliography = bibliography;
    	}
    }
    
    @Entity
    @Table(name="books")
    public class Book {
    
    	private Integer id;
    	private String title;
    	private Author author;
    
    	@Id
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	public Integer getId() {
    		return this.id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getTitle() {
    		return this.title;
    	}
    
    	public void setTitle(String title) {
    		this.title = title;
    	}
    
    	@ManyToOne
    	@JoinColumn(name="author_id")
    	public Author getAuthor() {
    		return this.author;
    	}
    
    	public void setAuthor(Author author) {
    		this.author = author;
    	}
    }
    How do I go about persisting an Author-class with a collection of books (a bibliography) inside it? I thought that I only had to persist the Author-instance (i.e. session.merge(author)) and the mappings would take care of the Book-instances in the list, but apparently this isn't the case.

    Edit: Nvm, I forgot to set the author attribute in the Book-instance. -.-'
    Last edited by Kristofer; Mar 3rd, 2010, 07:09 AM. Reason: Solution found
Working...
X