1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package ch.elca.el4j.tests.services.persistence.jpa;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.commons.lang.StringUtils;
23 import org.junit.Assert;
24 import org.junit.Test;
25
26 import ch.elca.el4j.services.persistence.jpa.criteria.QueryBuilder;
27 import ch.elca.el4j.services.persistence.jpa.criteria.SortOrder;
28
29
30
31
32
33
34
35
36
37 public class QueryBuilderTest {
38
39 public void testCorrectSql(String expectedSQL, String position, Double salMin, Double salMax, List<String> depIds) {
40 QueryBuilder builder = QueryBuilder.select("dep.NAME", "emp.name");
41 QueryBuilder subQueryBuilder = QueryBuilder.select("1");
42 subQueryBuilder.from("Dual ").startAnd().ifNotNull("1 <> {p}", 2).end().endBuilder();
43
44 builder.from("DEPARTMENT dep").innerJoin("EMPLOYEE emp", "dep.ID = emp.DEPARTMENT_ID").innerJoin(
45 "UNIVERSITY unv", "unv.ID = dep.UNV_ID").startOr().ifNotNull("emp.position = {p}", position).startAnd()
46 .ifNotNull("emp.SALARY > {p}", salMin).ifNotNull("emp.SALARY < {p}", salMax).end().exist(subQueryBuilder)
47 .ifNotNull("dep.ID in {p}", depIds).end()
48
49 .orderBy(SortOrder.ASC, "dep.ID").endBuilder();
50 String actualQuery = builder.toString();
51
52 String expectedSQLProcessed = StringUtils.deleteWhitespace(expectedSQL).toUpperCase().trim();
53 actualQuery = StringUtils.deleteWhitespace(actualQuery).toUpperCase().trim();
54
55 Assert.assertEquals(expectedSQLProcessed, actualQuery);
56
57
58 }
59
60 @Test
61 public void testCorrectSql1() {
62 String expectedSQL1 = "SELECT dep.NAME, emp.NAME" + " FROM DEPARTMENT dep"
63 + " JOIN EMPLOYEE emp ON (dep.ID = emp.DEPARTMENT_ID)" + " JOIN UNIVERSITY unv ON (unv.ID = dep.UNV_ID)"
64 + " WHERE emp.POSITION = {p}" + " OR (emp.SALARY > {p} AND emp.SALARY < {p})"
65 + " OR EXISTS (SELECT 1 FROM DUAL WHERE 1 <> {p}) ORDER BY DEP.ID ASC";
66
67 testCorrectSql(expectedSQL1, "pos", new Double(200), new Double(200), null);
68 }
69
70 @Test
71 public void testCorrectSql2() {
72 String expectedSQL2 = "SELECT dep.NAME, emp.NAME" + " FROM DEPARTMENT dep"
73 + " JOIN EMPLOYEE emp ON (dep.ID = emp.DEPARTMENT_ID)" + " JOIN UNIVERSITY unv ON (unv.ID = dep.UNV_ID)"
74 + " WHERE EXISTS (SELECT 1 FROM DUAL WHERE 1 <> {p})" + " ORDER BY DEP.ID ASC";
75
76 testCorrectSql(expectedSQL2, "", null, null, new ArrayList<String>());
77 }
78
79 @Test
80 public void testCorrectSql3() {
81 String expectedSQL3 = "SELECT dep.NAME, emp.NAME" + " FROM DEPARTMENT dep"
82 + " JOIN EMPLOYEE emp ON (dep.ID = emp.DEPARTMENT_ID)" + " JOIN UNIVERSITY unv ON (unv.ID = dep.UNV_ID)"
83 + " WHERE EXISTS (SELECT 1 FROM DUAL WHERE 1 <> {p}) OR dep.ID in {p}" + " ORDER BY DEP.ID ASC";
84
85 List<String> idList = new ArrayList<String>();
86 idList.add("1");
87
88 testCorrectSql(expectedSQL3, null, null, null, idList);
89 }
90
91 }