This commit is contained in:
Kevin Gilmore 2016-02-06 11:42:21 -06:00
commit d8ebf49f2d
208 changed files with 4563 additions and 599 deletions

View File

@ -6,12 +6,12 @@ import java.util.function.Function;
public class AdderImpl implements Adder { public class AdderImpl implements Adder {
@Override @Override
public String addWithFunction(Function<String, String> f) { public String addWithFunction(final Function<String, String> f) {
return f.apply("Something "); return f.apply("Something ");
} }
@Override @Override
public void addWithConsumer(Consumer<Integer> f) { public void addWithConsumer(final Consumer<Integer> f) {
} }
} }

View File

@ -0,0 +1,88 @@
package com.baeldung.doublecolon;
public class Computer {
private Integer age;
private String color;
private Integer healty;
public Computer(final int age, final String color) {
this.age = age;
this.color = color;
}
public Computer(final Integer age, final String color, final Integer healty) {
this.age = age;
this.color = color;
this.healty = healty;
}
public Computer() {
}
public Integer getAge() {
return age;
}
public void setAge(final Integer age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(final String color) {
this.color = color;
}
public Integer getHealty() {
return healty;
}
public void setHealty(final Integer healty) {
this.healty = healty;
}
public void turnOnPc() {
System.out.println("Computer turned on");
}
public void turnOffPc() {
System.out.println("Computer turned off");
}
public Double calculateValue(Double initialValue) {
return initialValue / 1.50;
}
@Override
public String toString() {
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Computer computer = (Computer) o;
if (age != null ? !age.equals(computer.age) : computer.age != null) {
return false;
}
return color != null ? color.equals(computer.color) : computer.color == null;
}
@Override
public int hashCode() {
int result = age != null ? age.hashCode() : 0;
result = 31 * result + (color != null ? color.hashCode() : 0);
return result;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.doublecolon;
import com.baeldung.doublecolon.function.ComputerPredicate;
import java.util.ArrayList;
import java.util.List;
public class ComputerUtils {
public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
public static List<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
final List<Computer> result = new ArrayList<>();
inventory.stream().filter(p::filter).forEach(result::add);
return result;
}
public static void repair(final Computer computer) {
if (computer.getHealty() < 50) {
computer.setHealty(100);
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.doublecolon;
import java.util.function.Function;
public class MacbookPro extends Computer {
public MacbookPro(int age, String color) {
super(age, color);
}
public MacbookPro(Integer age, String color, Integer healty) {
super(age, color, healty);
}
@Override
public void turnOnPc() {
System.out.println("MacbookPro turned on");
}
@Override
public void turnOffPc() {
System.out.println("MacbookPro turned off");
}
@Override
public Double calculateValue(Double initialValue) {
Function<Double, Double> function = super::calculateValue;
final Double pcValue = function.apply(initialValue);
System.out.println("First value is:" + pcValue);
return pcValue + (initialValue / 10);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.doublecolon.function;
import com.baeldung.doublecolon.Computer;
@FunctionalInterface
public interface ComputerPredicate {
boolean filter(Computer c);
}

View File

@ -0,0 +1,15 @@
package com.baeldung.doublecolon.function;
import java.util.Objects;
import java.util.function.Function;
@FunctionalInterface
public interface TriFunction<A, B, C, R> {
R apply(A a, B b, C c);
default <V> TriFunction<A, B, C, V> andThen(final Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.doublecolon;
import com.baeldung.doublecolon.function.TriFunction;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.function.BiFunction;
import static com.baeldung.doublecolon.ComputerUtils.*;
public class TestComputerUtils {
@Before
public void setup() {
}
@After
public void tearDown() {
}
@Test
public void testConstructorReference() {
Computer c1 = new Computer(2015, "white");
Computer c2 = new Computer(2009, "black");
Computer c3 = new Computer(2014, "black");
BiFunction<Integer, String, Computer> c4Function = Computer::new;
Computer c4 = c4Function.apply(2013, "white");
BiFunction<Integer, String, Computer> c5Function = Computer::new;
Computer c5 = c5Function.apply(2010, "black");
BiFunction<Integer, String, Computer> c6Function = Computer::new;
Computer c6 = c6Function.apply(2008, "black");
List<Computer> inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
List<Computer> blackComputer = filter(inventory, blackPredicate);
Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
List<Computer> after2010Computer = filter(inventory, after2010Predicate);
Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
List<Computer> before2011Computer = filter(inventory, c -> c.getAge() < 2011);
Assert.assertEquals("The Computer bought before 2011 are: ", before2011Computer.size(), 3);
inventory.sort(Comparator.comparing(Computer::getAge));
Assert.assertEquals("Oldest Computer in inventory", c6, inventory.get(0));
}
@Test
public void testStaticMethodReference() {
Computer c1 = new Computer(2015, "white", 35);
Computer c2 = new Computer(2009, "black", 65);
TriFunction<Integer, String, Integer, Computer> c6Function = Computer::new;
Computer c3 = c6Function.apply(2008, "black", 90);
List<Computer> inventory = Arrays.asList(c1, c2, c3);
inventory.forEach(ComputerUtils::repair);
Assert.assertEquals("Computer repaired", new Integer(100), c1.getHealty());
}
@Test
public void testInstanceMethodArbitraryObjectParticularType() {
Computer c1 = new Computer(2015, "white", 35);
Computer c2 = new MacbookPro(2009, "black", 65);
List<Computer> inventory = Arrays.asList(c1, c2);
inventory.forEach(Computer::turnOnPc);
}
@Test
public void testSuperMethodReference() {
final TriFunction<Integer, String, Integer, MacbookPro> integerStringIntegerObjectTriFunction = MacbookPro::new;
final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
Double initialValue = new Double(999.99);
final Double actualValue = macbookPro.calculateValue(initialValue);
Assert.assertEquals(766.659, actualValue, 0.0);
}
}

View File

@ -30,6 +30,14 @@ public class Java8CollectionCleanupUnitTest {
assertThat(listWithoutNulls, hasSize(3)); assertThat(listWithoutNulls, hasSize(3));
} }
@Test
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
listWithoutNulls.removeIf(p -> p == null);
assertThat(listWithoutNulls, hasSize(3));
}
@Test @Test
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() { public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3); final List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);

View File

@ -0,0 +1,70 @@
package org.baeldung.java;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import com.google.common.collect.Lists;
public class CollectionJavaPartitionUnitTest {
// java8 groupBy
@Test
public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final Map<Integer, List<Integer>> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
// When
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(3));
assertThat(lastPartition, equalTo(expectedLastPartition));
// intList.add(9);
// System.out.println(groups.values());
}
// java8 partitionBy
@Test
public final void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final Map<Boolean, List<Integer>> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
// When
final List<Integer> lastPartition = subSets.get(1);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(2));
assertThat(lastPartition, equalTo(expectedLastPartition));
// intList.add(9);
// System.out.println(groups.values());
}
// java8 split by separator
@Test
public final void givenList_whenSplittingBySeparator_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
final int[] indexes = Stream.of(IntStream.of(-1), IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), IntStream.of(intList.size())).flatMapToInt(s -> s).toArray();
final List<List<Integer>> subSets = IntStream.range(0, indexes.length - 1).mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])).collect(Collectors.toList());
// When
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(3));
assertThat(lastPartition, equalTo(expectedLastPartition));
}
}

View File

@ -0,0 +1,10 @@
{
"name":
{
"first": "Tatu",
"last": "Saloranta"
},
"title": "Jackson founder",
"company": "FasterXML"
}

View File

@ -0,0 +1,17 @@
package org.baeldung.jackson.node;
import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ExampleStructure {
private static ObjectMapper mapper = new ObjectMapper();
static JsonNode getExampleRoot() throws IOException {
InputStream exampleInput = ExampleStructure.class.getClassLoader().getResourceAsStream("node_example.json");
JsonNode rootNode = mapper.readTree(exampleInput);
return rootNode;
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.jackson.node;
public class NodeBean {
private int id;
private String name;
public NodeBean() {
}
public NodeBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,103 @@
package org.baeldung.jackson.node;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class NodeOperationTest {
private static ObjectMapper mapper = new ObjectMapper();
@Test
public void givenAnObject_whenConvertingIntoNode_thenCorrect() {
final NodeBean fromValue = new NodeBean(2016, "baeldung.com");
final JsonNode node = mapper.valueToTree(fromValue);
assertEquals(2016, node.get("id").intValue());
assertEquals("baeldung.com", node.get("name").textValue());
}
@Test
public void givenANode_whenWritingOutAsAJsonString_thenCorrect() throws IOException {
final String pathToTestFile = "node_to_json_test.json";
final char[] characterBuffer = new char[50];
final JsonNode node = mapper.createObjectNode();
((ObjectNode) node).put("id", 2016);
((ObjectNode) node).put("name", "baeldung.com");
try (FileWriter outputStream = new FileWriter(pathToTestFile)) {
mapper.writeValue(outputStream, node);
}
try (FileReader inputStreamForAssertion = new FileReader(pathToTestFile)) {
inputStreamForAssertion.read(characterBuffer);
}
final String textContentOfTestFile = new String(characterBuffer);
assertThat(textContentOfTestFile, containsString("2016"));
assertThat(textContentOfTestFile, containsString("baeldung.com"));
Files.delete(Paths.get(pathToTestFile));
}
@Test
public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException {
final JsonNode node = mapper.createObjectNode();
((ObjectNode) node).put("id", 2016);
((ObjectNode) node).put("name", "baeldung.com");
final NodeBean toValue = mapper.treeToValue(node, NodeBean.class);
assertEquals(2016, toValue.getId());
assertEquals("baeldung.com", toValue.getName());
}
@Test
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
final JsonNode rootNode = ExampleStructure.getExampleRoot();
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
addedNode.put("city", "Seattle").put("state", "Washington").put("country", "United States");
assertFalse(rootNode.path("address").isMissingNode());
assertEquals("Seattle", rootNode.path("address").path("city").textValue());
assertEquals("Washington", rootNode.path("address").path("state").textValue());
assertEquals("United States", rootNode.path("address").path("country").textValue());
}
@Test
public void givenANode_whenModifyingIt_thenCorrect() throws IOException {
final String newString = "{\"nick\": \"cowtowncoder\"}";
final JsonNode newNode = mapper.readTree(newString);
final JsonNode rootNode = ExampleStructure.getExampleRoot();
((ObjectNode) rootNode).set("name", newNode);
assertFalse(rootNode.path("name").path("nick").isMissingNode());
assertEquals("cowtowncoder", rootNode.path("name").path("nick").textValue());
}
@Test
public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException {
final JsonNode rootNode = ExampleStructure.getExampleRoot();
((ObjectNode) rootNode).remove("company");
assertTrue(rootNode.path("company").isMissingNode());
}
}

13
mockito-mocks-spring-beans/.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>mockito-mocks-spring-beans</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mocks</name>
<description>Injecting Mockito Mocks into Spring Beans</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.3.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MocksApplication {
public static void main(String[] args) {
SpringApplication.run(MocksApplication.class, args);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung;
import org.springframework.stereotype.Service;
@Service
public class NameService {
public String getUserName(String id) {
return "Real user name";
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private NameService nameService;
@Autowired
public UserService(NameService nameService) {
this.nameService = nameService;
}
public String getUserName(String id) {
return nameService.getUserName(id);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
@Profile("test")
@Configuration
public class NameServiceTestConfiguration {
@Bean
@Primary
public NameService nameService() {
return Mockito.mock(NameService.class);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MocksApplication.class)
public class UserServiceTest {
@Autowired
private UserService userService;
@Autowired
private NameService nameService;
@Test
public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name");
String testName = userService.getUserName("SomeId");
Assert.assertEquals("Mock user name", testName);
}
}

View File

@ -10,5 +10,5 @@ import java.lang.annotation.Target;
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })
@Documented @Documented
public @interface DataAccess { public @interface DataAccess {
Class<?>entity(); Class<?> entity();
} }

View File

@ -19,15 +19,13 @@ public class DataAccessAnnotationProcessor implements BeanPostProcessor {
} }
@Override @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
throws BeansException {
scanDataAccessAnnotation(bean, beanName); scanDataAccessAnnotation(bean, beanName);
return bean; return bean;
} }
@Override @Override
public Object postProcessAfterInitialization(Object bean, String beanName) public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
throws BeansException {
return bean; return bean;
} }

View File

@ -12,18 +12,14 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.ReflectionUtils; import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback; import org.springframework.util.ReflectionUtils.FieldCallback;
public final class DataAccessFieldCallback implements FieldCallback { public final class DataAccessFieldCallback implements FieldCallback {
private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class); private static Logger logger = LoggerFactory.getLogger(DataAccessFieldCallback.class);
private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; private static int AUTOWIRE_MODE = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " private static String ERROR_ENTITY_VALUE_NOT_SAME = "@DataAccess(entity) " + "value should have same type with injected generic type.";
+ "value should have same type with injected generic type."; private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " + "to raw (non-generic) declaration. This will make your code less type-safe.";
private static String WARN_NON_GENERIC_VALUE = "@DataAccess annotation assigned " private static String ERROR_CREATE_INSTANCE = "Cannot create instance of " + "type '{}' or instance creation is failed because: {}";
+ "to raw (non-generic) declaration. This will make your code less type-safe.";
private static String ERROR_CREATE_INSTANCE = "Cannot create instance of "
+ "type '{}' or instance creation is failed because: {}";
private ConfigurableListableBeanFactory configurableListableBeanFactory; private ConfigurableListableBeanFactory configurableListableBeanFactory;
private Object bean; private Object bean;
@ -34,15 +30,14 @@ public final class DataAccessFieldCallback implements FieldCallback {
} }
@Override @Override
public void doWith(final Field field) public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
throws IllegalArgumentException, IllegalAccessException {
if (!field.isAnnotationPresent(DataAccess.class)) { if (!field.isAnnotationPresent(DataAccess.class)) {
return; return;
} }
ReflectionUtils.makeAccessible(field); ReflectionUtils.makeAccessible(field);
final Type fieldGenericType = field.getGenericType(); final Type fieldGenericType = field.getGenericType();
// In this example, get actual "GenericDAO' type. // In this example, get actual "GenericDAO' type.
final Class<?> generic = field.getType(); final Class<?> generic = field.getType();
final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity(); final Class<?> classValue = field.getDeclaredAnnotation(DataAccess.class).entity();
if (genericTypeIsValid(classValue, fieldGenericType)) { if (genericTypeIsValid(classValue, fieldGenericType)) {
@ -54,7 +49,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
} }
} }
/** /**
* For example, if user write: * For example, if user write:
* <pre> * <pre>
@ -75,8 +69,6 @@ public final class DataAccessFieldCallback implements FieldCallback {
} }
} }
public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) { public final Object getBeanInstance(final String beanName, final Class<?> genericClass, final Class<?> paramClass) {
Object daoInstance = null; Object daoInstance = null;
if (!configurableListableBeanFactory.containsBean(beanName)) { if (!configurableListableBeanFactory.containsBean(beanName)) {
@ -90,7 +82,7 @@ public final class DataAccessFieldCallback implements FieldCallback {
logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e); logger.error(ERROR_CREATE_INSTANCE, genericClass.getTypeName(), e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName); daoInstance = configurableListableBeanFactory.initializeBean(toRegister, beanName);
configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true); configurableListableBeanFactory.autowireBeanProperties(daoInstance, AUTOWIRE_MODE, true);
configurableListableBeanFactory.registerSingleton(beanName, daoInstance); configurableListableBeanFactory.registerSingleton(beanName, daoInstance);

View File

@ -5,10 +5,11 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
public class BeanWithGenericDAO { public class BeanWithGenericDAO {
@DataAccess(entity=Person.class) @DataAccess(entity = Person.class)
private GenericDAO<Person> personGenericDAO; private GenericDAO<Person> personGenericDAO;
public BeanWithGenericDAO() {} public BeanWithGenericDAO() {
}
public GenericDAO<Person> getPersonGenericDAO() { public GenericDAO<Person> getPersonGenericDAO() {
return personGenericDAO; return personGenericDAO;

View File

@ -15,7 +15,6 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CustomAnnotationConfiguration.class }) @ContextConfiguration(classes = { CustomAnnotationConfiguration.class })
public class DataAccessFieldCallbackTest { public class DataAccessFieldCallbackTest {
@ -36,8 +35,7 @@ public class DataAccessFieldCallbackTest {
} }
@Test @Test
public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() public void whenMethodGenericTypeIsValidCalled_thenReturnCorrectValue() throws NoSuchFieldException, SecurityException {
throws NoSuchFieldException, SecurityException {
final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO); final DataAccessFieldCallback callback = new DataAccessFieldCallback(configurableListableBeanFactory, beanWithGenericDAO);
final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType(); final Type fieldType = BeanWithGenericDAO.class.getDeclaredField("personGenericDAO").getGenericType();
final boolean result = callback.genericTypeIsValid(Person.class, fieldType); final boolean result = callback.genericTypeIsValid(Person.class, fieldType);

1
spring-batch/README.md Normal file
View File

@ -0,0 +1 @@

View File

@ -40,8 +40,7 @@ public class SpringBatchConfig {
private Resource outputXml; private Resource outputXml;
@Bean @Bean
public ItemReader<Transaction> itemReader() public ItemReader<Transaction> itemReader() throws UnexpectedInputException, ParseException {
throws UnexpectedInputException, ParseException {
FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>(); FlatFileItemReader<Transaction> reader = new FlatFileItemReader<Transaction>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
String[] tokens = { "username", "userid", "transactiondate", "amount" }; String[] tokens = { "username", "userid", "transactiondate", "amount" };
@ -61,8 +60,7 @@ public class SpringBatchConfig {
} }
@Bean @Bean
public ItemWriter<Transaction> itemWriter(Marshaller marshaller) public ItemWriter<Transaction> itemWriter(Marshaller marshaller) throws MalformedURLException {
throws MalformedURLException {
StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<Transaction>(); StaxEventItemWriter<Transaction> itemWriter = new StaxEventItemWriter<Transaction>();
itemWriter.setMarshaller(marshaller); itemWriter.setMarshaller(marshaller);
itemWriter.setRootTagName("transactionRecord"); itemWriter.setRootTagName("transactionRecord");
@ -78,11 +76,8 @@ public class SpringBatchConfig {
} }
@Bean @Bean
protected Step step1(ItemReader<Transaction> reader, protected Step step1(ItemReader<Transaction> reader, ItemProcessor<Transaction, Transaction> processor, ItemWriter<Transaction> writer) {
ItemProcessor<Transaction, Transaction> processor, return steps.get("step1").<Transaction, Transaction> chunk(10).reader(reader).processor(processor).writer(writer).build();
ItemWriter<Transaction> writer) {
return steps.get("step1").<Transaction, Transaction> chunk(10)
.reader(reader).processor(processor).writer(writer).build();
} }
@Bean(name = "firstBatchJob") @Bean(name = "firstBatchJob")

View File

@ -38,8 +38,7 @@ public class SpringConfig {
} }
@Bean @Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException {
throws MalformedURLException {
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(dropReopsitoryTables); databasePopulator.addScript(dropReopsitoryTables);

View File

@ -48,9 +48,7 @@ public class Transaction {
@Override @Override
public String toString() { public String toString() {
return "Transaction [username=" + username + ", userId=" + userId return "Transaction [username=" + username + ", userId=" + userId + ", transactionDate=" + transactionDate + ", amount=" + amount + "]";
+ ", transactionDate=" + transactionDate + ", amount=" + amount
+ "]";
} }
} }

View File

@ -3,8 +3,7 @@ package org.baeldung.spring_batch_intro.service;
import org.baeldung.spring_batch_intro.model.Transaction; import org.baeldung.spring_batch_intro.model.Transaction;
import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemProcessor;
public class CustomItemProcessor implements public class CustomItemProcessor implements ItemProcessor<Transaction, Transaction> {
ItemProcessor<Transaction, Transaction> {
public Transaction process(Transaction item) { public Transaction process(Transaction item) {
System.out.println("Processing..." + item); System.out.println("Processing..." + item);

View File

@ -11,8 +11,11 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.2.3.RELEASE</org.springframework.version>
<org.springframework.data.version>1.3.2.RELEASE</org.springframework.data.version> <org.springframework.data.version>1.3.2.RELEASE</org.springframework.data.version>
<org.springframework.version>4.2.2.RELEASE</org.springframework.version>
<junit.version>4.11</junit.version> <junit.version>4.11</junit.version>
<org.slf4j.version>1.7.12</org.slf4j.version> <org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version> <logback.version>1.1.3</logback.version>

View File

@ -11,12 +11,12 @@
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name> <name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>

View File

@ -117,9 +117,11 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.2.4.RELEASE</org.springframework.version>
<org.springframework.data.version>1.7.1.RELEASE</org.springframework.data.version> <org.springframework.data.version>1.7.1.RELEASE</org.springframework.data.version>
<org.springframework.version>4.2.2.RELEASE</org.springframework.version>
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version> <junit.version>4.11</junit.version>
<rest-assured.version>2.4.1</rest-assured.version> <rest-assured.version>2.4.1</rest-assured.version>

View File

@ -9,6 +9,7 @@ import com.mongodb.DBObject;
@Component @Component
public class UserWriterConverter implements Converter<User, DBObject> { public class UserWriterConverter implements Converter<User, DBObject> {
@Override @Override
public DBObject convert(final User user) { public DBObject convert(final User user) {
final DBObject dbObject = new BasicDBObject(); final DBObject dbObject = new BasicDBObject();
@ -22,4 +23,5 @@ public class UserWriterConverter implements Converter<User, DBObject> {
dbObject.removeField("_class"); dbObject.removeField("_class");
return dbObject; return dbObject;
} }
} }

View File

@ -0,0 +1,15 @@
## Spring Data Redis
### Relevant Articles:
- [Introduction to Spring Data Redis]
### Build the Project with Tests Running
```
mvn clean install
```
### Run Tests Directly
```
mvn test
```

76
spring-data-redis/pom.xml Normal file
View File

@ -0,0 +1,76 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>sprint-data-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.2.2.RELEASE</spring.version>
<spring-data-redis>1.6.2.RELEASE</spring-data-redis>
<nosqlunit.version>0.8.0</nosqlunit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring-data-redis}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.5.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-redis</artifactId>
<version>${nosqlunit.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,24 @@
package org.baeldung.spring.data.redis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
@ComponentScan("org.baeldung.spring.data.redis")
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
final RedisTemplate< String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}

View File

@ -0,0 +1,59 @@
package org.baeldung.spring.data.redis.model;
import java.io.Serializable;
public class Student implements Serializable {
public enum Gender {
MALE, FEMALE
}
private String id;
private String name;
private Gender gender;
private int grade;
public Student(String id, String name, Gender gender, int grade) {
this.id = id;
this.name = name;
this.gender = gender;
this.grade = grade;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", gender=" + gender + ", grade=" + grade + '}';
}
}

View File

@ -0,0 +1,20 @@
package org.baeldung.spring.data.redis.repo;
import org.baeldung.spring.data.redis.model.Student;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
public interface StudentRepository {
void saveStudent(Student person);
void updateStudent(Student student);
Student findStudent(String id);
Map<Object, Object> findAllStudents();
void deleteStudent(String id);
}

View File

@ -0,0 +1,49 @@
package org.baeldung.spring.data.redis.repo;
import org.baeldung.spring.data.redis.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import java.util.Map;
@Repository
public class StudentRepositoryImpl implements StudentRepository {
private static final String KEY = "Student";
private RedisTemplate<String, Object> redisTemplate;
private HashOperations hashOperations;
@Autowired
public StudentRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@PostConstruct
private void init() {
hashOperations = redisTemplate.opsForHash();
}
public void saveStudent(final Student student) {
hashOperations.put(KEY, student.getId(), student);
}
public void updateStudent(final Student student) {
hashOperations.put(KEY, student.getId(), student);
}
public Student findStudent(final String id) {
return (Student) hashOperations.get(KEY, id);
}
public Map<Object, Object> findAllStudents() {
return hashOperations.entries(KEY);
}
public void deleteStudent(final String id) {
hashOperations.delete(KEY, id);
}
}

View File

@ -0,0 +1,20 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

Binary file not shown.

After

Width:  |  Height:  |  Size: 855 B

View File

@ -0,0 +1,60 @@
package org.baeldung.spring.data.redis.repo;
import org.baeldung.spring.data.redis.config.RedisConfig;
import org.baeldung.spring.data.redis.model.Student;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RedisConfig.class)
public class StudentRepositoryTest {
@Autowired
private StudentRepository studentRepository;
@Test
public void whenSavingStudent_thenAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.saveStudent(student);
final Student retrievedStudent = studentRepository.findStudent(student.getId());
assertEquals(student.getId(), retrievedStudent.getId());
}
@Test
public void whenUpdatingStudent_thenAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.saveStudent(student);
student.setName("Richard Watson");
studentRepository.saveStudent(student);
final Student retrievedStudent = studentRepository.findStudent(student.getId());
assertEquals(student.getName(), retrievedStudent.getName());
}
@Test
public void whenSavingStudents_thenAllShouldAvailableOnRetrieval() throws Exception {
final Student engStudent = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
final Student medStudent = new Student("Med2015001", "Gareth Houston", Student.Gender.MALE, 2);
studentRepository.saveStudent(engStudent);
studentRepository.saveStudent(medStudent);
final Map<Object, Object> retrievedStudent = studentRepository.findAllStudents();
assertEquals(retrievedStudent.size(), 2);
}
@Test
public void whenDeletingStudent_thenNotAvailableOnRetrieval() throws Exception {
final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
studentRepository.saveStudent(student);
studentRepository.deleteStudent(student.getId());
final Student retrievedStudent = studentRepository.findStudent(student.getId());
assertNull(retrievedStudent);
}
}

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class ChildDao extends AbstractHibernateDao<Child>implements IChildDao { public class ChildDao extends AbstractHibernateDao<Child> implements IChildDao {
@Autowired @Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class FooDao extends AbstractHibernateDao<Foo>implements IFooDao { public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
@Autowired @Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;

View File

@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class ParentDao extends AbstractHibernateDao<Parent>implements IParentDao { public class ParentDao extends AbstractHibernateDao<Parent> implements IParentDao {
@Autowired @Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ChildService extends AbstractService<Child>implements IChildService { public class ChildService extends AbstractService<Child> implements IChildService {
@Autowired @Autowired
private IChildDao dao; private IChildDao dao;

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class FooService extends AbstractService<Foo>implements IFooService { public class FooService extends AbstractService<Foo> implements IFooService {
@Autowired @Autowired
private IFooDao dao; private IFooDao dao;

View File

@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ParentService extends AbstractService<Parent>implements IParentService { public class ParentService extends AbstractService<Parent> implements IParentService {
@Autowired @Autowired
private IParentDao dao; private IParentDao dao;

1
spring-freemarker/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

86
spring-freemarker/pom.xml Normal file
View File

@ -0,0 +1,86 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.freemarker.example</groupId>
<artifactId>spring4-freemarker-example</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Spring Freemarker Example</name>
<properties>
<jdk.version>1.8</jdk.version>
<spring.version>4.2.4.RELEASE</spring.version>
<freemarker.version>2.3.23</freemarker.version>
<logback.version>1.1.3</logback.version>
<jcl.slf4j.version>1.7.12</jcl.slf4j.version>
<servletapi.version>3.1.0</servletapi.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${jcl.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<!-- compile only, deployed container will provide this -->
<!-- Need this for config annotation -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servletapi.version}</version>
<scope>provided</scope>
</dependency>
<!-- Freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<failOnMissingWebXml>true</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,38 @@
package com.baeldung.freemarker.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
@EnableWebMvc
@Configuration
@ComponentScan({"com.baeldung.freemarker"})
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public FreeMarkerViewResolver freemarkerViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(true);
resolver.setPrefix("");
resolver.setSuffix(".ftl");
return resolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
return freeMarkerConfigurer;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.freemarker.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.freemarker.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.baeldung.freemarker.model.Car;
@Controller
public class SpringController {
private static List<Car> carList = new ArrayList<Car>();
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "redirect:/cars";
}
static {
carList.add(new Car("Honda", "Civic"));
carList.add(new Car("Toyota", "Camry"));
carList.add(new Car("Nissan", "Altima"));
}
@RequestMapping(value = "/cars", method = RequestMethod.GET)
public String init(@ModelAttribute("model") ModelMap model) {
model.addAttribute("carList", carList);
return "index";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addCar(@ModelAttribute("car") Car car) {
if (null != car && null != car.getMake() && null != car.getModel()
&& !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
carList.add(car);
}
return "redirect:/cars";
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.freemarker.model;
public class Car {
private String make;
private String model;
public Car(){
}
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p: %c - %m%n" />
</layout>
</appender>
<!-- Application Loggers -->
<logger name="com.spring.freemarker">
<level value="info" />
</logger>
<!-- 3rdparty Loggers -->
<logger name="org.springframework.core">
<level value="info" />
</logger>
<logger name="org.springframework.beans">
<level value="info" />
</logger>
<logger name="org.springframework.context">
<level value="info" />
</logger>
<logger name="org.springframework.web">
<level value="info" />
</logger>
<!-- Root Logger -->
<root>
<priority value="warn" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@ -0,0 +1,61 @@
<html>
<head><title> FreeMarker Spring MVC Hello World</title>
<style>
body, input {
font-family: Calibri, Arial;
margin: 0px;
padding: 0px;
}
#header h2 {
color: white;
background-color: #3275A8;
height: 50px;
padding: 5px 0 0 5px;
font-size: 20px;
}
.datatable {margin-bottom:5px;border:1px solid #eee;border-collapse:collapse;width:400px;max-width:100%;font-family:Calibri}
.datatable th {padding:3px;border:1px solid #888;height:30px;background-color:#B2D487;text-align:center;vertical-align:middle;color:#444444}
.datatable tr {border:1px solid #888}
.datatable tr.odd {background-color:#eee}
.datatable td {padding:2px;border:1px solid #888}
#content { padding 5px; margin: 5px; text-align: center}
fieldset { width: 300px; padding: 5px; margin-bottom: 0px; }
legend { font-weight: bold; }
</style>
<body>
<div id="header">
<H2>
FreeMarker Spring MVC Hello World
</H2>
</div>
<div id="content">
<fieldset>
<legend>Add Car</legend>
<form name="car" action="add" method="post">
Make : <input type="text" name="make" /> <br/>
Model: <input type="text" name="model" /> <br/>
<input type="submit" value=" Save " />
</form>
</fieldset>
<br/>
<table class="datatable">
<tr>
<th>Make</th> <th>Model</th>
</tr>
<#list model["carList"] as car>
<tr>
<td>${car.make}</td> <td>${car.model}</td>
</tr>
</#list>
</table>
</div>
</body>
</html>

View File

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p: %c - %m%n" />
</layout>
</appender>
<!-- Application Loggers -->
<logger name="com.spring.freemarker">
<level value="info" />
</logger>
<!-- 3rdparty Loggers -->
<logger name="org.springframework.core">
<level value="info" />
</logger>
<logger name="org.springframework.beans">
<level value="info" />
</logger>
<logger name="org.springframework.context">
<level value="info" />
</logger>
<logger name="org.springframework.web">
<level value="info" />
</logger>
<!-- Root Logger -->
<root>
<priority value="info" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@ -4,7 +4,7 @@ import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public class FooDao extends AbstractHibernateDao<Foo>implements IFooDao { public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
public FooDao() { public FooDao() {
super(); super();

View File

@ -1,6 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>spring-hibernate4</artifactId> <artifactId>spring-hibernate4</artifactId>
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
@ -15,6 +15,16 @@
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version> <version>${org.springframework.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${org.springframework.security.version}</version>
</dependency>
<!-- persistence --> <!-- persistence -->
@ -23,21 +33,35 @@
<artifactId>spring-orm</artifactId> <artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version> <version>${org.springframework.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId> <artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version> <version>${hibernate.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.javassist</groupId> <groupId>org.hibernate</groupId>
<artifactId>javassist</artifactId> <artifactId>hibernate-envers</artifactId>
<version>${javassist.version}</version> <version>${hibernate-envers.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>${jta.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${el-api.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version> <version>${mysql-connector-java.version}</version>
<scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -82,7 +106,7 @@
<version>${org.springframework.version}</version> <version>${org.springframework.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
@ -90,12 +114,27 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${org.springframework.security.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId> <artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version> <version>${org.hamcrest.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId> <artifactId>hamcrest-library</artifactId>
@ -175,18 +214,22 @@
<properties> <properties>
<!-- Spring --> <!-- Spring -->
<org.springframework.version>4.2.4.RELEASE</org.springframework.version> <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
<org.springframework.security.version>4.0.3.RELEASE</org.springframework.security.version> <org.springframework.security.version>4.0.3.RELEASE</org.springframework.security.version>
<javassist.version>3.20.0-GA</javassist.version> <org.springframework.data.version>1.9.2.RELEASE</org.springframework.data.version>
<javassist.version>3.20.0-GA</javassist.version>
<!-- persistence --> <!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version> <hibernate.version>4.3.11.Final</hibernate.version>
<hibernate-envers.version>${hibernate.version}</hibernate-envers.version>
<mysql-connector-java.version>5.1.37</mysql-connector-java.version> <mysql-connector-java.version>5.1.37</mysql-connector-java.version>
<tomcat-dbcp.version>7.0.42</tomcat-dbcp.version> <tomcat-dbcp.version>8.0.30</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<el-api.version>2.2.4</el-api.version>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version> <org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version> <logback.version>1.1.3</logback.version>
<!-- various --> <!-- various -->
<hibernate-validator.version>5.2.2.Final</hibernate-validator.version> <hibernate-validator.version>5.2.2.Final</hibernate-validator.version>
@ -196,7 +239,7 @@
<!-- testing --> <!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version> <org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version> <junit.version>4.11</junit.version>
<mockito.version>1.10.19</mockito.version> <mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4.1</httpcore.version> <httpcore.version>4.4.1</httpcore.version>
@ -209,7 +252,8 @@
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version> <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.15</cargo-maven2-plugin.version> <cargo-maven2-plugin.version>1.4.15</cargo-maven2-plugin.version>
<!-- <hibernate4-maven-plugin.version>1.1.0</hibernate4-maven-plugin.version> -->
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.dao.common.IAuditOperations;
import com.baeldung.persistence.model.Bar;
public interface IBarAuditableDao extends IBarDao, IAuditOperations<Bar> {
//
}

View File

@ -0,0 +1,10 @@
package com.baeldung.persistence.dao;
import java.io.Serializable;
import com.baeldung.persistence.model.Bar;
import org.springframework.data.repository.CrudRepository;
public interface IBarCrudRepository extends CrudRepository<Bar, Serializable> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.dao.common.IOperations;
import com.baeldung.persistence.model.Bar;
public interface IBarDao extends IOperations<Bar> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.model.Child;
import com.baeldung.persistence.dao.common.IOperations;
public interface IChildDao extends IOperations<Child> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.dao.common.IAuditOperations;
import com.baeldung.persistence.model.Foo;
public interface IFooAuditableDao extends IFooDao, IAuditOperations<Foo> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.dao.common.IOperations;
public interface IFooDao extends IOperations<Foo> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.dao;
import com.baeldung.persistence.model.Parent;
import com.baeldung.persistence.dao.common.IOperations;
public interface IParentDao extends IOperations<Parent> {
//
}

View File

@ -0,0 +1,14 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import com.google.common.base.Preconditions;
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
protected Class<T> clazz;
protected final void setClazz(final Class<T> clazzToSet) {
clazz = Preconditions.checkNotNull(clazzToSet);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import java.util.List;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.envers.query.AuditQuery;
@SuppressWarnings("unchecked")
public class AbstractHibernateAuditableDao<T extends Serializable> extends AbstractHibernateDao<T> implements IAuditOperations<T> {
@Override
public List<T> getEntitiesAtRevision(final Number revision) {
final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession());
final AuditQuery query = auditReader.createQuery().forEntitiesAtRevision(clazz, revision);
final List<T> resultList = query.getResultList();
return resultList;
}
@Override
public List<T> getEntitiesModifiedAtRevision(final Number revision) {
final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession());
final AuditQuery query = auditReader.createQuery().forEntitiesModifiedAtRevision(clazz, revision);
final List<T> resultList = query.getResultList();
return resultList;
}
@Override
public List<T> getRevisions() {
final AuditReader auditReader = AuditReaderFactory.get(getCurrentSession());
final AuditQuery query = auditReader.createQuery().forRevisionsOfEntity(clazz, true, true);
final List<T> resultList = query.getResultList();
return resultList;
}
}

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.dao.common; package com.baeldung.persistence.dao.common;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
@ -10,55 +10,49 @@ import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public abstract class AbstractHibernateDao<T extends Serializable> implements IOperations<T> { public abstract class AbstractHibernateDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
private Class<T> clazz;
@Autowired @Autowired
private SessionFactory sessionFactory; protected SessionFactory sessionFactory;
// API // API
protected final void setClazz(final Class<T> clazzToSet) {
clazz = Preconditions.checkNotNull(clazzToSet);
}
@Override @Override
public final T findOne(final long id) { public T findOne(final long id) {
return (T) getCurrentSession().get(clazz, id); return (T) getCurrentSession().get(clazz, id);
} }
@Override @Override
public final List<T> findAll() { public List<T> findAll() {
return getCurrentSession().createQuery("from " + clazz.getName()).list(); return getCurrentSession().createQuery("from " + clazz.getName()).list();
} }
@Override @Override
public final void create(final T entity) { public void create(final T entity) {
Preconditions.checkNotNull(entity); Preconditions.checkNotNull(entity);
// getCurrentSession().persist(entity);
getCurrentSession().saveOrUpdate(entity); getCurrentSession().saveOrUpdate(entity);
} }
@Override @Override
public final T update(final T entity) { public T update(final T entity) {
Preconditions.checkNotNull(entity); Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity); return (T) getCurrentSession().merge(entity);
} }
@Override @Override
public final void delete(final T entity) { public void delete(final T entity) {
Preconditions.checkNotNull(entity); Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity); getCurrentSession().delete(entity);
} }
@Override @Override
public final void deleteById(final long entityId) { public void deleteById(final long entityId) {
final T entity = findOne(entityId); final T entity = findOne(entityId);
Preconditions.checkState(entity != null); Preconditions.checkState(entity != null);
delete(entity); delete(entity);
} }
protected final Session getCurrentSession() { protected Session getCurrentSession() {
return sessionFactory.getCurrentSession(); return sessionFactory.getCurrentSession();
} }

View File

@ -0,0 +1,56 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
public class AbstractJpaDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> {
@PersistenceContext
private EntityManager em;
// API
@Override
public T findOne(final long id) {
return em.find(clazz, Long.valueOf(id).intValue());
}
@Override
public List<T> findAll() {
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<T> cq = cb.createQuery(clazz);
final Root<T> rootEntry = cq.from(clazz);
final CriteriaQuery<T> all = cq.select(rootEntry);
final TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
@Override
public void create(final T entity) {
em.persist(entity);
}
@Override
public T update(final T entity) {
em.merge(entity);
return entity;
}
@Override
public void delete(final T entity) {
em.remove(entity);
}
@Override
public void deleteById(final long entityId) {
delete(findOne(entityId));
}
}

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.dao.common; package com.baeldung.persistence.dao.common;
import java.io.Serializable; import java.io.Serializable;
@ -8,6 +8,6 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T>implements IGenericDao<T> { public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> {
// //
} }

View File

@ -0,0 +1,14 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import java.util.List;
public interface IAuditOperations<T extends Serializable> {
List<T> getEntitiesAtRevision(Number revision);
List<T> getEntitiesModifiedAtRevision(Number revision);
List<T> getRevisions();
}

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.dao.common; package com.baeldung.persistence.dao.common;
import java.io.Serializable; import java.io.Serializable;

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.dao.common; package com.baeldung.persistence.dao.common;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;

View File

@ -0,0 +1,28 @@
package com.baeldung.persistence.dao.impl;
import java.util.List;
import com.baeldung.persistence.dao.IBarAuditableDao;
import com.baeldung.persistence.dao.common.AbstractHibernateAuditableDao;
import com.baeldung.persistence.model.Bar;
public class BarAuditableDao extends AbstractHibernateAuditableDao<Bar> implements IBarAuditableDao {
public BarAuditableDao() {
super();
setClazz(Bar.class);
}
// API
@Override
public List<Bar> getRevisions() {
final List<Bar> resultList = super.getRevisions();
for (final Bar bar : resultList) {
bar.getFooSet().size(); // force FooSet initialization
}
return resultList;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.dao.IBarDao;
import com.baeldung.persistence.model.Bar;
import org.springframework.stereotype.Repository;
@Repository
public class BarDao extends AbstractHibernateDao<Bar> implements IBarDao {
public BarDao() {
super();
setClazz(Bar.class);
}
// API
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.IBarDao;
import com.baeldung.persistence.dao.common.AbstractJpaDao;
import com.baeldung.persistence.model.Bar;
import org.springframework.stereotype.Repository;
@Repository
public class BarJpaDao extends AbstractJpaDao<Bar> implements IBarDao {
public BarJpaDao() {
super();
setClazz(Bar.class);
}
// API
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.model.Child;
import com.baeldung.persistence.dao.IChildDao;
import org.springframework.stereotype.Repository;
@Repository
public class ChildDao extends AbstractHibernateDao<Child> implements IChildDao {
public ChildDao() {
super();
setClazz(Child.class);
}
// API
}

View File

@ -0,0 +1,17 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.common.AbstractHibernateAuditableDao;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.dao.IFooAuditableDao;
public class FooAuditableDao extends AbstractHibernateAuditableDao<Foo> implements IFooAuditableDao {
public FooAuditableDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.dao.IFooDao;
import com.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
public FooDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@ -0,0 +1,19 @@
package com.baeldung.persistence.dao.impl;
import com.baeldung.persistence.dao.IParentDao;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.model.Parent;
import org.springframework.stereotype.Repository;
@Repository
public class ParentDao extends AbstractHibernateDao<Parent> implements IParentDao {
public ParentDao() {
super();
setClazz(Parent.class);
}
// API
}

View File

@ -0,0 +1,242 @@
package com.baeldung.persistence.model;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import org.hibernate.annotations.OrderBy;
import org.hibernate.envers.Audited;
import org.jboss.logging.Logger;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.google.common.collect.Sets;
@Entity
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
@Audited
@EntityListeners(AuditingEntityListener.class)
public class Bar implements Serializable {
private static Logger logger = Logger.getLogger(Bar.class);
public enum OPERATION {
INSERT, UPDATE, DELETE;
private String value;
OPERATION() {
value = toString();
}
public String getValue() {
return value;
}
public static OPERATION parse(final String value) {
OPERATION operation = null;
for (final OPERATION op : OPERATION.values()) {
if (op.getValue().equals(value)) {
operation = op;
break;
}
}
return operation;
}
};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OrderBy(clause = "NAME DESC")
// @NotAudited
private Set<Foo> fooSet = Sets.newHashSet();
@Column(name = "operation")
private String operation;
@Column(name = "timestamp")
private long timestamp;
@Column(name = "created_date")
@CreatedDate
private long createdDate;
@Column(name = "modified_date")
@LastModifiedDate
private long modifiedDate;
@Column(name = "created_by")
@CreatedBy
private String createdBy;
@Column(name = "modified_by")
@LastModifiedBy
private String modifiedBy;
public Bar() {
super();
}
public Bar(final String name) {
super();
this.name = name;
}
// API
public Set<Foo> getFooSet() {
return fooSet;
}
public void setFooSet(final Set<Foo> fooSet) {
this.fooSet = fooSet;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public OPERATION getOperation() {
return OPERATION.parse(operation);
}
public void setOperation(final OPERATION operation) {
this.operation = operation.getValue();
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(final long timestamp) {
this.timestamp = timestamp;
}
public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(final long createdDate) {
this.createdDate = createdDate;
}
public long getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(final long modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(final String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public void setOperation(final String operation) {
this.operation = operation;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
@PrePersist
public void onPrePersist() {
logger.info("@PrePersist");
audit(OPERATION.INSERT);
}
@PreUpdate
public void onPreUpdate() {
logger.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
logger.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
}

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.model; package com.baeldung.persistence.model;
import java.io.Serializable; import java.io.Serializable;

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.model; package com.baeldung.persistence.model;
import java.io.Serializable; import java.io.Serializable;
@ -12,7 +12,11 @@ import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import org.hibernate.envers.Audited;
@Entity @Entity
@Audited
// @Proxy(lazy = false)
public class Foo implements Serializable { public class Foo implements Serializable {
@Id @Id

View File

@ -1,4 +1,4 @@
package org.baeldung.persistence.model; package com.baeldung.persistence.model;
import java.io.Serializable; import java.io.Serializable;

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.service;
import com.baeldung.persistence.dao.common.IAuditOperations;
import com.baeldung.persistence.model.Bar;
public interface IBarAuditableService extends IBarService, IAuditOperations<Bar> {
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.service;
import com.baeldung.persistence.dao.common.IOperations;
import com.baeldung.persistence.model.Bar;
public interface IBarService extends IOperations<Bar> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.service;
import com.baeldung.persistence.model.Child;
import com.baeldung.persistence.dao.common.IOperations;
public interface IChildService extends IOperations<Child> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.service;
import com.baeldung.persistence.dao.common.IAuditOperations;
import com.baeldung.persistence.model.Foo;
public interface IFooAuditableService extends IFooService, IAuditOperations<Foo> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.service;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.dao.common.IOperations;
public interface IFooService extends IOperations<Foo> {
//
}

View File

@ -0,0 +1,8 @@
package com.baeldung.persistence.service;
import com.baeldung.persistence.model.Parent;
import com.baeldung.persistence.dao.common.IOperations;
public interface IParentService extends IOperations<Parent> {
//
}

View File

@ -0,0 +1,30 @@
package com.baeldung.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import com.baeldung.persistence.dao.common.IAuditOperations;
import com.baeldung.persistence.dao.common.IOperations;
import org.springframework.transaction.annotation.Transactional;
@Transactional(value = "hibernateTransactionManager")
public abstract class AbstractHibernateAuditableService<T extends Serializable> extends AbstractHibernateService<T> implements IOperations<T>, IAuditOperations<T> {
@Override
public List<T> getEntitiesAtRevision(final Number revision) {
return getAuditableDao().getEntitiesAtRevision(revision);
}
@Override
public List<T> getEntitiesModifiedAtRevision(final Number revision) {
return getAuditableDao().getEntitiesModifiedAtRevision(revision);
}
@Override
public List<T> getRevisions() {
return getAuditableDao().getRevisions();
}
abstract protected IAuditOperations<T> getAuditableDao();
}

View File

@ -0,0 +1,42 @@
package com.baeldung.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import com.baeldung.persistence.dao.common.IOperations;
import org.springframework.transaction.annotation.Transactional;
@Transactional(value = "hibernateTransactionManager")
public abstract class AbstractHibernateService<T extends Serializable> extends AbstractService<T> implements IOperations<T> {
@Override
public T findOne(final long id) {
return super.findOne(id);
}
@Override
public List<T> findAll() {
return super.findAll();
}
@Override
public void create(final T entity) {
super.create(entity);
}
@Override
public T update(final T entity) {
return super.update(entity);
}
@Override
public void delete(final T entity) {
super.delete(entity);
}
@Override
public void deleteById(final long entityId) {
super.deleteById(entityId);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import com.baeldung.persistence.dao.common.IOperations;
import org.springframework.transaction.annotation.Transactional;
@Transactional(value = "jpaTransactionManager")
public abstract class AbstractJpaService<T extends Serializable> extends AbstractService<T> implements IOperations<T> {
@Override
public T findOne(final long id) {
return super.findOne(id);
}
@Override
public List<T> findAll() {
return super.findAll();
}
@Override
public void create(final T entity) {
super.create(entity);
}
@Override
public T update(final T entity) {
return super.update(entity);
}
@Override
public void delete(final T entity) {
super.delete(entity);
}
@Override
public void deleteById(final long entityId) {
super.deleteById(entityId);
}
}

View File

@ -1,12 +1,10 @@
package org.baeldung.persistence.service.common; package com.baeldung.persistence.service.common;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import org.baeldung.persistence.dao.common.IOperations; import com.baeldung.persistence.dao.common.IOperations;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public abstract class AbstractService<T extends Serializable> implements IOperations<T> { public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
@Override @Override

View File

@ -0,0 +1,46 @@
package com.baeldung.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import com.baeldung.persistence.dao.common.IOperations;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
@Transactional(value = "jpaTransactionManager")
public abstract class AbstractSpringDataJpaService<T extends Serializable> implements IOperations<T> {
@Override
public T findOne(final long id) {
return getDao().findOne(Long.valueOf(id));
}
@Override
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public void create(final T entity) {
getDao().save(entity);
}
@Override
public T update(final T entity) {
return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().delete(Long.valueOf(entityId));
}
protected abstract CrudRepository<T, Serializable> getDao();
}

View File

@ -0,0 +1,41 @@
package com.baeldung.persistence.service.impl;
import com.baeldung.persistence.dao.common.IAuditOperations;
import com.baeldung.persistence.service.common.AbstractHibernateAuditableService;
import com.baeldung.persistence.dao.IBarAuditableDao;
import com.baeldung.persistence.dao.IBarDao;
import com.baeldung.persistence.dao.common.IOperations;
import com.baeldung.persistence.model.Bar;
import com.baeldung.persistence.service.IBarAuditableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class BarAuditableService extends AbstractHibernateAuditableService<Bar> implements IBarAuditableService {
@Autowired
@Qualifier("barHibernateDao")
private IBarDao dao;
@Autowired
@Qualifier("barHibernateAuditableDao")
private IBarAuditableDao auditDao;
public BarAuditableService() {
super();
}
// API
@Override
protected IOperations<Bar> getDao() {
return dao;
}
@Override
protected IAuditOperations<Bar> getAuditableDao() {
return auditDao;
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.persistence.service.impl;
import com.baeldung.persistence.dao.IBarDao;
import com.baeldung.persistence.dao.common.IOperations;
import com.baeldung.persistence.model.Bar;
import com.baeldung.persistence.service.IBarService;
import com.baeldung.persistence.service.common.AbstractJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class BarJpaService extends AbstractJpaService<Bar> implements IBarService {
@Autowired
@Qualifier("barJpaDao")
private IBarDao dao;
public BarJpaService() {
super();
}
// API
@Override
protected IOperations<Bar> getDao() {
return dao;
}
}

Some files were not shown because too many files have changed in this diff Show More