01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with 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,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */
19: package hellojpa;
20:
21: import java.util.*;
22: import javax.persistence.*;
23:
24: /**
25: * A very simple, stand-alone program that stores a new entity in the
26: * database and then performs a query to retrieve it.
27: */
28: public class Main {
29:
30: @SuppressWarnings("unchecked")
31: public static void main(String[] args) {
32: // Create a new EntityManagerFactory using the System properties.
33: // The "hellojpa" name will be used to configure based on the
34: // corresponding name in the META-INF/persistence.xml file
35: EntityManagerFactory factory = Persistence
36: .createEntityManagerFactory("hellojpa", System
37: .getProperties());
38:
39: // Create a new EntityManager from the EntityManagerFactory. The
40: // EntityManager is the main object in the persistence API, and is
41: // used to create, delete, and query objects, as well as access
42: // the current transaction
43: EntityManager em = factory.createEntityManager();
44:
45: // Begin a new local transaction so that we can persist a new entity
46: em.getTransaction().begin();
47:
48: // Create and persist a new Message entity
49: em.persist(new Message("Hello Persistence!"));
50:
51: // Commit the transaction, which will cause the entity to
52: // be stored in the database
53: em.getTransaction().commit();
54:
55: // It is always good practice to close the EntityManager so that
56: // resources are conserved.
57: em.close();
58:
59: // Create a fresh, new EntityManager
60: EntityManager em2 = factory.createEntityManager();
61:
62: // Perform a simple query for all the Message entities
63: Query q = em2.createQuery("select m from Message m");
64:
65: // Go through each of the entities and print out each of their
66: // messages, as well as the date on which it was created
67: for (Message m : (List<Message>) q.getResultList()) {
68: System.out.println(m.getMessage() + " (created on: "
69: + m.getCreated() + ")");
70: }
71:
72: // Again, it is always good to clean up after ourselves
73: em2.close();
74: factory.close();
75: }
76: }
|