1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| package test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class BookManager implements BookManager_Interface {
private Collection books;
@PersistenceContext
EntityManager em;
public void deleteBookById(long id) {
em.remove(em.find(Book2.class, id));
}
public Collection getAllBooks() {
// TODO Auto-generated method stub
loadData();
return books;
}
public void init() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Random random = new Random();
em.persist(new Book2(random.nextLong(), "David Roos", "Struts book", true));
em.persist(new Book2(random.nextLong(), "Micheal Jackson", "Java book", true));
em.persist(new Book2(random.nextLong(), "Bruce Lee", "Java2 book", false));
em.persist(new Book2(random.nextLong(), "Tom Jones" ,"EJB book", true));
em.persist(new Book2(random.nextLong(), "Mc Donald", "Jboss for beginners", false));
em.persist(new Book2(random.nextLong(), "Lars Mars", "Using Myeclipse for cooking", true));
em.persist(new Book2(random.nextLong(), "Mary Jane", "EJB or spending your weekends", true));
}
public Book2 loadBookById(long id) {
// TODO Auto-generated method stub
return (Book2)em.find(Book2.class, id);
}
public void loadData() {
// TODO Auto-generated method stub
books = (Collection)em.createQuery("from Book2");
if (books == null)
init();
}
public long saveToDB(Book2 book) {
loadData();
// laliluna 04.10.2004 loop over collection and trying to find the book
boolean bookExist = false;
ArrayList booksNew = (ArrayList) books;
int index = 0;
for (Iterator iter = books.iterator(); iter.hasNext();) {
Book2 element = (Book2) iter.next();
// laliluna 04.10.2004 if book is found do an update
if (element.getId() == book.getId()) {
booksNew.set(index, book);
bookExist = true;
break;
}
index++;
}
books = booksNew;
// laliluna 04.10.2004 if book is not found, create a new book
if (bookExist == false) {
Random random = new Random();
book.setId(random.nextLong());
em.persist(book);
}
// laliluna 04.10.2004 save to DB ;-)
return book.getId();
}
} |