Skip to content

Commit

Permalink
[playframework#1232] Fix JPABinder to bind multiple ids
Browse files Browse the repository at this point in the history
  • Loading branch information
pepite committed Dec 1, 2011
1 parent 7a4e4d7 commit f45fe8f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 9 deletions.
32 changes: 25 additions & 7 deletions framework/src/play/db/jpa/JPAPlugin.java
Expand Up @@ -47,16 +47,34 @@ public Object bind(RootParamNode rootParamNode, String name, Class clazz, java.l

ParamNode paramNode = rootParamNode.getChild(name, true);

String keyName = Model.Manager.factoryFor(clazz).keyName();
String[] ids = paramNode.getChild(keyName, true).getValues();
String[] keyNames = new JPAModelLoader(clazz).keyNames();
ParamNode[] ids = new ParamNode[keyNames.length];
// Collect the matching ids
int i = 0;
for (String keyName : keyNames) {
ids[i++] = paramNode.getChild(keyName, true);
}
if (ids != null && ids.length > 0) {
try {
Query query = JPA.em().createQuery("from " + clazz.getName() + " o where o." + keyName + " = ?");
EntityManager em = JPA.em();
String q = "from " + clazz.getName() + " o where";
for (String keyName : keyNames) {
q += " o." + keyName + " = ? and " ;
}
if (q.length() > 4) {
q = q.substring(0, q.length() - 4);
}
Query query = em.createQuery(q);
// The primary key can be a composite.
int i = 1;
Class pk = Model.Manager.factoryFor(clazz).keyType();
for (String id : ids) {
query.setParameter(i++, Binder.directBind(rootParamNode.getOriginalKey(), annotations, id, pk, null));
Class[] pk = new JPAModelLoader(clazz).keyTypes();
int j = 0;
for (ParamNode id : ids) {
if (id.getValues() == null || id.getValues().length == 0) {
// We have no ids, it is a new entity
return GenericModel.create(rootParamNode, name, clazz, annotations);
}
query.setParameter(j + 1, Binder.directBind(id.getOriginalKey(), annotations, id.getValues()[0], pk[j++], null));

}
Object o = query.getSingleResult();
return GenericModel.edit(rootParamNode, name, o, annotations);
Expand Down
4 changes: 3 additions & 1 deletion samples-and-tests/just-test-cases/test/YamlTest.java
Expand Up @@ -10,7 +10,9 @@ public void testYamlLoading() {
Fixtures.load("yamlTestData.yml");
YamlModel ym = YamlModel.all().first();
assertEquals("Morten", ym.name);


assertEquals(DataWithCompositeKey.all().fetch().size(), 2);

//check binary
assertEquals("This String is stored in yaml file using base64", new String(ym.binaryData));

Expand Down
10 changes: 9 additions & 1 deletion samples-and-tests/just-test-cases/test/yamlTestData.yml
@@ -1,4 +1,12 @@
YamlModel(ym1):
id: 1
name: Morten
binaryData: !!binary VGhpcyBTdHJpbmcgaXMgc3RvcmVkIGluIHlhbWwgZmlsZSB1c2luZyBiYXNlNjQ=
binaryData: !!binary VGhpcyBTdHJpbmcgaXMgc3RvcmVkIGluIHlhbWwgZmlsZSB1c2luZyBiYXNlNjQ=

DataWithCompositeKey(1):
key1: a
key2: b

DataWithCompositeKey(2):
key1: a
key2: c

0 comments on commit f45fe8f

Please sign in to comment.