01: /**
02: *
03: * Licensed to the Apache Software Foundation (ASF) under one or more
04: * contributor license agreements. See the NOTICE file distributed with
05: * this work for additional information regarding copyright ownership.
06: * The ASF licenses this file to You under the Apache License, Version 2.0
07: * (the "License"); you may not use this file except in compliance with
08: * the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */package org.superbiz.servlet;
18:
19: import javax.persistence.EntityManagerFactory;
20: import javax.persistence.PersistenceUnit;
21: import javax.persistence.EntityManager;
22: import javax.persistence.EntityTransaction;
23: import javax.persistence.Query;
24: import javax.servlet.ServletException;
25: import javax.servlet.ServletOutputStream;
26: import javax.servlet.http.HttpServlet;
27: import javax.servlet.http.HttpServletRequest;
28: import javax.servlet.http.HttpServletResponse;
29: import java.io.IOException;
30:
31: public class JpaServlet extends HttpServlet {
32: @PersistenceUnit(name="jpa-example")
33: private EntityManagerFactory emf;
34:
35: protected void doGet(HttpServletRequest request,
36: HttpServletResponse response) throws ServletException,
37: IOException {
38: response.setContentType("text/plain");
39: ServletOutputStream out = response.getOutputStream();
40:
41: out.println("@PersistenceUnit=" + emf);
42:
43: EntityManager em = emf.createEntityManager();
44: EntityTransaction transaction = em.getTransaction();
45: transaction.begin();
46:
47: JpaBean jpaBean = new JpaBean();
48: jpaBean.setName("JpaBean");
49: em.persist(jpaBean);
50:
51: transaction.commit();
52: transaction.begin();
53:
54: Query query = em
55: .createQuery("SELECT j FROM JpaBean j WHERE j.name='JpaBean'");
56: jpaBean = (JpaBean) query.getSingleResult();
57: out.println("Loaded " + jpaBean);
58:
59: em.remove(jpaBean);
60:
61: transaction.commit();
62: transaction.begin();
63:
64: query = em
65: .createQuery("SELECT count(j) FROM JpaBean j WHERE j.name='JpaBean'");
66: int count = ((Number) query.getSingleResult()).intValue();
67: if (count == 0) {
68: out.println("Removed " + jpaBean);
69: } else {
70: out.println("ERROR: unable to remove" + jpaBean);
71: }
72:
73: transaction.commit();
74: }
75: }
|