#313 - Added examples showing basic usage of Spring Data JDBC.

Original pull request: #324.
This commit is contained in:
Jens Schauder
2017-04-12 16:06:24 +02:00
committed by Oliver Gierke
parent 9c2164ece6
commit 5d556d6d45
19 changed files with 839 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.experimental.UtilityClass;
/**
* Trivial class to print domain objects to the console in a somewhat readable format.
*
* @author Jens Schauder
*/
@UtilityClass
public class Output {
private final Logger LOG = LoggerFactory.getLogger(Output.class);
public static void list(Iterable<?> categories, String title) {
StringBuilder message = new StringBuilder(String.format("==== %s ====\n", title));
categories.forEach(category -> {
message.append(category.toString().replace(", ", ",\n\t"));
});
LOG.info(message.toString());
}
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.aggregate;
/**
* Age group for which a {@link LegoSet} is intended.
*
* @author Jens Schauder
*/
public enum AgeGroup {
_0to3,
_3to8,
_8to12,
_12andOlder
}

View File

@@ -0,0 +1,155 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.aggregate;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.jdbc.core.DataAccessStrategy;
import org.springframework.data.jdbc.core.DefaultDataAccessStrategy;
import org.springframework.data.jdbc.core.DelegatingDataAccessStrategy;
import org.springframework.data.jdbc.core.SqlGeneratorSource;
import org.springframework.data.jdbc.mapping.event.BeforeSave;
import org.springframework.data.jdbc.mapping.model.*;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.lang.Nullable;
import javax.sql.DataSource;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Jens Schauder
*/
@Configuration
@EnableJdbcRepositories
public class AggregateConfiguration {
@Bean
public ApplicationListener<?> idSetting() {
final AtomicInteger id = new AtomicInteger(0);
return (ApplicationListener<BeforeSave>) event -> {
Object entity = event.getEntity();
if (entity instanceof LegoSet) {
LegoSet legoSet = (LegoSet) entity;
if (legoSet.getId() == 0) {
legoSet.setId(id.incrementAndGet());
}
Manual manual = legoSet.getManual();
if (manual != null) {
manual.setId((long) legoSet.getId());
}
}
};
}
@Bean
public NamingStrategy namingStrategy() {
Map<String, String> tableAliases = new HashMap<String, String>();
tableAliases.put("Manual", "Handbuch");
Map<String, String> columnAliases = new HashMap<String, String>();
columnAliases.put("LegoSet.intMaximumAge", "maxAge");
columnAliases.put("LegoSet.intMinimumAge", "minAge");
columnAliases.put("Handbuch.id", "Handbuch_id");
Map<String, String> reverseColumnAliases = new HashMap<String, String>();
reverseColumnAliases.put("manual", "Handbuch_id");
Map<String, String> keyColumnAliases = new HashMap<String, String>();
keyColumnAliases.put("models", "name");
return new DefaultNamingStrategy() {
@Override
public String getColumnName(JdbcPersistentProperty property) {
String defaultName = super.getColumnName(property);
String key = getTableName(property.getOwner().getType()) + "." + defaultName;
return columnAliases.computeIfAbsent(key, __ -> defaultName);
}
@Override
public String getTableName(Class<?> type) {
return tableAliases.computeIfAbsent(super.getTableName(type),key -> key);
}
@Override
public String getReverseColumnName(JdbcPersistentProperty property) {
return reverseColumnAliases.computeIfAbsent(property.getName(), __ -> super.getReverseColumnName(property));
}
@Override
public String getKeyColumn(JdbcPersistentProperty property) {
return keyColumnAliases.computeIfAbsent(property.getName(), __ -> super.getKeyColumn(property));
}
};
}
@Bean
public ConversionCustomizer conversionCustomizer() {
return conversions -> conversions.addConverter(new Converter<Clob, String>() {
@Nullable
@Override
public String convert(Clob clob) {
try {
return Math.toIntExact(clob.length()) == 0 //
? "" //
: clob.getSubString(1, Math.toIntExact(clob.length()));
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert CLOB to String.", e);
}
}
});
}
// temporary workaround for https://jira.spring.io/browse/DATAJDBC-155
@Bean
DataAccessStrategy defaultDataAccessStrategy(JdbcMappingContext context, DataSource dataSource) {
NamedParameterJdbcOperations operations = new NamedParameterJdbcTemplate(dataSource);
DelegatingDataAccessStrategy accessStrategy = new DelegatingDataAccessStrategy();
accessStrategy.setDelegate(new DefaultDataAccessStrategy( //
new SqlGeneratorSource(context), //
operations, //
context, //
accessStrategy) //
);
return accessStrategy;
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.aggregate;
import lombok.Data;
import org.springframework.data.annotation.AccessType;
import org.springframework.data.annotation.AccessType.Type;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
/**
* A Lego Set consisting of multiple Blocks and a manual
*
* @author Jens Schauder
*/
@Data
@AccessType(Type.PROPERTY)
public class LegoSet {
@Id
private int id;
private String name;
@Transient
private Period minimumAge;
@Transient
private Period maximumAge;
/**
* Since Manuals are part of a {@link LegoSet} and only make sense inside a {@link LegoSet} it is considered part of the Aggregate.
*/
private Manual manual;
// You can build multiple models from one LegoSet
private final Map<String, Model> models = new HashMap<>();
// conversion for custom types currently has to be done through getters/setter + marking the underlying property with @Transient.
public int getIntMinimumAge() {
return toInt(this.minimumAge);
}
public void setIntMinimumAge(int years) {
minimumAge = toPeriod(years);
}
public int getIntMaximumAge() {
return toInt(this.maximumAge);
}
public void setIntMaximumAge(int years) {
maximumAge = toPeriod(years);
}
private static int toInt(Period period) {
return (int) (period == null ? 0 : period.get(ChronoUnit.YEARS));
}
private static Period toPeriod(int years) {
return Period.ofYears(years);
}
public void addModel(String name, String description) {
Model model = new Model();
model.name = name;
model.description = description;
models.put(name, model);
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.aggregate;
import org.springframework.data.repository.CrudRepository;
/**
* A repository for {@link LegoSet}.
* @author Jens Schauder
*/
public interface LegoSetRepository extends CrudRepository<LegoSet, Integer> {
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.aggregate;
import org.springframework.data.annotation.Id;
import lombok.Data;
/**
* A manual instructing how to assemble a {@link LegoSet}.
*
* @author Jens Schauder
*/
@Data
public class Manual {
Manual(String text, String author) {
this.id = null;
this.author = author;
this.text = text;
}
@Id
private Long id;
private String author;
private String text;
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.aggregate;
import lombok.ToString;
import org.springframework.data.annotation.Id;
/**
* One of potentially multiple models that can be build from a single {@link LegoSet}.
*
* No getters or setters needed.
*
* @author Jens Schauder
*/
@ToString
public class Model {
@Id
String name;
String description;
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.simpleentity;
import java.time.LocalDateTime;
import example.springdata.jdbc.basics.aggregate.AgeGroup;
import example.springdata.jdbc.basics.aggregate.LegoSet;
import org.springframework.data.annotation.Id;
import lombok.Data;
import lombok.Setter;
/**
* Coarse classification for {@link LegoSet}s, like "Car", "Plane", "Building" and so on.
*
* @author Jens Schauder
*/
@Data
public class Category {
public Category(String name, String description, AgeGroup ageGroup) {
this.id = null;
this.name = name;
this.description = description;
this.ageGroup = ageGroup;
}
@Id
private final Long id;
private String name;
private String description;
private LocalDateTime created = LocalDateTime.now();
@Setter
private long inserted;
public void timeStamp() {
if (inserted == 0) {
inserted = System.currentTimeMillis();
}
}
private AgeGroup ageGroup;
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.simpleentity;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jdbc.core.DataAccessStrategy;
import org.springframework.data.jdbc.core.DefaultDataAccessStrategy;
import org.springframework.data.jdbc.core.DelegatingDataAccessStrategy;
import org.springframework.data.jdbc.core.SqlGeneratorSource;
import org.springframework.data.jdbc.mapping.event.BeforeSave;
import org.springframework.data.jdbc.mapping.event.JdbcEvent;
import org.springframework.data.jdbc.mapping.model.JdbcMappingContext;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import javax.sql.DataSource;
/**
* Contains infrastructure necessary for creating repositories and two listeners.
* <p>
* Not that a listener may change an entity without any problem.
*
* @author Jens Schauder
*/
@Configuration
@EnableJdbcRepositories
public class CategoryConfiguration {
@Bean
public ApplicationListener<?> loggingListener() {
return (ApplicationListener<ApplicationEvent>) event -> {
if (event instanceof JdbcEvent) {
System.out.println("received an event: " + event);
}
};
}
@Bean
public ApplicationListener<BeforeSave> timeStampingSaveTime() {
return event -> {
Object entity = event.getEntity();
if (entity instanceof Category) {
Category category = (Category) entity;
category.timeStamp();
}
};
}
// temporary workaround for https://jira.spring.io/browse/DATAJDBC-155
@Bean
DataAccessStrategy defaultDataAccessStrategy(JdbcMappingContext context, DataSource dataSource) {
NamedParameterJdbcOperations operations = new NamedParameterJdbcTemplate(dataSource);
DelegatingDataAccessStrategy accessStrategy = new DelegatingDataAccessStrategy();
accessStrategy.setDelegate(new DefaultDataAccessStrategy( //
new SqlGeneratorSource(context), //
operations, //
context, //
accessStrategy) //
);
return accessStrategy;
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.jdbc.basics.simpleentity;
import org.springframework.data.repository.CrudRepository;
/**
* Repository for Categories.
*
* @author Jens Schauder
*/
public interface CategoryRepository extends CrudRepository<Category, Long> {
}

View File

@@ -0,0 +1,2 @@
logging.level.org.springframework.data=INFO
logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG

View File

@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS category (id INTEGER IDENTITY PRIMARY KEY, name VARCHAR(100), description VARCHAR(2000), agegroup VARCHAR(20), created DATETIME, inserted BIGINT);
CREATE TABLE IF NOT EXISTS LegoSet (id INTEGER, name VARCHAR(100), minAge INTEGER, maxAge INTEGER);
CREATE TABLE IF NOT EXISTS Handbuch (handbuch_id INTEGER, author CHAR(100), text CLOB);
CREATE TABLE IF NOT EXISTS Model (name VARCHAR(100), description CLOB, legoset INTEGER);

View File

@@ -0,0 +1,71 @@
package example.springdata.jdbc.basics.aggregate;/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import example.springdata.jdbc.basics.Output;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureJdbc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.Period;
/**
* Demonstrates various possibilities to customize the behavior of a repository.
*
* @author Jens Schauder
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AggregateConfiguration.class)
@AutoConfigureJdbc
public class AggregateTests {
@Autowired
private LegoSetRepository repository;
@Test
public void exerciseSomewhatComplexEntity() {
LegoSet smallCar = createLegoSet();
smallCar.setManual(new Manual("Just put all the pieces together in the right order", "Jens Schauder"));
smallCar.addModel("suv", "SUV with sliding doors.");
smallCar.addModel("roadster", "Slick red roadster.");
repository.save(smallCar);
Output.list(repository.findAll(), "Original LegoSet");
smallCar.getManual().setText("Just make it so it looks like a car.");
smallCar.addModel("pickup", "A pickup truck with some tools in the back.");
repository.save(smallCar);
Output.list(repository.findAll(), "Updated");
smallCar.setManual(new Manual("One last attempt: Just build a car! Ok?", "Jens Schauder"));
repository.save(smallCar);
Output.list(repository.findAll(), "Manual replaced");
}
private LegoSet createLegoSet() {
LegoSet smallCar = new LegoSet();
smallCar.setName("Small Car 01");
smallCar.setMinimumAge(Period.ofYears(5));
smallCar.setMaximumAge(Period.ofYears(12));
return smallCar;
}
}

View File

@@ -0,0 +1,67 @@
package example.springdata.jdbc.basics.simpleentity;/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import example.springdata.jdbc.basics.Output;
import example.springdata.jdbc.basics.aggregate.AgeGroup;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureJdbc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Demonstrates simple CRUD operations with a simple entity without any references.
*
* @author Jens Schauder
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CategoryConfiguration.class)
@AutoConfigureJdbc
public class SimpleEntityTests {
@Autowired
private CategoryRepository repository;
@Test
public void exerciseRepositoryForSimpleEntity() {
// create some categories
Category cars = new Category("Cars", "Anything that has approximately 4 wheels", AgeGroup._3to8);
Category buildings = new Category("Buildings", null, AgeGroup._12andOlder);
// save categories
repository.saveAll(asList(cars, buildings));
Output.list(repository.findAll(), "`Cars` and `Buildings` got saved");
assertThat(cars.getId()).isNotNull();
assertThat(buildings.getId()).isNotNull();
// update one
buildings.setDescription("Famous and impressive buildings incl. the 'bike shed'.");
repository.save(buildings);
Output.list(repository.findAll(), "`Buildings` has a description");
// delete stuff again
repository.delete(cars);
Output.list(repository.findAll(), "`Cars` is gone.");
}
}