/
QueryDslBetweenTest.java
85 lines (71 loc) · 2.67 KB
/
QueryDslBetweenTest.java
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
package sandbox;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.support.Expressions;
import com.mysema.query.types.Ops;
import com.mysema.query.types.expr.BooleanExpression;
import com.mysema.query.types.expr.SimpleExpression;
import org.junit.After;
import org.junit.Before;
import querydsl.MyTable;
import querydsl.QMyTable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import static org.junit.Assert.assertEquals;
public class QueryDslBetweenTest {
private EntityManagerFactory emf;
private EntityManager em;
@Before
public void setUp() throws Exception {
emf = Persistence.createEntityManagerFactory("myPU");
em = emf.createEntityManager();
em.getTransaction().begin();
{
final MyTable expected = new MyTable();
expected.setCol1(10);
expected.setCol2(20);
em.persist(expected);
}
{
final MyTable unexpected = new MyTable();
unexpected.setCol1(30);
unexpected.setCol2(40);
em.persist(unexpected);
}
em.getTransaction().commit();
}
// http://stackoverflow.com/a/7662029/3591946
@org.junit.Test
public void betweenRedundant() throws Exception {
final int constant = 10;
final QMyTable m = QMyTable.myTable;
final SimpleExpression<Boolean> operation = Expressions.operation(Boolean.class, Ops.BETWEEN,
Expressions.constant(constant), m.col1, m.col2);
// This yields:
// SELECT ID, COL1, COL2 FROM MYTABLE WHERE ((? BETWEEN COL1 AND COL2) = ?)
// bind => [10, true]
final MyTable actual = new JPAQuery(em).from(m).where(operation.eq(true)).uniqueResult(m);
assert actual != null;
assertEquals(10, (int) actual.getCol1());
assertEquals(20, (int) actual.getCol2());
}
@org.junit.Test
public void betweenImproved() throws Exception {
final int constant = 10;
final QMyTable m = QMyTable.myTable;
final BooleanExpression operation = Expressions.booleanOperation(Ops.BETWEEN,
Expressions.constant(constant), m.col1, m.col2);
// This yields:
// SELECT ID, COL1, COL2 FROM MYTABLE WHERE (? BETWEEN COL1 AND COL2)
// bind => [10]
final MyTable actual = new JPAQuery(em).from(m).where(operation).uniqueResult(m);
assert actual != null;
assertEquals(10, (int) actual.getCol1());
assertEquals(20, (int) actual.getCol2());
}
@After
public void tearDown() throws Exception {
em.close();
emf.close();
}
}