1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package examples.spring;
17
18 import static examples.spring.PersonDynamicSqlSupport.*;
19 import static org.assertj.core.api.Assertions.assertThat;
20 import static org.mybatis.dynamic.sql.SqlBuilder.*;
21
22 import java.util.List;
23
24 import org.junit.jupiter.api.Test;
25 import org.mybatis.dynamic.sql.delete.DeleteModel;
26 import org.mybatis.dynamic.sql.render.RenderingStrategies;
27 import org.mybatis.dynamic.sql.select.SelectModel;
28 import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
29 import org.mybatis.dynamic.sql.update.UpdateModel;
30 import org.mybatis.dynamic.sql.util.Buildable;
31 import org.mybatis.dynamic.sql.util.spring.NamedParameterJdbcTemplateExtensions;
32 import org.mybatis.dynamic.sql.where.WhereApplier;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
35 import org.springframework.transaction.annotation.Transactional;
36
37 @SpringJUnitConfig(classes = SpringConfiguration.class)
38 @Transactional
39 class ReusableWhereTest {
40
41 @Autowired
42 private NamedParameterJdbcTemplateExtensions template;
43
44 @Test
45 void testCount() {
46 Buildable<SelectModel> countStatement = countFrom(person)
47 .applyWhere(commonWhere);
48
49 long rows = template.count(countStatement);
50 assertThat(rows).isEqualTo(3);
51 }
52
53 @Test
54 void testDelete() {
55 Buildable<DeleteModel> deleteStatement = deleteFrom(person)
56 .applyWhere(commonWhere);
57
58 long rows = template.delete(deleteStatement);
59
60 assertThat(rows).isEqualTo(3);
61 }
62
63 @Test
64 void testSelect() {
65 Buildable<SelectModel> selectStatement = select(person.allColumns())
66 .from(person)
67 .applyWhere(commonWhere);
68
69 List<PersonRecord> rows = template.selectList(selectStatement, PersonTemplateTest.personRowMapper);
70
71 assertThat(rows).hasSize(3);
72 }
73
74 @Test
75 void testUpdate() {
76 Buildable<UpdateModel> updateStatement = update(person)
77 .set(occupation).equalToStringConstant("worker")
78 .applyWhere(commonWhere);
79
80 int rows = template.update(updateStatement);
81
82 assertThat(rows).isEqualTo(3);
83 }
84
85 @Test
86 void testComposition() {
87 WhereApplier whereApplier = commonWhere.andThen(wa -> wa.and(birthDate, isNotNull()));
88 whereApplier = whereApplier.andThen(wa -> wa.or(addressId, isLessThan(3)));
89
90 SelectStatementProvider selectStatement = select(person.allColumns())
91 .from(person)
92 .applyWhere(whereApplier)
93 .build()
94 .render(RenderingStrategies.SPRING_NAMED_PARAMETER);
95
96 assertThat(selectStatement.getSelectStatement()).isEqualTo(
97 "select * from Person " +
98 "where id = :p1 or occupation is null and birth_date is not null or address_id < :p2");
99
100 }
101
102 private final WhereApplier commonWhere = where(id, isEqualTo(1)).or(occupation, isNull()).toWhereApplier();
103 }