My favorites | Sign in
Project Logo
Project hosting will be READ-ONLY Wednesday at 8am PST due to brief network maintenance.
                
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/* Copyright (c) 2008-2009, Frank Schwarz <frank.schwarz@buschmais.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
* * Redistributions of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
* * Redistributions in binary form must reproduce
* the above copyright notice, this list of
* conditions and the following disclaimer in the
* documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package oopex.eclipselink1.jpa.queries;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import oopex.eclipselink1.jpa.queries.model.ForProfitCompany;
import oopex.eclipselink1.jpa.queries.model.NonProfitCompany;
import oopex.eclipselink1.jpa.queries.model.Person;

import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.expressions.ExpressionBuilder;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.mappings.ObjectReferenceMapping;
import org.eclipse.persistence.mappings.querykeys.OneToOneQueryKey;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.sessions.Session;

public class DowncastsMain {

public static void main(String[] args) {

EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("default");
try {
System.out.println("*** insert ***");
insert(entityManagerFactory);
System.out.println("*** query with JPQL ***");
querywithjpql(entityManagerFactory);
System.out.println("*** query with criteria ***");
querywithcriteria(entityManagerFactory);
System.out.println("*** query with query keys ***");
querywithquerykeys(entityManagerFactory);
System.out.println("*** delete ***");
delete(entityManagerFactory);
} finally {
entityManagerFactory.close();
System.out.println("*** finished ***");
}
}

private static void insert(EntityManagerFactory entityManagerFactory) {
EntityManager entityManager = entityManagerFactory
.createEntityManager();
try {
entityManager.getTransaction().begin();
Person person1 = new Person("Carla Peters");
Person person2 = new Person("John Reader");

NonProfitCompany company1 = new NonProfitCompany("Cats in need", "animal wellfare");
ForProfitCompany company2 = new ForProfitCompany("Oil Ltd.", "oil production");

person1.setEmployer(company1);
person2.setEmployer(company2);

entityManager.persist(person1);
entityManager.persist(person2);

entityManager.getTransaction().commit();
} finally {
if (entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
}
entityManager.close();
}
}

@SuppressWarnings("unchecked")
public static void querywithjpql(EntityManagerFactory entityManagerFactory) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
//SELECT p FROM Person p WHERE TYPE(p.company) = ForProfitCompany AND ((ForProfitCompany)p.company).sector LIKE '%oil%'
Query query = entityManager.createQuery("SELECT p FROM Person p, ForProfitCompany company WHERE company.sector LIKE '%oil%' AND p.employer = company");
List<Person> list = query.getResultList();
for (Person person : list) {
System.out.println(String.format("result: [%s, employer: [%s]]", person, person.getEmployer()));
}
} finally {
entityManager.close();
}
}

@SuppressWarnings("unchecked")
public static void querywithcriteria(EntityManagerFactory entityManagerFactory) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
final Session session = ((JpaEntityManager)entityManager).getSession();
ReadAllQuery query = new ReadAllQuery(Person.class);
ExpressionBuilder personE = query.getExpressionBuilder();
ExpressionBuilder forProfitCompanyE = new ExpressionBuilder(ForProfitCompany.class);
Expression join = personE.get("employer").equal(forProfitCompanyE);
query.setSelectionCriteria(join.and(forProfitCompanyE.get("sector").like("%oil%")));
Collection<Person> collection = (Collection<Person>) session.executeQuery(query);
for (Person person : collection) {
System.out.println(String.format("result: [%s, employer: [%s]]", person, person.getEmployer()));
}
} finally {
entityManager.close();
}
}

@SuppressWarnings("unchecked")
public static void querywithquerykeys(EntityManagerFactory entityManagerFactory) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
try {
final Session session = ((JpaEntityManager)entityManager).getSession();
{
// establish a (persistent!) one-to-one-query-key from Person to ForProfitCompany as profitCompanyEmployer
ClassDescriptor personDescriptor = session.getDescriptor(Person.class);
ObjectReferenceMapping employerMapping = (ObjectReferenceMapping) personDescriptor.getMappingForAttributeName("employer");
ExpressionBuilder personE = new ExpressionBuilder();
DatabaseField primaryKeyField = employerMapping.getReferenceDescriptor().getPrimaryKeyFields().get(0);
DatabaseField foreignKeyField = employerMapping.getForeignKeyFields().get(0);
Expression expression = personE.getField(primaryKeyField).equal(personE.getParameter(foreignKeyField));
OneToOneQueryKey profitCompanyEmployer = new OneToOneQueryKey();
profitCompanyEmployer.setName("profitCompanyEmployer");
profitCompanyEmployer.setDescriptor(personDescriptor);
profitCompanyEmployer.setReferenceClass(ForProfitCompany.class);
profitCompanyEmployer.setJoinCriteria(expression);
personDescriptor.addQueryKey(profitCompanyEmployer);
}
ReadAllQuery query = new ReadAllQuery(Person.class);
query.setShouldOuterJoinSubclasses(true);
ExpressionBuilder personE = query.getExpressionBuilder();
// now use that query key as an ordinary field
query.setSelectionCriteria(personE.get("profitCompanyEmployer").get("sector").like("%oil%"));
Collection<Person> collection = (Collection<Person>) session.executeQuery(query);
for (Person person : collection) {
System.out.println(String.format("result: [%s, employer: [%s]]", person, person.getEmployer()));
}
} finally {
entityManager.close();
}
}

@SuppressWarnings("unchecked")
private static void delete(EntityManagerFactory entityManagerFactory) {
EntityManager entityManager = entityManagerFactory
.createEntityManager();
try {
entityManager.getTransaction().begin();
Query pQuery = entityManager.createQuery("SELECT p FROM Person p");
Collection<Person> pCollection = (Collection<Person>) pQuery
.getResultList();
for (Person person : pCollection) {
entityManager.remove(person);
}
entityManager.getTransaction().commit();
} finally {
if (entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
}
entityManager.close();
}
}
}
Show details Hide details

Change log

r197 by frank.sc...@buschmais.com on Jun 05, 2009   Diff
Testing Doug Clarke's proposal of using
query keys for downcasts
Go to: 
Project members, sign in to write a code review

Older revisions

r154 by frank.sc...@buschmais.com on Jan 11, 2009   Diff
clarifying the sample's intention
r127 by frank.sc...@buschmais.com on Dec 22, 2008   Diff
downcast-equivalent in queries
All revisions of this file

File info

Size: 8353 bytes, 192 lines
Hosted by Google Code