@Entity
@Table(name = "AUTHOR")
public class Author {
private long id;
private String name;
private String email;
public Author() {
}
public Author(String name, String email) {
this.name = name;
this.email = email;
}
@Id
@Column(name = "AUTHOR_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
}
//setter/getter
}
@Entity
@Table(name = "BOOK")
public class Book {
private long id;
private String title;
private String description;
private Date publishedDate;
private List<Author> author = new
ArrayList<Author>();
public Book() {
}
@Id
@Column(name = "BOOK_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
}
@Temporal(TemporalType.DATE)
@Column(name = "PUBLISHED")
public Date
getPublishedDate() {
return publishedDate;
}
@OneToMany(cascade =
CascadeType.ALL)
@JoinColumn(name = "BOOK_ID")
public List<Author>
getAuthor() {
return author;
}
//setter/getter
}
public class BooksTest {
public static void main(String[] args) {
SessionFactory
sessionFactory = HibernateUtils.getSessionFactory();
Session
session = sessionFactory.openSession();
try{
session.beginTransaction();
// creates a Book
entity
Book
newBook = new Book();
newBook.setTitle("Pro PHP
MVC");
newBook.setDescription("Php MVC
Book");
newBook.setPublishedDate(new Date());
List<Author>
authors= new
ArrayList<Author>();
authors.add(new Author("Shambhu
Kumar", "shambhu@gmail.com"));
authors.add(new Author("Ravi
Kumar", "Ravi@gmail.com"));
newBook.setAuthor(authors);
// persists the
book entity
Long
bookId = (Long) session.save(newBook);
// gets the book
entity back
Book
book = (Book) session.get(Book.class, bookId);
System.out.println("Book's Title:
" +
book.getTitle());
System.out.println("Book's
Description: " + book.getTitle());
book.getAuthor().add(new Author("Shambhu1", "shambhu@gmail.com"));
book.getAuthor().add(new
Author("Ravi1", "Ravi@gmail.com"));
session.update(book);
List<Author>
authorsList = book.getAuthor();
for(Author author:authorsList){
System.out.println("Name: " + author.getName());
System.out.println("Mail: " + author.getEmail());
}
}
finally{
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
}
0 comments: