PageRenderTime 29ms CodeModel.GetById 10ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 1ms

/testing/library/src/com/google/appengine/library/JPABookDataService.java

http://datanucleus-appengine.googlecode.com/
Java | 71 lines | 54 code | 11 blank | 6 comment | 2 complexity | b03a6222dcfc51444370d0914490e5bd MD5 | raw file
 1// Copyright 2008 Google Inc. All Rights Reserved.
 2
 3package com.google.appengine.library;
 4
 5import java.util.Collection;
 6
 7import javax.persistence.EntityManager;
 8import javax.persistence.EntityManagerFactory;
 9import javax.persistence.EntityTransaction;
10import javax.persistence.Persistence;
11import javax.persistence.Query;
12
13/**
14 * TODO: figure out why EntityTransaction is needed for JPA.
15 *
16 * @author kjin@google.com (Kevin Jin)
17 */
18final class JPABookDataService implements BookDataService {
19
20  private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("book");
21  private final EntityManager em = emf.createEntityManager();
22  private static final String FROM_CLAUSE = "SELECT FROM " + Book.class.getName();
23
24  @SuppressWarnings("unchecked")
25  public Iterable<Book> asIterable(String jpqlQuery) {
26    return em.createQuery(FROM_CLAUSE + jpqlQuery).getResultList();
27  }
28
29  @SuppressWarnings("unchecked")
30  public Iterable<Book> asIterable(String jpqlQuery, int limit, int offset) {
31    Query query = em.createQuery(FROM_CLAUSE + jpqlQuery);
32    query.setMaxResults(limit);
33    query.setFirstResult(offset);
34    return query.getResultList();
35  }
36
37  @SuppressWarnings("unchecked")
38  public int countEntities(String jpqlQuery) {
39    return ((Collection) asIterable(jpqlQuery)).size();
40  }
41
42  public void delete(Book book) {
43    EntityTransaction txn = em.getTransaction();
44    try {
45      txn.begin();
46      em.remove(book);
47      txn.commit();
48    } finally {
49      if (txn.isActive()) {
50        txn.rollback();
51      }
52    }
53  }
54
55  public void put(Book book) {
56    EntityTransaction txn = em.getTransaction();
57    try {
58      txn.begin();
59      em.persist(book);
60      txn.commit();
61    } finally {
62      if (txn.isActive()) {
63        txn.rollback();
64      }
65    }
66  }
67
68  public void close() {
69    em.close();
70  }
71}