ids);
39 |
40 | /**
41 | * Saves the given entity. If {@link org.springframework.data.domain.Persistable#isNew()
42 | * entity.isNew()} returns true, then it creates a new record; otherwise it
43 | * updates the existing one.
44 | *
45 | * Use the returned instance for further operations as the save
46 | * operation might have changed the entity instance completely.
47 | *
48 | * @param entity
49 | * @return A saved entity.
50 | * @throws IllegalArgumentException if the given entity is null.
51 | */
52 | S save(S entity);
53 |
54 | /**
55 | * Saves all the given entities.
56 | *
57 | * @see #save(S)
58 | * @param entities
59 | * @return Saved entities.
60 | * @throws IllegalArgumentException if one of the given entities is null.
61 | */
62 | List save(Iterable entities);
63 |
64 | /**
65 | * Inserts the given new entity into database.
66 | *
67 | * Use the returned instance for further operations as the insert
68 | * operation might have changed the entity instance.
69 | *
70 | * @param entity
71 | * @return An inserted entity.
72 | * @throws org.springframework.dao.DuplicateKeyException if record with the
73 | * same primary key as the given entity already exists.
74 | */
75 | S insert(S entity);
76 |
77 | /**
78 | * Updates the given entity. If no record with the entity's ID exists in
79 | * the database, then it throws an exception.
80 | *
81 | * Use the returned instance for further operations as the update
82 | * operation might have changed the entity instance.
83 | *
84 | * @param entity
85 | * @return An updated entity.
86 | * @throws NoRecordUpdatedException if the entity doesn't exist (i.e. no
87 | * record has been updated).
88 | * @throws IllegalArgumentException if some of the properties mapped to the
89 | * entity's primary key are null.
90 | */
91 | S update(S entity);
92 | }
93 |
--------------------------------------------------------------------------------
/src/main/java/cz/jirutka/spring/data/jdbc/TableDescription.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc;
18 |
19 | import org.springframework.util.Assert;
20 |
21 | import java.util.List;
22 |
23 | import static java.util.Arrays.asList;
24 | import static java.util.Collections.singletonList;
25 | import static java.util.Collections.unmodifiableList;
26 |
27 | public class TableDescription {
28 |
29 | private String tableName;
30 | private String selectClause = "*";
31 | private String fromClause;
32 | private List pkColumns = singletonList("id");
33 |
34 |
35 | public TableDescription() {
36 | }
37 |
38 | public TableDescription(String tableName, String selectClause, String fromClause, List pkColumns) {
39 | setTableName(tableName);
40 | setSelectClause(selectClause);
41 | setFromClause(fromClause);
42 | setPkColumns(pkColumns);
43 | }
44 |
45 | public TableDescription(String tableName, String fromClause, String... pkColumns) {
46 | this(tableName, null, fromClause, asList(pkColumns));
47 | }
48 |
49 | public TableDescription(String tableName, String idColumn) {
50 | this(tableName, null, idColumn);
51 | }
52 |
53 |
54 | /**
55 | * @see #setTableName(String)
56 | * @throws IllegalStateException if {@code tableName} is not set.
57 | */
58 | public String getTableName() {
59 | Assert.state(tableName != null, "tableName must not be null");
60 | return tableName;
61 | }
62 |
63 | /**
64 | * @param tableName The table name.
65 | * @throws IllegalArgumentException if {@code tableName} is blank.
66 | */
67 | public void setTableName(String tableName) {
68 | Assert.hasText(tableName, "tableName must not be blank");
69 | this.tableName = tableName;
70 | }
71 |
72 | /**
73 | * @see #setSelectClause(String)
74 | */
75 | public String getSelectClause() {
76 | return selectClause;
77 | }
78 |
79 | /**
80 | * @param selectClause The expression to be used in SELECT clause, i.e.
81 | * list of columns to be retrieved. Default is {@code *}.
82 | */
83 | public void setSelectClause(String selectClause) {
84 | this.selectClause = selectClause != null ? selectClause : "*";
85 | }
86 |
87 | /**
88 | * @see #setSelectClause(String)
89 | */
90 | public String getFromClause() {
91 | return fromClause != null ? fromClause : getTableName();
92 | }
93 |
94 | /**
95 | * @param fromClause The expression to be used in SELECT ... FROM clause,
96 | * i.e. table and join clauses. Defaults to {@link #getTableName()}.
97 | */
98 | public void setFromClause(String fromClause) {
99 | this.fromClause = fromClause;
100 | }
101 |
102 | /**
103 | * @see #setFromClause(String)
104 | */
105 | public List getPkColumns() {
106 | return pkColumns;
107 | }
108 |
109 | /**
110 | * @param pkColumns A list of columns names that are part of the table's
111 | * primary key.
112 | * @throws IllegalArgumentException if {@code pkColumn} is empty.
113 | */
114 | public void setPkColumns(List pkColumns) {
115 | Assert.notEmpty(pkColumns, "At least one primary key column must be provided");
116 | this.pkColumns = unmodifiableList(pkColumns);
117 | }
118 |
119 | /**
120 | * @see #setPkColumns(List)
121 | */
122 | public void setPkColumns(String... idColumns) {
123 | setPkColumns(asList(idColumns));
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/src/main/java/cz/jirutka/spring/data/jdbc/sql/SqlGeneratorFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Jakub Jirutka .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package cz.jirutka.spring.data.jdbc.sql;
17 |
18 | import org.slf4j.Logger;
19 | import org.slf4j.LoggerFactory;
20 | import org.springframework.dao.DataAccessResourceFailureException;
21 |
22 | import javax.sql.DataSource;
23 | import java.sql.DatabaseMetaData;
24 | import java.sql.SQLException;
25 | import java.util.ArrayDeque;
26 | import java.util.Deque;
27 | import java.util.Map;
28 | import java.util.WeakHashMap;
29 |
30 | public class SqlGeneratorFactory {
31 |
32 | private static final Logger LOG = LoggerFactory.getLogger(SqlGeneratorFactory.class);
33 |
34 | private static final SqlGeneratorFactory INSTANCE = new SqlGeneratorFactory(true);
35 |
36 | private final Deque generators = new ArrayDeque<>();
37 |
38 | private final Map cache = new WeakHashMap<>(2, 1.0f);
39 |
40 |
41 | /**
42 | * @param registerDefault Whether to register default (built-in) generators.
43 | * @see #getInstance()
44 | */
45 | public SqlGeneratorFactory(boolean registerDefault) {
46 | if (registerDefault) {
47 | registerGenerator(new DefaultSqlGenerator());
48 | registerGenerator(new LimitOffsetSqlGenerator());
49 | registerGenerator(new SQL2008SqlGenerator());
50 | registerGenerator(new Oracle9SqlGenerator());
51 | }
52 | }
53 |
54 | /**
55 | * @return The singleton instance of SqlGeneratorFactory.
56 | */
57 | public static SqlGeneratorFactory getInstance() {
58 | return INSTANCE;
59 | }
60 |
61 |
62 | /**
63 | * @param dataSource The DataSource for which to find compatible
64 | * SQL Generator.
65 | * @return An SQL Generator compatible with the given {@code dataSource}.
66 | * @throws DataAccessResourceFailureException if exception is thrown when
67 | * trying to obtain Connection or MetaData from the
68 | * {@code dataSource}.
69 | * @throws IllegalStateException if no compatible SQL Generator is found.
70 | */
71 | public SqlGenerator getGenerator(DataSource dataSource) {
72 |
73 | if (cache.containsKey(dataSource)) {
74 | return cache.get(dataSource);
75 | }
76 |
77 | DatabaseMetaData metaData;
78 | try {
79 | metaData = dataSource.getConnection().getMetaData();
80 | } catch (SQLException ex) {
81 | throw new DataAccessResourceFailureException(
82 | "Failed to retrieve database metadata", ex);
83 | }
84 |
85 | for (SqlGenerator generator : generators) {
86 | try {
87 | if (generator.isCompatible(metaData)) {
88 | LOG.info("Using SQL Generator {} for dataSource {}",
89 | generator.getClass().getName(), dataSource.getClass());
90 |
91 | cache.put(dataSource, generator);
92 | return generator;
93 | }
94 | } catch (SQLException ex) {
95 | LOG.warn("Exception occurred when invoking isCompatible() on {}",
96 | generator.getClass().getSimpleName(), ex);
97 | }
98 | }
99 |
100 | // This should not happen, because registry should always contain one
101 | // "default" generator that returns true for every DatabaseMetaData.
102 | throw new IllegalStateException("No compatible SQL Generator found.");
103 | }
104 |
105 | /**
106 | * Adds the {@code sqlGenerator} to the top of the generators registry.
107 | *
108 | * @param sqlGenerator The SQL Generator instance to register.
109 | */
110 | public void registerGenerator(SqlGenerator sqlGenerator) {
111 | generators.push(sqlGenerator);
112 | }
113 |
114 | /**
115 | * Removes all generators from the factory's registry.
116 | */
117 | public void clear() {
118 | generators.clear();
119 | cache.clear();
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/src/test/groovy/cz/jirutka/spring/data/jdbc/sql/SqlGeneratorFactoryTest.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Jakub Jirutka .
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package cz.jirutka.spring.data.jdbc.sql
17 |
18 | import org.springframework.dao.DataAccessResourceFailureException
19 | import spock.lang.Specification
20 |
21 | import javax.sql.DataSource
22 | import java.sql.Connection
23 | import java.sql.DatabaseMetaData
24 | import java.sql.SQLException
25 |
26 | class SqlGeneratorFactoryTest extends Specification {
27 |
28 | def factory = new SqlGeneratorFactory(true)
29 |
30 | def sqlGenerator = Mock(SqlGenerator)
31 | def dbMetaData = Stub(DatabaseMetaData)
32 |
33 | def dataSource = Mock(DataSource) {
34 | getConnection() >> Mock(Connection) {
35 | getMetaData() >> dbMetaData
36 | }
37 | }
38 |
39 |
40 | def 'getInstance(): returns singleton instance with registered generators'() {
41 | expect:
42 | SqlGeneratorFactory.getInstance() != null
43 | SqlGeneratorFactory.getInstance().is(SqlGeneratorFactory.getInstance())
44 | ! SqlGeneratorFactory.getInstance().@generators.isEmpty()
45 | }
46 |
47 |
48 | def 'getGenerator(): returns first generator that responds with true for isCompatible()'() {
49 | setup:
50 | def sqlGenerator2 = Mock(SqlGenerator)
51 | def sqlGenerator3 = Mock(SqlGenerator)
52 | and:
53 | [sqlGenerator3, sqlGenerator2, sqlGenerator].each {
54 | factory.registerGenerator(it)
55 | }
56 | when:
57 | def actual = factory.getGenerator(dataSource)
58 | then:
59 | 1 * sqlGenerator.isCompatible(dbMetaData) >> false
60 | 1 * sqlGenerator2.isCompatible(dbMetaData) >> { throw new SQLException('Not me!') }
61 | 1 * sqlGenerator3.isCompatible(dbMetaData) >> true
62 | actual == sqlGenerator3
63 | }
64 |
65 | def 'getGenerator(): caches result'() {
66 | setup:
67 | def dbMetaData2 = Mock(DatabaseMetaData)
68 | def dataSource2 = Mock(DataSource) {
69 | getConnection() >> Mock(Connection) {
70 | getMetaData() >> dbMetaData2
71 | }
72 | }
73 | def sqlGenerator2 = Mock(SqlGenerator)
74 | and:
75 | factory.registerGenerator(sqlGenerator2)
76 | factory.registerGenerator(sqlGenerator)
77 | when:
78 | 2.times { assert factory.getGenerator(dataSource).is(sqlGenerator) }
79 | then:
80 | 1 * sqlGenerator.isCompatible(dbMetaData) >> true
81 | when:
82 | factory.getGenerator(dataSource2).is(sqlGenerator2)
83 | then:
84 | 1 * sqlGenerator.isCompatible(dbMetaData2) >> false
85 | 1 * sqlGenerator2.isCompatible(dbMetaData2) >> true
86 | when:
87 | factory.getGenerator(dataSource).is(sqlGenerator)
88 | then:
89 | 0 * sqlGenerator.isCompatible(_)
90 | }
91 |
92 | def 'getGenerator(): throws IllegalStateException when no compatible generator is found'() {
93 | setup:
94 | factory.clear()
95 | factory.registerGenerator(sqlGenerator)
96 | sqlGenerator.isCompatible(dbMetaData) >> false
97 | when:
98 | factory.getGenerator(dataSource)
99 | then:
100 | thrown IllegalStateException
101 | }
102 |
103 | def 'getGenerator(): throws DataAccessResourceFailureException when failed to get MetaData'() {
104 | when:
105 | factory.getGenerator(dataSource)
106 | then:
107 | 1 * dataSource.getConnection() >> { throw new SQLException('Oh crap!') }
108 | and:
109 | thrown DataAccessResourceFailureException
110 | }
111 |
112 |
113 | def 'registerGenerator(): adds given generator to the top of the generators stack'() {
114 | when:
115 | factory.registerGenerator(sqlGenerator)
116 | then:
117 | factory.@generators.first.is(sqlGenerator)
118 | }
119 |
120 |
121 | def 'clear(): removes all registered generators'() {
122 | setup:
123 | assert !factory.@generators.isEmpty()
124 | when:
125 | factory.clear()
126 | then:
127 | factory.@generators.isEmpty()
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/CHANGELOG.adoc:
--------------------------------------------------------------------------------
1 | = Changelog
2 | :issues-nurkiewicz-uri: https://github.com/nurkiewicz/spring-data-jdbc-repository/issues
3 | :issues-uri: https://github.com/jirutka/spring-data-jdbc-repository/issues
4 |
5 |
6 | == 0.6.0 (unreleased)
7 |
8 | Enhancements::
9 | * Remove requirement for entities to implement `Persistable` interface. Entities may implement `Persistable`, or use annotation `@Id` from Spring Data Commons.
10 | * Add `SqlGeneratorFactory` that automatically selects compatible `SqlGenerator` according to used database.
11 | * Add protected getter for `jdbcOperations` ({issues-uri}/2[#2]).
12 | * Optimize `delete(Iterable)` – delete entities in a single query.
13 | * Make `update(S)` more robust – throw exception when ID is not null or wrong number of rows is (not) updated.
14 |
15 | Bug fixes::
16 | * Fix duplication in test dependencies – exclude `groovy-all` from `spock-spring`.
17 |
18 | Changes::
19 | * Rename base package from `com.nurkiewicz.jdbcrepository` to `cz.jirutka.spring.data.jdbc`.
20 | * `JdbcRepository`:
21 | ** remove method `pk(Object...)`,
22 | ** rename `JdbcRepository` to `BaseJdbcRepository` and create interface `JdbcRepository`,
23 | ** remove argument `sqlGenerator` from constructors and remove constructors without `rowUnmapper`,
24 | ** rename `getTable()` to `getTableDesc()`,
25 | ** rename `create(..)` to `insert(..)`, `preCreate(..)` to `preInsert(..)` and `postCreate` to `postInsert(..)`,
26 | ** remove overloaded method `postUpdate(S, int)` (it’s not needed anymore, see above),
27 | ** inject dependencies using `@Autowired` instead of manual lookup in `BeanFactory`,
28 | ** add required dependency on `DataSource` and make dependency on `JdbcOperations` optional,
29 | ** disallow properties change after initialization (invoking `afterPropertiesSet()`).
30 | * `TableDescription`:
31 | ** rename `getName()` to `getTableName()` and `getIdColumns()` to `getPkColumns()`,
32 | ** add property `selectClause`,
33 | ** add setters for all properties.
34 | * `SqlGenerator` and subclasses:
35 | ** remove field `allColumnsClause` and one-argument constructor (this is replaced by property `selectClause` in `TableDescription`),
36 | ** rename `SqlGenerator` to `DefaultSqlGenerator`, create interface `SqlGenerator` and reorganize subclasses.
37 | * Rename `MissingRowUnmapper` to `UnsupportedRowUnmapper`.
38 |
39 | Infrastructure::
40 | * Update dependencies.
41 | * Refactor and extend tests for `SqlGenerator`.
42 | * Add tests for methods `insert(..)` and `update(..)`.
43 |
44 |
45 | == 0.5.0 (2016-02-15)
46 |
47 | ⭐️ Project forked and published under new coordinates: cz.jirutka.spring:spring-data-jdbc-repository.
48 |
49 | Enhancements::
50 | * Rewrite all tests to Spock/Groovy.
51 | * Add overloaded hook method `JdbcRepository#postUpdate(Persistable, int)` with number of affected rows.
52 | * Improve `exists(ID)` performance; use `select 1` instead of `select count(*)`.
53 | * Change visibility of methods `JdbcRepository#update(Persistable)` and `JdbcRepository#create(Persistable)` to public.
54 |
55 | Bug fixes::
56 | * Treat column names as case-insensitive ({issues-nurkiewicz-uri}/16[nurkiewicz#16]).
57 | * Fix autowiring of SqlGenerator bean ({issues-nurkiewicz-uri}/25[nurkiewicz#25]).
58 |
59 | Deprecations/changes::
60 | * Drop support for Java 6, minimal required version is now 7.
61 | * Deprecate method `JdbcRepository.pk(Object...)`
62 |
63 | Infrastructure::
64 | * Reformat and slightly refactor sources.
65 | * Test on CI with both OpenJDK 7 and OracleJDK 8.
66 | * Run integration tests for Oracle on Travis using Oracle XE installed with https://github.com/cbandy/travis-oracle[cbandy/travis-oracle].
67 | * Run integration tests for MS SQL on AppVeyor using SQL Server 2012SP1 and 2014.
68 | * Add integration tests for MariaDB and run them on Travis.
69 | * Separate CI build jobs for embedded databases, PostgreSQL, MariaDB, MySQL, Oracle, and MSSQL.
70 | * Replace BoneCP with HikariCP in tests.
71 | * Inherit versions from Spring’s platform-bom.
72 |
73 |
74 | == 0.4.1 (2014-10-23)
75 |
76 | * Fixed standalone configuration and CDI Implementation ({issues-nurkiewicz-uri}/10[nurkiewicz#10])
77 |
78 | == 0.4 (2014-06-16)
79 |
80 | * Repackaged: `com.blogspot.nurkiewicz` -> `com.nurkiewicz`
81 |
82 | == 0.3.2 (2014-06-16)
83 |
84 | * First version available in Maven central repository
85 | * Upgraded Spring Data Commons 1.6.1 -> 1.8.0
86 |
87 | == 0.3.1 (2013-03-16)
88 |
89 | * Upgraded Spring dependencies: 3.2.1 -> 3.2.4 and 1.5.0 -> 1.6.1
90 | * Allow manually injecting JdbcOperations, SqlGenerator and DataSource ({issues-nurkiewicz-uri}/5[nurkiewicz#5])
91 |
92 | == 0.3 (2013-03-06)
93 |
94 | * Oracle 10g / 11g support ({issues-nurkiewicz-uri}/3[nurkiewicz#3])
95 | * Upgrading Spring dependency to 3.2.1.RELEASE and http://www.springsource.org/spring-data/commons[Spring Data Commons] to 1.5.0.RELEASE ({issues-nurkiewicz-uri}/4[nurkiewicz#4]).
96 |
97 | == 0.2 (2013-01-23)
98 |
99 | * MS SQL Server 2008/2012 support ({issues-nurkiewicz-uri}/2[nurkiewicz#2])
100 |
101 | == 0.1 (2013-01-20)
102 |
103 | * Initial revision (http://nurkiewicz.blogspot.no/2013/01/spring-data-jdbc-generic-dao.html[announcement])
104 |
--------------------------------------------------------------------------------
/src/test/groovy/cz/jirutka/spring/data/jdbc/JdbcRepositoryCompoundPkIT.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the 'License')
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an 'AS IS' BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc
18 |
19 | import cz.jirutka.spring.data.jdbc.fixtures.BoardingPass
20 | import cz.jirutka.spring.data.jdbc.fixtures.BoardingPassRepository
21 | import org.springframework.data.domain.PageRequest
22 | import org.springframework.data.domain.Sort
23 | import org.springframework.data.domain.Sort.Order
24 | import org.springframework.transaction.annotation.Transactional
25 | import spock.lang.Specification
26 | import spock.lang.Unroll
27 |
28 | import javax.annotation.Resource
29 |
30 | import static org.springframework.data.domain.Sort.Direction.ASC
31 | import static org.springframework.data.domain.Sort.Direction.DESC
32 |
33 | @Unroll
34 | @Transactional
35 | abstract class JdbcRepositoryCompoundPkIT extends Specification {
36 |
37 | @Resource BoardingPassRepository repository
38 |
39 | final entities = [
40 | new BoardingPass('FOO-100', 1, 'Smith', 'B01'),
41 | new BoardingPass('FOO-100', 2, 'Johnson', 'C02'),
42 | new BoardingPass('BAR-100', 1, 'Gordon', 'D03'),
43 | new BoardingPass('BAR-100', 2, 'Who', 'E04')
44 | ]
45 |
46 |
47 | def '#method(T): inserts entity with compound PK'() {
48 | setup:
49 | def entity = entities[0]
50 | when:
51 | repository./$method/(entity)
52 | then:
53 | repository.findOne(entity.id) == entity
54 | where:
55 | method << ['save', 'insert']
56 | }
57 |
58 | def '#method(T): updates entity with compound PK'() {
59 | setup:
60 | repository.save(entities[0])
61 | def entity = repository.save(entities[1])
62 | and:
63 | entity.passenger = 'Jameson'
64 | entity.seat = 'C03'
65 | when:
66 | repository./$method/(entity)
67 | then:
68 | repository.count() == 2
69 | repository.findOne(entity.id) == new BoardingPass('FOO-100', 2, 'Jameson', 'C03')
70 | where:
71 | method << ['save', 'update']
72 | }
73 |
74 |
75 | def 'delete(ID): deletes entity by given compound PK'() {
76 | setup:
77 | def entity = entities[0]
78 | repository.save(entities)
79 | when:
80 | repository.delete(entity.id)
81 | then:
82 | ! repository.exists(entity.id)
83 | repository.count() == 3
84 | }
85 |
86 | def 'delete(T): deletes given entity with compound PK'() {
87 | setup:
88 | def entity = entities[0]
89 | repository.save(entities)
90 | when:
91 | repository.delete(entity)
92 | then:
93 | ! repository.exists(entity.id)
94 | repository.count() == 3
95 | }
96 |
97 |
98 | def 'findAll(Sortable): returns sorted entities'() {
99 | setup:
100 | repository.save(entities)
101 | when:
102 | def results = repository.findAll(
103 | new Sort(new Order(ASC, 'flight_no'), new Order(DESC, 'seq_no')))
104 | then:
105 | results == entities.reverse()
106 | }
107 |
108 | def 'findAll(Pageable): returns paged and sorted entities'() {
109 | setup:
110 | repository.save(entities)
111 | when:
112 | def page = repository.findAll(
113 | new PageRequest(pageNum, 3,
114 | new Sort(new Order(ASC, 'flight_no'), new Order(DESC, 'seq_no'))
115 | ))
116 | then:
117 | page.totalElements == 4
118 | page.totalPages == 2
119 | page.content == entities[entitiesIdx]
120 | where:
121 | pageNum || entitiesIdx
122 | 0 || 3..1
123 | 1 || 0..0
124 | }
125 |
126 |
127 | def 'findAll(Iterable): returns nothing when given empty list'() {
128 | setup:
129 | repository.save(entities)
130 | when:
131 | def results = repository.findAll([])
132 | then:
133 | results.asList().isEmpty()
134 | }
135 |
136 | def 'findAll(Iterable): returns one entity when given one id'() {
137 | setup:
138 | def ids = entities.collect { repository.save(it).id }
139 | when:
140 | def results = repository.findAll([ids[1]])
141 | then:
142 | results.size() == 1
143 | results == [entities[1]]
144 | }
145 |
146 | def 'findAll(Iterable): returns two entities when given two ids'() {
147 | setup:
148 | def ids = entities.collect { repository.save(it).id }
149 | when:
150 | def results = repository.findAll(ids[1..2])
151 | then:
152 | results.size() == 2
153 | results as Set == entities[1..2] as Set
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/src/main/java/cz/jirutka/spring/data/jdbc/sql/DefaultSqlGenerator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc.sql;
18 |
19 | import cz.jirutka.spring.data.jdbc.TableDescription;
20 | import org.springframework.data.domain.Pageable;
21 | import org.springframework.data.domain.Sort;
22 | import org.springframework.data.domain.Sort.Direction;
23 | import org.springframework.data.domain.Sort.Order;
24 | import org.springframework.util.Assert;
25 |
26 | import java.sql.DatabaseMetaData;
27 | import java.sql.SQLException;
28 | import java.util.Collection;
29 | import java.util.Iterator;
30 | import java.util.List;
31 | import java.util.Map;
32 |
33 | import static cz.jirutka.spring.data.jdbc.internal.StringUtils.repeat;
34 | import static java.lang.String.format;
35 | import static org.springframework.util.StringUtils.collectionToDelimitedString;
36 |
37 | /**
38 | * SQL Generator compatible with SQL:99.
39 | */
40 | public class DefaultSqlGenerator implements SqlGenerator {
41 |
42 | static final String
43 | AND = " AND ",
44 | OR = " OR ",
45 | COMMA = ", ",
46 | PARAM = " = ?";
47 |
48 |
49 | public boolean isCompatible(DatabaseMetaData metadata) throws SQLException {
50 | return true;
51 | }
52 |
53 |
54 | public String count(TableDescription table) {
55 | return format("SELECT count(*) FROM %s", table.getFromClause());
56 | }
57 |
58 | public String deleteAll(TableDescription table) {
59 | return format("DELETE FROM %s", table.getTableName());
60 | }
61 |
62 | public String deleteById(TableDescription table) {
63 | return deleteByIds(table, 1);
64 | }
65 |
66 | public String deleteByIds(TableDescription table, int idsCount) {
67 | return deleteAll(table) + " WHERE " + idsPredicate(table, idsCount);
68 | }
69 |
70 | public String existsById(TableDescription table) {
71 | return format("SELECT 1 FROM %s WHERE %s", table.getTableName(), idPredicate(table));
72 | }
73 |
74 | public String insert(TableDescription table, Map columns) {
75 |
76 | return format("INSERT INTO %s (%s) VALUES (%s)",
77 | table.getTableName(),
78 | collectionToDelimitedString(columns.keySet(), COMMA),
79 | repeat("?", COMMA, columns.size()));
80 | }
81 |
82 | public String selectAll(TableDescription table) {
83 | return format("SELECT %s FROM %s", table.getSelectClause(), table.getFromClause());
84 | }
85 |
86 | public String selectAll(TableDescription table, Pageable page) {
87 | Sort sort = page.getSort() != null ? page.getSort() : sortById(table);
88 |
89 | return format("SELECT t2__.* FROM ( "
90 | + "SELECT row_number() OVER (ORDER BY %s) AS rn__, t1__.* FROM ( %s ) t1__ "
91 | + ") t2__ WHERE t2__.rn__ BETWEEN %s AND %s",
92 | orderByExpression(sort), selectAll(table),
93 | page.getOffset() + 1, page.getOffset() + page.getPageSize());
94 | }
95 |
96 | public String selectAll(TableDescription table, Sort sort) {
97 | return selectAll(table) + (sort != null ? orderByClause(sort) : "");
98 | }
99 |
100 | public String selectById(TableDescription table) {
101 | return selectByIds(table, 1);
102 | }
103 |
104 | public String selectByIds(TableDescription table, int idsCount) {
105 | return idsCount > 0
106 | ? selectAll(table) + " WHERE " + idsPredicate(table, idsCount)
107 | : selectAll(table);
108 | }
109 |
110 | public String update(TableDescription table, Map columns) {
111 |
112 | return format("UPDATE %s SET %s WHERE %s",
113 | table.getTableName(),
114 | formatParameters(columns.keySet(), COMMA),
115 | idPredicate(table));
116 | }
117 |
118 |
119 | protected String orderByClause(Sort sort) {
120 | return " ORDER BY " + orderByExpression(sort);
121 | }
122 |
123 | protected String orderByExpression(Sort sort) {
124 | StringBuilder sb = new StringBuilder();
125 |
126 | for (Iterator it = sort.iterator(); it.hasNext(); ) {
127 | Order order = it.next();
128 | sb.append(order.getProperty()).append(' ').append(order.getDirection());
129 |
130 | if (it.hasNext()) sb.append(COMMA);
131 | }
132 | return sb.toString();
133 | }
134 |
135 | protected Sort sortById(TableDescription table) {
136 | return new Sort(Direction.ASC, table.getPkColumns());
137 | }
138 |
139 |
140 | private String idPredicate(TableDescription table) {
141 | return formatParameters(table.getPkColumns(), AND);
142 | }
143 |
144 | private String idsPredicate(TableDescription table, int idsCount) {
145 | Assert.isTrue(idsCount > 0, "idsCount must be greater than zero");
146 |
147 | List idColumnNames = table.getPkColumns();
148 |
149 | if (idsCount == 1) {
150 | return idPredicate(table);
151 |
152 | } else if (idColumnNames.size() > 1) {
153 | return repeat("(" + formatParameters(idColumnNames, AND) + ")", OR, idsCount);
154 |
155 | } else {
156 | return idColumnNames.get(0) + " IN (" + repeat("?", COMMA, idsCount) + ")";
157 | }
158 | }
159 |
160 | private String formatParameters(Collection columns, String delimiter) {
161 | return collectionToDelimitedString(columns, delimiter, "", PARAM);
162 | }
163 | }
164 |
--------------------------------------------------------------------------------
/src/test/groovy/cz/jirutka/spring/data/jdbc/JdbcRepositoryManyToOneIT.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the 'License')
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an 'AS IS' BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc
18 |
19 | import cz.jirutka.spring.data.jdbc.fixtures.CommentWithUserRepository
20 | import cz.jirutka.spring.data.jdbc.fixtures.User
21 | import cz.jirutka.spring.data.jdbc.fixtures.UserRepository
22 | import cz.jirutka.spring.data.jdbc.fixtures.CommentWithUser
23 | import org.springframework.data.domain.PageRequest
24 | import org.springframework.data.domain.Sort
25 | import org.springframework.transaction.annotation.Transactional
26 | import spock.lang.Specification
27 | import spock.lang.Unroll
28 |
29 | import javax.annotation.Resource
30 | import java.sql.Date
31 | import java.sql.Timestamp
32 |
33 | import static java.util.Calendar.JANUARY
34 | import static org.springframework.data.domain.Sort.Direction.ASC
35 | import static org.springframework.data.domain.Sort.Direction.DESC
36 |
37 | @Unroll
38 | @Transactional
39 | abstract class JdbcRepositoryManyToOneIT extends Specification {
40 |
41 | @Resource CommentWithUserRepository repository
42 | @Resource UserRepository userRepository
43 |
44 | final someDate = new Date(new GregorianCalendar(2013, JANUARY, 19).timeInMillis)
45 | final someTimestamp = new Timestamp(new GregorianCalendar(2013, JANUARY, 20).timeInMillis)
46 | final someUser = new User('Jimmy', someDate, -1, false)
47 |
48 | final entities = [
49 | new CommentWithUser(someUser, 'First comment', someTimestamp, 3),
50 | new CommentWithUser(someUser, 'Second comment', someTimestamp, 2),
51 | new CommentWithUser(someUser, 'Third comment', someTimestamp, 1)
52 | ]
53 |
54 |
55 | def setup() {
56 | userRepository.save(someUser)
57 | }
58 |
59 |
60 | def '#method(T): generates primary key'() {
61 | when:
62 | repository.save(entities[0])
63 | then:
64 | entities[0].id != null
65 | where:
66 | method << ['save', 'insert']
67 | }
68 |
69 | def '#method(T)/findOne(): inserts and returns entity with association attached'() {
70 | setup:
71 | def expected = entities[0]
72 | when:
73 | repository./$method/(expected)
74 | def actual = repository.findOne(expected.id)
75 | then:
76 | actual == expected
77 | actual.user == expected.user
78 | where:
79 | method << ['save', 'insert']
80 | }
81 |
82 | def "#method(T): updates entity's association"() {
83 | setup:
84 | def firstUser = userRepository.save(new User('First user', someDate, 10, false))
85 | def comment = repository.save(entities[0])
86 | when:
87 | comment.user = firstUser
88 | repository./$method/(comment)
89 | then:
90 | repository.count() == 1
91 | def result = repository.findOne(comment.id)
92 | result.user == firstUser
93 | where:
94 | method << ['save', 'update']
95 | }
96 |
97 |
98 | def 'findAll(Sort): returns sorted entities with the same association'() {
99 | setup:
100 | repository.save(entities)
101 | when:
102 | def actual = repository.findAll(new Sort('favourite_count'))
103 | then:
104 | actual == entities.sort{ it.favouriteCount }
105 | actual*.user == [someUser] * 3
106 | }
107 |
108 | def 'findAll(Sort): returns sorted entities with different associations'() {
109 | given:
110 | def firstUser = userRepository.save(new User('First user', someDate, 10, false))
111 | def secondUser = userRepository.save(new User('Second user', someDate, 20, false))
112 | def thirdUser = userRepository.save(new User('Third user', someDate, 30, false))
113 |
114 | def first = repository.save(new CommentWithUser(firstUser, 'First comment', someTimestamp, 3))
115 | def second = repository.save(new CommentWithUser(secondUser, 'Second comment', someTimestamp, 2))
116 | def third = repository.save(new CommentWithUser(thirdUser, 'Third comment', someTimestamp, 1))
117 | when:
118 | def results = repository.findAll(new Sort(DESC, 'favourite_count'))
119 | then:
120 | results == [first, second, third]
121 | }
122 |
123 | def 'findAll(Pageable): returns paged and sorted entities with associations attached'() {
124 | setup:
125 | repository.save(entities)
126 | when:
127 | def page = repository.findAll(new PageRequest(pageNum, 2, ASC, 'favourite_count'))
128 | then:
129 | page.totalElements == 3
130 | page.totalPages == 2
131 | page.content == entities[entitiesIdx]
132 | page.content*.user.unique() == [someUser]
133 | where:
134 | pageNum || entitiesIdx
135 | 0 || 2..1
136 | 1 || 0..0
137 | }
138 |
139 |
140 | def 'delete(T): deletes an entity without deleting associated entity'() {
141 | setup:
142 | def comment = repository.save(entities[0])
143 | when:
144 | repository.delete(comment)
145 | then:
146 | repository.count() == 0
147 | userRepository.exists(someUser.userName)
148 | }
149 |
150 |
151 | def 'deletesAll(): deletes all entities without deleting associated entities'() {
152 | setup:
153 | repository.save(entities)
154 | when:
155 | repository.deleteAll()
156 | then:
157 | repository.count() == 0
158 | userRepository.exists(someUser.userName)
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 | 4.0.0
6 |
7 |
8 | cz.jirutka.maven
9 | groovy-parent
10 | 1.3.2
11 |
12 |
13 |
14 |
15 |
16 | cz.jirutka.spring
17 | spring-data-jdbc-repository
18 | 0.6.0-SNAPSHOT
19 | jar
20 |
21 | Spring Data JDBC repository
22 |
23 | A repository implementation compatible with Spring Data abstraction that uses JdbcTemplate
24 |
25 | https://github.com/jirutka/spring-data-jdbc-repository
26 | 2012
27 |
28 |
29 |
30 | Jakub Jirutka
31 | jakub@jirutka.cz
32 | CTU in Prague
33 | http://www.cvut.cz
34 |
35 |
36 | Tomasz Nurkiewicz
37 | http://nurkiewicz.com
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 | Apache 2.0
47 | http://www.apache.org/licenses/LICENSE-2.0
48 |
49 |
50 |
51 |
52 | https://github.com/jirutka/spring-data-jdbc-repository
53 | scm:git:git@github.com:jirutka/spring-data-jdbc-repository.git
54 |
55 |
56 |
57 | github
58 | https://github.com/jirutka/spring-data-jdbc-repository/issues
59 |
60 |
61 |
62 | travis
63 | https://travis-ci.org/jirutka/spring-data-jdbc-repository/
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | io.spring.platform
73 | platform-bom
74 | 2.0.2.RELEASE
75 | pom
76 | import
77 |
78 |
79 |
80 |
81 |
82 |
83 | org.springframework
84 | spring-beans
85 |
86 |
87 |
88 | org.springframework
89 | spring-jdbc
90 |
91 |
92 |
93 | org.springframework.data
94 | spring-data-commons
95 |
96 |
97 |
98 |
99 |
100 | cglib
101 | cglib-nodep
102 | 3.2.1
103 | test
104 |
105 |
106 |
107 | ch.qos.logback
108 | logback-classic
109 | test
110 |
111 |
112 |
113 | org.codehaus.groovy
114 | groovy
115 | test
116 |
117 |
118 |
119 | org.slf4j
120 | jcl-over-slf4j
121 | ${slf4j.version}
122 | test
123 |
124 |
125 |
126 | org.spockframework
127 | spock-core
128 | test
129 |
130 |
131 |
132 | org.spockframework
133 | spock-spring
134 | ${spock.version}
135 |
136 |
137 | org.codehaus.groovy
138 | groovy-all
139 |
140 |
141 | test
142 |
143 |
144 |
145 | org.springframework
146 | spring-aop
147 | test
148 |
149 |
150 |
151 | org.springframework
152 | spring-context
153 | test
154 |
155 |
156 |
157 | org.springframework
158 | spring-test
159 | test
160 |
161 |
162 |
163 |
164 |
165 | com.h2database
166 | h2
167 | test
168 |
169 |
170 |
171 | com.zaxxer
172 | HikariCP-java6
173 | test
174 |
175 |
176 |
177 | mysql
178 | mysql-connector-java
179 | test
180 |
181 |
182 |
183 | net.sourceforge.jtds
184 | jtds
185 | 1.3.1
186 | test
187 |
188 |
189 |
190 | org.apache.derby
191 | derby
192 | test
193 |
194 |
195 |
196 | org.hsqldb
197 | hsqldb
198 | test
199 |
200 |
201 |
202 | org.mariadb.jdbc
203 | mariadb-java-client
204 | 1.3.6
205 | test
206 |
207 |
208 |
209 | org.postgresql
210 | postgresql
211 | test
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 | oracle
221 |
224 |
225 |
226 | com.oracle
227 | ojdbc6
228 | 11.2.0.3
229 | test
230 |
231 |
232 |
233 |
234 |
235 |
236 |
--------------------------------------------------------------------------------
/src/test/groovy/cz/jirutka/spring/data/jdbc/sql/SqlGeneratorTest.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the 'License')
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an 'AS IS' BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc.sql
18 |
19 | import cz.jirutka.spring.data.jdbc.TableDescription
20 | import org.springframework.data.domain.PageRequest
21 | import org.springframework.data.domain.Pageable
22 | import org.springframework.data.domain.Sort
23 | import org.springframework.data.domain.Sort.Direction
24 | import org.springframework.data.domain.Sort.Order
25 | import spock.lang.Specification
26 | import spock.lang.Unroll
27 |
28 | import static org.springframework.data.domain.Sort.Direction.ASC
29 | import static org.springframework.data.domain.Sort.Direction.DESC
30 |
31 | @Unroll
32 | class SqlGeneratorTest extends Specification {
33 |
34 | final ANY = new Object()
35 |
36 | def table = new TableDescription (
37 | tableName: 'tab',
38 | selectClause: 'a, b',
39 | fromClause: 'tabx',
40 | pkColumns: ['tid']
41 | )
42 |
43 | def getSqlGenerator() { new DefaultSqlGenerator() }
44 |
45 |
46 | def 'count()'() {
47 | expect:
48 | sqlGenerator.count(table) == 'SELECT count(*) FROM tabx'
49 | }
50 |
51 |
52 | def 'deleteAll()'() {
53 | expect:
54 | sqlGenerator.deleteAll(table) == 'DELETE FROM tab'
55 | }
56 |
57 |
58 | def 'deleteById(): with #desc'() {
59 | setup:
60 | table.pkColumns = pkColumns(pkSize)
61 | expect:
62 | sqlGenerator.deleteById(table) == "DELETE FROM tab WHERE ${pkPredicate(pkSize)}"
63 | where:
64 | pkSize || desc
65 | 1 || 'simple PK'
66 | 3 || 'composite PK'
67 | }
68 |
69 |
70 | def 'deleteByIds(): with idsCount = #idsCount'() {
71 | when:
72 | sqlGenerator.deleteByIds(table, idsCount)
73 | then:
74 | thrown IllegalArgumentException
75 | where:
76 | idsCount << [0, -1]
77 | }
78 |
79 | def 'deleteByIds(): when simple PK and given #desc'() {
80 | expect:
81 | sqlGenerator.deleteByIds(table, idsCount) == "DELETE FROM tab WHERE ${whereClause}"
82 | where:
83 | idsCount || whereClause | desc
84 | 1 || 'tid = ?' | 'one id'
85 | 3 || 'tid IN (?, ?, ?)' | 'several ids'
86 | }
87 |
88 | def 'deleteByIds(): when composite PK and given #desc'() {
89 | setup:
90 | table.pkColumns = pkColumns(2)
91 | expect:
92 | sqlGenerator.deleteByIds(table, idsCount) == "DELETE FROM tab WHERE ${whereClause}"
93 | where:
94 | idsCount || whereClause | desc
95 | 1 || pkPredicate(2) | 'one id'
96 | 2 || "(${pkPredicate(2)}) OR (${pkPredicate(2)})" | 'several ids'
97 | }
98 |
99 |
100 | def 'existsById(): with #desc'() {
101 | setup:
102 | table.pkColumns = pkColumns(pkSize)
103 | expect:
104 | sqlGenerator.existsById(table) == "SELECT 1 FROM tab WHERE ${pkPredicate(pkSize)}"
105 | where:
106 | pkSize || desc
107 | 1 || 'simple PK'
108 | 3 || 'composite PK'
109 | }
110 |
111 |
112 | def 'insert()'() {
113 | when:
114 | def actual = sqlGenerator.insert(table, [x: ANY, y: ANY, z: ANY])
115 | then:
116 | actual == 'INSERT INTO tab (x, y, z) VALUES (?, ?, ?)'
117 | }
118 |
119 |
120 | def 'selectAll()'() {
121 | expect:
122 | sqlGenerator.selectAll(table) == 'SELECT a, b FROM tabx'
123 | }
124 |
125 | def "selectAll(Pageable): #desc"() {
126 | setup:
127 | table.pkColumns = pkColumns(pkSize)
128 | def expected = expectedPaginatedQuery(table, pageable)
129 | expect:
130 | sqlGenerator.selectAll(table, pageable) == expected
131 | where:
132 | pkSize | pageable || desc
133 | 1 | page(0, 10) || 'when simple key and requested first page'
134 | 1 | page(20, 10) || 'when simple key and requested third page'
135 | 1 | page(0, 10, order(ASC, 'a')) || 'when simple key and requested first page with sort'
136 | 3 | page(0, 10) || 'when composite key and requested first page'
137 | 3 | page(20, 10, order(ASC, 'a')) || 'when composite key and requested third page with sort'
138 | }
139 |
140 | def 'selectAll(Sort): #expected'() {
141 | when:
142 | def actual = sqlGenerator.selectAll(table, new Sort(orders))
143 | then:
144 | actual == "SELECT a, b FROM tabx ${expected}"
145 | where:
146 | orders || expected
147 | [order(ASC, 'a')] || 'ORDER BY a ASC'
148 | [order(DESC, 'a')] || 'ORDER BY a DESC'
149 | [order(ASC, 'a'), order(DESC, 'b')] || 'ORDER BY a ASC, b DESC'
150 | }
151 |
152 |
153 | def 'selectById(): with #desc'() {
154 | setup:
155 | table.pkColumns = pkColumns(pkSize)
156 | expect:
157 | sqlGenerator.selectById(table) == "SELECT a, b FROM tabx WHERE ${pkPredicate(pkSize)}"
158 | where:
159 | pkSize || desc
160 | 1 || 'simple PK'
161 | 3 || 'composite PK'
162 | }
163 |
164 |
165 | def 'selectByIds(): when simple PK and given #desc'() {
166 | expect:
167 | sqlGenerator.selectByIds(table, idsCount) == "SELECT a, b FROM tabx${expected}"
168 | where:
169 | idsCount || expected | desc
170 | 0 || '' | 'no id'
171 | 1 || ' WHERE tid = ?' | 'one id'
172 | 2 || ' WHERE tid IN (?, ?)' | 'two ids'
173 | 3 || ' WHERE tid IN (?, ?, ?)' | 'several ids'
174 | }
175 |
176 | def 'selectByIds(): when composite PK and given #desc'() {
177 | setup:
178 | table.pkColumns = pkColumns(3)
179 | expected = expected.replaceAll('%1', pkPredicate(3))
180 | when:
181 | def actual = sqlGenerator.selectByIds(table, idsCount)
182 | then:
183 | actual == "SELECT a, b FROM tabx${expected}"
184 | where:
185 | idsCount || expected | desc
186 | 0 || '' | 'no id'
187 | 1 || ' WHERE %1' | 'one id'
188 | 2 || ' WHERE (%1) OR (%1)' | 'two ids'
189 | 3 || ' WHERE (%1) OR (%1) OR (%1)' | 'several ids'
190 | }
191 |
192 |
193 | def 'update(): with #desc'() {
194 | setup:
195 | table.pkColumns = pkColumns(idsCount)
196 | when:
197 | def actual = sqlGenerator.update(table, [x: ANY, y: ANY, z: ANY])
198 | then:
199 | actual == "UPDATE tab SET x = ?, y = ?, z = ? WHERE ${pkPredicate(idsCount)}"
200 | where:
201 | idsCount || desc
202 | 1 || 'simple PK'
203 | 2 || 'composite PK'
204 | }
205 |
206 |
207 | def expectedPaginatedQuery(TableDescription table, Pageable page) {
208 |
209 | // If sort is not specified, then it should be sorted by primary key columns.
210 | def sort = page.sort ?: new Sort(ASC, table.pkColumns)
211 |
212 | def firstIndex = page.offset + 1
213 | def lastIndex = page.offset + page.pageSize
214 |
215 | """
216 | SELECT t2__.* FROM (
217 | SELECT row_number() OVER (${orderBy(sort)}) AS rn__, t1__.* FROM (
218 | SELECT ${table.selectClause} FROM ${table.fromClause}
219 | ) t1__
220 | ) t2__ WHERE t2__.rn__ BETWEEN ${firstIndex} AND ${lastIndex}
221 | """.trim().replaceAll(/\s+/, ' ')
222 | }
223 |
224 |
225 | def page(int offset, int limit, Order... orders) {
226 | def sort = orders.length > 0 ? new Sort(orders) : null
227 | new PageRequest(offset / limit as int, limit, sort)
228 | }
229 |
230 | def order(Direction dir, String property) {
231 | new Order(dir, property)
232 | }
233 |
234 | def orderBy(Sort sort) {
235 | 'ORDER BY ' + sort.collect { "${it.property} ${it.direction.name()}" }.join(', ')
236 | }
237 |
238 | static pkColumns(count) {
239 | (1..count).collect { "id${it}" }*.toString()
240 | }
241 |
242 | static pkPredicate(count) {
243 | pkColumns(count).collect { "$it = ?" }.join(' AND ')
244 | }
245 | }
246 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/src/test/groovy/cz/jirutka/spring/data/jdbc/JdbcRepositoryManualKeyIT.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the 'License')
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an 'AS IS' BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc
18 |
19 | import cz.jirutka.spring.data.jdbc.fixtures.CommentRepository
20 | import cz.jirutka.spring.data.jdbc.fixtures.User
21 | import cz.jirutka.spring.data.jdbc.fixtures.UserRepository
22 | import org.springframework.dao.DuplicateKeyException
23 | import org.springframework.data.domain.PageRequest
24 | import org.springframework.data.domain.Sort
25 | import org.springframework.data.domain.Sort.Order
26 | import org.springframework.jdbc.core.JdbcTemplate
27 | import org.springframework.transaction.annotation.Transactional
28 | import spock.lang.Specification
29 | import spock.lang.Unroll
30 |
31 | import javax.annotation.Resource
32 | import javax.sql.DataSource
33 | import java.sql.Date
34 |
35 | import static org.springframework.data.domain.Sort.Direction.ASC
36 | import static org.springframework.data.domain.Sort.Direction.DESC
37 |
38 | @Unroll
39 | @Transactional
40 | abstract class JdbcRepositoryManualKeyIT extends Specification {
41 |
42 | @Resource UserRepository repository
43 | @Resource CommentRepository commentRepository
44 | @Resource DataSource dataSource
45 |
46 | final someDateOfBirth = new Date(new GregorianCalendar(2013, Calendar.JANUARY, 9).timeInMillis)
47 |
48 | final entities = [
49 | Ruby: new User('Ruby', someDateOfBirth, 40, true),
50 | Emma: new User('Emma', someDateOfBirth, 38, true),
51 | Drew: new User('Drew', someDateOfBirth, 40, true),
52 | Lucy: new User('Lucy', someDateOfBirth, 38, true),
53 | Mindy: new User('Mindy', someDateOfBirth, 42, true)
54 | ]
55 |
56 | JdbcTemplate jdbc
57 |
58 |
59 | def setup() {
60 | jdbc = new JdbcTemplate(dataSource)
61 |
62 | for (User user : entities.values()) {
63 | insertUser(user)
64 | }
65 | assert selectIds() == entities.keySet()
66 | }
67 |
68 |
69 | def 'findOne(ID): returns null when the table is empty'() {
70 | setup:
71 | deleteAllUsers()
72 | expect:
73 | repository.findOne('Emma') == null
74 | }
75 |
76 | def 'findOne(ID): returns null when record for given id does not exist'() {
77 | expect:
78 | repository.findOne('John') == null
79 | }
80 |
81 | def 'findOne(ID): returns entity for the given id'() {
82 | expect:
83 | repository.findOne('Drew') == entities['Drew']
84 | }
85 |
86 |
87 | def 'findAll(): returns empty list when the table is empty'() {
88 | setup:
89 | deleteAllUsers()
90 | expect:
91 | repository.findAll().empty
92 | }
93 |
94 | def 'findAll(): returns list of all entities in the table'() {
95 | expect:
96 | repository.findAll() as Set == entities.values() as Set
97 | }
98 |
99 |
100 | def 'findAll(Iterable): returns list of entities for the given ids'() {
101 | when:
102 | def results = repository.findAll(ids) as Set
103 | then:
104 | results == ids.collect(entities.&get) as Set
105 | where:
106 | ids << [[], ['Mindy'], ['Mindy', 'Ruby']]
107 | }
108 |
109 |
110 | def 'findAll(Sort): returns entities sorted by one column'() {
111 | when:
112 | def results = repository.findAll(new Sort(new Order(ASC, 'user_name')))
113 | then:
114 | results == ['Drew', 'Emma', 'Lucy', 'Mindy', 'Ruby'].collect(entities.&get)
115 | }
116 |
117 | def 'findAll(Sort): returns entities sorted by two columns'() {
118 | when:
119 | def results = repository.findAll(
120 | new Sort(new Order(DESC, 'reputation'), new Order(ASC, 'user_name')))
121 | then:
122 | results == ['Mindy', 'Drew', 'Ruby', 'Emma', 'Lucy'].collect(entities.&get)
123 | }
124 |
125 |
126 | def 'findAll(Pageable): returns empty page when the table is empty'() {
127 | setup:
128 | deleteAllUsers()
129 | when:
130 | def page = repository.findAll(new PageRequest(0, 20))
131 | then:
132 | ! page.hasContent()
133 | page.totalElements == 0
134 | page.size == 20
135 | page.number == 0
136 | }
137 |
138 | def 'findAll(Pageable): returns paged entities'() {
139 | when:
140 | def page = repository.findAll(new PageRequest(pageNum, 3))
141 | then:
142 | page.totalElements == entities.size()
143 | page.size == 3
144 | page.number == pageNum
145 | page.content.size() == resultSize
146 | entities.values().containsAll(page.content)
147 | where:
148 | pageNum | resultSize
149 | 0 | 3
150 | 1 | 2
151 | }
152 |
153 | def 'findAll(Pageable): returns empty page when 2nd page requested, but only one record in table'() {
154 | setup:
155 | deleteAllUsers()
156 | insertUser entities['Mindy']
157 | when:
158 | def page = repository.findAll(new PageRequest(1, 5))
159 | then:
160 | page.content.size() == 0
161 | page.number == 1
162 | page.size == 5
163 | page.totalElements == 1
164 | }
165 |
166 | def 'findAll(Pageable): returns paged entities sorted by two columns'() {
167 | when:
168 | def page = repository.findAll(new PageRequest(pageNum, 3,
169 | new Sort(new Order(DESC, 'reputation'), new Order(ASC, 'user_name'))))
170 | then:
171 | page.number == pageNum
172 | page.size == 3
173 | page.totalElements == 5
174 | page.content == resultIds.collect(entities.&get)
175 | where:
176 | pageNum | resultIds
177 | 0 | ['Mindy', 'Drew', 'Ruby']
178 | 1 | ['Emma', 'Lucy']
179 | }
180 |
181 |
182 | def '#method(T): inserts the given new entity'() {
183 | setup:
184 | deleteAllUsers()
185 | when:
186 | repository./$method/(entities['Mindy'])
187 | then:
188 | selectUserById('Mindy') == entities['Mindy']
189 | where:
190 | method << ['save', 'insert']
191 | }
192 |
193 | def 'save(T): throws DuplicateKeyException when the given entity is marked as new, but already exists'() {
194 | when:
195 | repository.save(entities['Mindy'])
196 | then:
197 | thrown DuplicateKeyException
198 | }
199 |
200 | def 'insert(): throws DuplicateKeyException when given entity that is already persisted'() {
201 | when:
202 | repository.save(entities['Mindy'])
203 | then:
204 | thrown DuplicateKeyException
205 | }
206 |
207 | def '#method(T): updates the record when already exists'() {
208 | setup:
209 | deleteAllUsers()
210 | and:
211 | def entity = repository.save(entities['Lucy'])
212 | entity.enabled = false
213 | entity.reputation = 42
214 | when:
215 | repository./$method/(entity)
216 | then:
217 | repository.findOne(entity.id) == new User(entity.id, entity.dateOfBirth, 42, false)
218 | where:
219 | method << ['save', 'update']
220 | }
221 |
222 | def 'update(): throws NoRecordUpdatedException when record does not exist'() {
223 | setup:
224 | deleteAllUsers()
225 | when:
226 | repository.update(entities['Emma'])
227 | then:
228 | def ex = thrown(NoRecordUpdatedException)
229 | ex.tableName == repository.tableDesc.tableName
230 | ex.id == ['Emma']
231 | }
232 |
233 | def 'update(): throws IllegalArgumentException when given entity with null id'() {
234 | setup:
235 | deleteAllUsers()
236 | when:
237 | repository.update(new User(null, someDateOfBirth, 0, true))
238 | then:
239 | thrown IllegalArgumentException
240 | }
241 |
242 |
243 | def 'save(Iterable): inserts given entities'() {
244 | setup:
245 | deleteAllUsers()
246 | when:
247 | repository.save(entities.values())
248 | then:
249 | entities.values().every { User expected ->
250 | selectUserById(expected.id) == expected
251 | }
252 | }
253 |
254 |
255 | def 'exists(ID): returns false when DB is empty'() {
256 | setup:
257 | deleteAllUsers()
258 | expect:
259 | ! repository.exists('John')
260 | }
261 |
262 | def 'exists(ID): returns false when record with such id does not exist'() {
263 | expect:
264 | ! repository.exists('John')
265 | }
266 |
267 | def 'exists(ID): returns true when record for given id exists'() {
268 | expect:
269 | repository.exists('Mindy')
270 | }
271 |
272 |
273 | def 'delete(ID): does nothing when record for given id does not exist'() {
274 | when:
275 | repository.delete('Johny')
276 | then:
277 | notThrown Exception
278 | }
279 |
280 | def 'delete(ID): deletes record by given id'() {
281 | when:
282 | repository.delete('Lucy')
283 | then:
284 | ! selectIds().contains('Lucy')
285 | selectIds() == entities.keySet() - 'Lucy'
286 | }
287 |
288 | def 'delete(T): deletes record by given entity'() {
289 | when:
290 | repository.delete(entities['Lucy'])
291 | then:
292 | ! selectIds().contains('Lucy')
293 | selectIds() == entities.keySet() - 'Lucy'
294 | }
295 |
296 | def 'delete(Iterable): deletes multiple entities'() {
297 | setup:
298 | def toDelete = ['Lucy', 'Emma'].collect(entities.&get)
299 | when:
300 | repository.delete(toDelete as List)
301 | then:
302 | selectIds() == entities.keySet() - toDelete*.id
303 | }
304 |
305 | def 'delete(Iterable): ignores non existing entities'() {
306 | setup:
307 | def toDelete = [entities['Lucy'], new User('John', someDateOfBirth, 15, true)]
308 | when:
309 | repository.delete(toDelete as List)
310 | then:
311 | selectIds() == entities.keySet() - toDelete*.id
312 | }
313 |
314 |
315 | def 'deleteAll(): deletes all records in the table'() {
316 | when:
317 | repository.deleteAll()
318 | then:
319 | selectIds().empty
320 | }
321 |
322 |
323 | def 'count(): returns zero when DB is empty'() {
324 | setup:
325 | deleteAllUsers()
326 | expect:
327 | repository.count() == 0
328 | }
329 |
330 | def 'count(): returns correct number of records in the table'() {
331 | expect:
332 | repository.count() == 5
333 | }
334 |
335 |
336 |
337 | def insertUser(User user) {
338 | jdbc.update('INSERT INTO USERS VALUES (?, ?, ?, ?)',
339 | user.userName, user.dateOfBirth, user.reputation, user.enabled)
340 | assert selectIds().contains(user.userName)
341 | }
342 |
343 | def selectUserById(String id) {
344 | jdbc.queryForObject('SELECT * FROM USERS WHERE user_name = ?', UserRepository.ROW_MAPPER, id)
345 | }
346 |
347 | def selectIds() {
348 | jdbc.queryForList('SELECT user_name FROM USERS', String) as Set
349 | }
350 |
351 | def deleteAllUsers() {
352 | jdbc.execute('DELETE FROM USERS')
353 | }
354 | }
355 |
--------------------------------------------------------------------------------
/src/main/java/cz/jirutka/spring/data/jdbc/BaseJdbcRepository.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2014 Tomasz Nurkiewicz .
3 | * Copyright 2016 Jakub Jirutka .
4 | *
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | */
17 | package cz.jirutka.spring.data.jdbc;
18 |
19 | import cz.jirutka.spring.data.jdbc.sql.SqlGenerator;
20 | import cz.jirutka.spring.data.jdbc.sql.SqlGeneratorFactory;
21 | import org.springframework.beans.factory.InitializingBean;
22 | import org.springframework.beans.factory.annotation.Autowired;
23 | import org.springframework.core.GenericTypeResolver;
24 | import org.springframework.data.domain.Page;
25 | import org.springframework.data.domain.PageImpl;
26 | import org.springframework.data.domain.Pageable;
27 | import org.springframework.data.domain.Persistable;
28 | import org.springframework.data.domain.Sort;
29 | import org.springframework.data.repository.PagingAndSortingRepository;
30 | import org.springframework.data.repository.core.EntityInformation;
31 | import org.springframework.data.repository.core.support.PersistableEntityInformation;
32 | import org.springframework.data.repository.core.support.ReflectionEntityInformation;
33 | import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
34 | import org.springframework.jdbc.core.JdbcOperations;
35 | import org.springframework.jdbc.core.JdbcTemplate;
36 | import org.springframework.jdbc.core.PreparedStatementCreator;
37 | import org.springframework.jdbc.core.RowMapper;
38 | import org.springframework.jdbc.support.GeneratedKeyHolder;
39 | import org.springframework.util.Assert;
40 | import org.springframework.util.LinkedCaseInsensitiveMap;
41 |
42 | import javax.sql.DataSource;
43 | import java.io.Serializable;
44 | import java.sql.Connection;
45 | import java.sql.PreparedStatement;
46 | import java.sql.SQLException;
47 | import java.util.ArrayList;
48 | import java.util.Collections;
49 | import java.util.List;
50 | import java.util.Map;
51 |
52 | import static cz.jirutka.spring.data.jdbc.internal.IterableUtils.toList;
53 | import static cz.jirutka.spring.data.jdbc.internal.ObjectUtils.wrapToArray;
54 | import static java.util.Arrays.asList;
55 |
56 | /**
57 | * Implementation of {@link PagingAndSortingRepository} using {@link JdbcTemplate}
58 | */
59 | public abstract class BaseJdbcRepository
60 | implements JdbcRepository, InitializingBean {
61 |
62 | private final EntityInformation entityInfo;
63 | private final TableDescription table;
64 | private final RowMapper rowMapper;
65 | private final RowUnmapper rowUnmapper;
66 |
67 | // Read-only after initialization (invoking afterPropertiesSet()).
68 | private DataSource dataSource;
69 | private JdbcOperations jdbcOps;
70 | private SqlGeneratorFactory sqlGeneratorFactory = SqlGeneratorFactory.getInstance();
71 | private SqlGenerator sqlGenerator;
72 |
73 | private boolean initialized;
74 |
75 |
76 | public BaseJdbcRepository(EntityInformation entityInformation, RowMapper rowMapper,
77 | RowUnmapper rowUnmapper, TableDescription table) {
78 | Assert.notNull(rowMapper);
79 | Assert.notNull(table);
80 |
81 | this.entityInfo = entityInformation != null ? entityInformation : createEntityInformation();
82 | this.rowUnmapper = rowUnmapper != null ? rowUnmapper : new UnsupportedRowUnmapper();
83 | this.rowMapper = rowMapper;
84 | this.table = table;
85 | }
86 |
87 | public BaseJdbcRepository(RowMapper rowMapper, RowUnmapper rowUnmapper, TableDescription table) {
88 | this(null, rowMapper, rowUnmapper, table);
89 | }
90 |
91 | public BaseJdbcRepository(RowMapper rowMapper, RowUnmapper rowUnmapper, String tableName, String idColumn) {
92 | this(rowMapper, rowUnmapper, new TableDescription(tableName, idColumn));
93 | }
94 |
95 | public BaseJdbcRepository(RowMapper rowMapper, RowUnmapper rowUnmapper, String tableName) {
96 | this(rowMapper, rowUnmapper, new TableDescription(tableName, "id"));
97 | }
98 |
99 |
100 | @Override
101 | public void afterPropertiesSet() {
102 | Assert.notNull(dataSource, "dataSource must be provided");
103 |
104 | if (jdbcOps == null) {
105 | jdbcOps = new JdbcTemplate(dataSource);
106 | }
107 | if (sqlGenerator == null) {
108 | sqlGenerator = sqlGeneratorFactory.getGenerator(dataSource);
109 | }
110 | initialized = true;
111 | }
112 |
113 | /**
114 | * @param dataSource The DataSource to use (required).
115 | * @throws IllegalStateException if invoked after initialization
116 | * (i.e. after {@link #afterPropertiesSet()} has been invoked).
117 | */
118 | @Autowired
119 | public void setDataSource(DataSource dataSource) {
120 | throwOnChangeAfterInitialization("dataSource");
121 | this.dataSource = dataSource;
122 | }
123 |
124 | /**
125 | * @param jdbcOps If not set, {@link JdbcTemplate} is created.
126 | * @throws IllegalStateException if invoked after initialization
127 | * (i.e. after {@link #afterPropertiesSet()} has been invoked).
128 | */
129 | @Autowired(required = false)
130 | public void setJdbcOperations(JdbcOperations jdbcOps) {
131 | throwOnChangeAfterInitialization("jdbcOperations");
132 | this.jdbcOps = jdbcOps;
133 | }
134 |
135 | /**
136 | * @param sqlGeneratorFactory If not set, {@link SqlGeneratorFactory#getInstance()}
137 | * is used.
138 | * @throws IllegalStateException if invoked after initialization
139 | * (i.e. after {@link #afterPropertiesSet()} has been invoked).
140 | */
141 | @Autowired(required = false)
142 | public void setSqlGeneratorFactory(SqlGeneratorFactory sqlGeneratorFactory) {
143 | throwOnChangeAfterInitialization("sqlGeneratorFactory");
144 | this.sqlGeneratorFactory = sqlGeneratorFactory;
145 | }
146 |
147 | /**
148 | * @param sqlGenerator If not set, then it's obtained from
149 | * {@link SqlGeneratorFactory}.
150 | * @throws IllegalStateException if invoked after initialization
151 | * (i.e. after {@link #afterPropertiesSet()} has been invoked).
152 | */
153 | @Autowired(required = false)
154 | public void setSqlGenerator(SqlGenerator sqlGenerator) {
155 | throwOnChangeAfterInitialization("sqlGenerator");
156 | this.sqlGenerator = sqlGenerator;
157 | }
158 |
159 |
160 | ////////// Repository methods //////////
161 |
162 | @Override
163 | public long count() {
164 | return jdbcOps.queryForObject(sqlGenerator.count(table), Long.class);
165 | }
166 |
167 | @Override
168 | public void delete(ID id) {
169 | // Workaround for Groovy that cannot distinguish between two methods
170 | // with almost the same type erasure and always calls the former one.
171 | if (getEntityInfo().getJavaType().isInstance(id)) {
172 | // noinspection unchecked
173 | id = id((T) id);
174 | }
175 | jdbcOps.update(sqlGenerator.deleteById(table), wrapToArray(id));
176 | }
177 |
178 | @Override
179 | public void delete(T entity) {
180 | delete(id(entity));
181 | }
182 |
183 | @Override
184 | public void delete(Iterable extends T> entities) {
185 | List ids = ids(entities);
186 |
187 | if (!ids.isEmpty()) {
188 | jdbcOps.update(sqlGenerator.deleteByIds(table, ids.size()), flatten(ids));
189 | }
190 | }
191 |
192 | @Override
193 | public void deleteAll() {
194 | jdbcOps.update(sqlGenerator.deleteAll(table));
195 | }
196 |
197 | @Override
198 | public boolean exists(ID id) {
199 | return !jdbcOps.queryForList(
200 | sqlGenerator.existsById(table), wrapToArray(id), Integer.class).isEmpty();
201 | }
202 |
203 | @Override
204 | public List findAll() {
205 | return jdbcOps.query(sqlGenerator.selectAll(table), rowMapper);
206 | }
207 |
208 | @Override
209 | public T findOne(ID id) {
210 | List entityOrEmpty = jdbcOps.query(
211 | sqlGenerator.selectById(table), wrapToArray(id), rowMapper);
212 |
213 | return entityOrEmpty.isEmpty() ? null : entityOrEmpty.get(0);
214 | }
215 |
216 | @Override
217 | public S save(S entity) {
218 | return getEntityInfo().isNew(entity) ? insert(entity) : update(entity);
219 | }
220 |
221 | @Override
222 | public List save(Iterable entities) {
223 | List ret = new ArrayList<>();
224 | for (S s : entities) {
225 | ret.add(save(s));
226 | }
227 | return ret;
228 | }
229 |
230 | @Override
231 | public List findAll(Iterable ids) {
232 | List idsList = toList(ids);
233 |
234 | if (idsList.isEmpty()) {
235 | return Collections.emptyList();
236 | }
237 | return jdbcOps.query(
238 | sqlGenerator.selectByIds(table, idsList.size()), rowMapper, flatten(idsList));
239 | }
240 |
241 | @Override
242 | public List findAll(Sort sort) {
243 | return jdbcOps.query(sqlGenerator.selectAll(table, sort), rowMapper);
244 | }
245 |
246 | @Override
247 | public Page findAll(Pageable page) {
248 | String query = sqlGenerator.selectAll(table, page);
249 |
250 | return new PageImpl<>(jdbcOps.query(query, rowMapper), page, count());
251 | }
252 |
253 | @Override
254 | public S insert(S entity) {
255 | Map columns = preInsert(columns(entity), entity);
256 |
257 | return id(entity) == null
258 | ? insertWithAutoGeneratedKey(entity, columns)
259 | : insertWithManuallyAssignedKey(entity, columns);
260 | }
261 |
262 | @Override
263 | public S update(S entity) {
264 | Map columns = preUpdate(entity, columns(entity));
265 |
266 | List