INTSAMPLES-62 - Create JPA Samples

* Sample supports Hibernate, EclipsLink and OpenJPA
* Sample uses Spring 3.1 (Profiles)
* Retrieves a list of records
* Creates a new DB record

INTSAMPLES-62 Code Review Fixes
* Use Log4j
* Fix dependencies

INTSAMPLES-62 - Make JPA Sample compliant with INT-2601

* Fix whitespace issues
* Make sure all schemas are version-less
This commit is contained in:
Gunnar Hillert
2012-04-17 17:24:57 -04:00
committed by Gary Russell
parent 504b281751
commit 7fda2f841b
18 changed files with 799 additions and 0 deletions

View File

@@ -0,0 +1,182 @@
/*
* Copyright 2002-2012 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 org.springframework.integration.samples.jpa;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Scanner;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.integration.samples.jpa.service.PersonService;
import org.springframework.util.StringUtils;
/**
* Starts the Spring Context and will initialize the Spring Integration routes.
*
* @author Gunnar Hillert
* @author Amol Nayak
* @version 1.0
*
*/
public final class Main {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
/**
* Prevent instantiation.
*/
private Main() {}
/**
* Load the Spring Integration Application Context
*
* @param args - command line arguments
*/
public static void main(final String... args) {
final Scanner scanner = new Scanner(System.in);
System.out.println("\n========================================================="
+ "\n "
+ "\n Welcome to the Spring Integration JPA Sample! "
+ "\n "
+ "\n For more information please visit: "
+ "\n http://www.springintegration.org/ "
+ "\n "
+ "\n=========================================================" );
System.out.println("Please enter a choice and press <enter>: ");
System.out.println("\t1. Use Hibernate");
System.out.println("\t2. Use OpenJPA");
System.out.println("\t3. Use EclipseLink");
System.out.println("\tq. Quit the application");
System.out.print("Enter you choice: ");
final GenericXmlApplicationContext context = new GenericXmlApplicationContext();
while (true) {
final String input = scanner.nextLine();
if("1".equals(input.trim())) {
context.getEnvironment().setActiveProfiles("hibernate");
break;
} else if("2".equals(input.trim())) {
context.getEnvironment().setActiveProfiles("openjpa");
break;
} else if("3".equals(input.trim())) {
context.getEnvironment().setActiveProfiles("eclipselink");
break;
} else if("q".equals(input.trim())) {
System.out.println("Exiting application...bye.");
System.exit(0);
} else {
System.out.println("Invalid choice\n\n");
System.out.print("Enter you choice: ");
}
}
context.load("classpath:META-INF/spring/integration/*-context.xml");
context.registerShutdownHook();
context.refresh();
final PersonService personService = context.getBean(PersonService.class);
System.out.println("Please enter a choice and press <enter>: ");
System.out.println("\t1. List all people");
System.out.println("\t2. Create a new person");
System.out.println("\tq. Quit the application");
System.out.print("Enter you choice: ");
while (true) {
final String input = scanner.nextLine();
if("1".equals(input.trim())) {
findPeople(personService);
} else if("2".equals(input.trim())) {
createPersonDetails(scanner,personService);
} else if("q".equals(input.trim())) {
break;
} else {
System.out.println("Invalid choice\n\n");
}
System.out.println("Please enter a choice and press <enter>: ");
System.out.println("\t1. List all people");
System.out.println("\t2. Create a new person");
System.out.println("\tq. Quit the application");
System.out.print("Enter you choice: ");
}
System.out.println("Exiting application...bye.");
System.exit(0);
}
private static void createPersonDetails(final Scanner scanner,PersonService service) {
while(true) {
System.out.print("\nEnter the Person's name:");
String name = null;
while(true) {
name = scanner.nextLine();
if (StringUtils.hasText(name)) {
break;
}
System.out.print("No text entered....Please enter a name:");
}
Person person = new Person();
person.setName(name);
person = service.createPerson(person);
System.out.println("Created person record with id: " + person.getId());
System.out.print("Do you want to create another person? (y/n)");
String choice = scanner.nextLine();
if(!"y".equalsIgnoreCase(choice)) {
break;
}
}
}
/**
* @param service
* @param input
*/
private static void findPeople(final PersonService service) {
System.out.println("ID NAME CREATED");
System.out.println("==================================");
final List<Person> people = service.findPeople();
if(people != null && !people.isEmpty()) {
for(Person person : people) {
System.out.print(String.format("%d, %s, ", person.getId(), person.getName()));
System.out.println(DATE_FORMAT.format(person.getCreatedDateTime()));
}
} else {
System.out.println(
String.format("No Person record found."));
}
System.out.println("==================================\n\n");
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright 2002-2012 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 org.springframework.integration.samples.jpa;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* A simple POJO representing a Person.
*
* @author Amol Nayak
* @author Gunnar Hillert
*
*/
@Entity
@Table(name="PEOPLE")
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="CREATED_DATE_TIME")
private Date createdDateTime;
public Person() {
super();
this.createdDateTime = new Date();
}
public Person(String name) {
super();
this.name = name;
this.createdDateTime = new Date();
}
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;
}
public Date getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Date createdDateTime) {
this.createdDateTime = createdDateTime;
}
@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(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Person other = (Person) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2002-2012 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 org.springframework.integration.samples.jpa.service;
import java.util.List;
import org.springframework.integration.annotation.Payload;
import org.springframework.integration.samples.jpa.Person;
/**
* The Service is used to create Person instance in database
*
* @author Amol Nayak
* @author Gunnar Hillert
*
*/
public interface PersonService {
/**
* Creates a {@link Person} instance from the {@link Person} instance passed
*
* @param the created person instance, it will contain the generated primary key and the formated name
* @return The persisted Entity
*/
Person createPerson(Person person);
/**
*
* @return the matching {@link Person} record(S)
*/
@Payload("new java.util.Date()")
List<Person> findPeople();
}

View File

@@ -0,0 +1,6 @@
drop table PEOPLE;
DROP TABLE OPENJPA_SEQUENCE_TABLE;
CREATE TABLE OPENJPA_SEQUENCE_TABLE (ID TINYINT NOT NULL, SEQUENCE_VALUE BIGINT, PRIMARY KEY (ID));
CREATE TABLE PEOPLE (id BIGINT generated by default as identity, name VARCHAR(255), CREATED_DATE_TIME TIMESTAMP, PRIMARY KEY (id));

View File

@@ -0,0 +1,2 @@
drop table OPENJPA_SEQUENCE_TABLE;
drop table PEOPLE;

View File

@@ -0,0 +1,2 @@
insert into PEOPLE(id, name, CREATED_DATE_TIME)
values ('1001', 'Cartman', NOW());

View File

@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jpa="http://www.springframework.org/schema/integration/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/integration/jpa http://www.springframework.org/schema/integration/jpa/spring-integration-jpa.xsd">
<!-- Setting Up the Database -->
<jdbc:embedded-database id="dataSource" type="H2"/>
<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS" >
<jdbc:script location="classpath:H2-DropTables.sql" />
<jdbc:script location="classpath:H2-CreateTables.sql" />
<jdbc:script location="classpath:H2-PopulateData.sql" />
</jdbc:initialize-database>
<!-- Define the JPA transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="vendorAdaptor" />
<property name="packagesToScan" value="org.springframework.integration.samples.jpa"/>
</bean>
<bean id="abstractVendorAdaptor" abstract="true">
<property name="generateDdl" value="true" />
<property name="database" value="H2" />
<property name="showSql" value="false"/>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
</beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jpa="http://www.springframework.org/schema/integration/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/integration/jpa http://www.springframework.org/schema/integration/jpa/spring-integration-jpa.xsd">
<import resource="classpath:/META-INF/spring/integration/commonJpa-context.xml" />
<bean id="vendorAdaptor" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"
parent="abstractVendorAdaptor">
</bean>
</beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jpa="http://www.springframework.org/schema/integration/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/integration/jpa http://www.springframework.org/schema/integration/jpa/spring-integration-jpa.xsd">
<import resource="classpath:/META-INF/spring/integration/commonJpa-context.xml" />
<bean id="vendorAdaptor" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
parent="abstractVendorAdaptor">
</bean>
</beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jpa="http://www.springframework.org/schema/integration/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/integration/jpa http://www.springframework.org/schema/integration/jpa/spring-integration-jpa.xsd">
<import resource="classpath:/META-INF/spring/integration/commonJpa-context.xml" />
<bean id="vendorAdaptor" class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"
parent="abstractVendorAdaptor">
</bean>
</beans>

View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-jpa="http://www.springframework.org/schema/integration/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/integration/jpa http://www.springframework.org/schema/integration/jpa/spring-integration-jpa.xsd">
<int:channel id="createPersonRequestChannel"/>
<int:channel id="createPersonReplyChannel"/>
<int:channel id="listPeopleRequestChannel"/>
<int:channel id="listPeopleReplyChannel"/>
<int:gateway id="personService"
service-interface="org.springframework.integration.samples.jpa.service.PersonService"
default-request-timeout="5000" default-reply-timeout="5000">
<int:method name="createPerson" request-channel="createPersonRequestChannel"/>
<int:method name="findPeople" request-channel="listPeopleRequestChannel"/>
</int:gateway>
<int-jpa:retrieving-outbound-gateway entity-manager-factory="entityManagerFactory"
request-channel="listPeopleRequestChannel"
jpa-query="select p from Person p order by p.name asc">
</int-jpa:retrieving-outbound-gateway>
<int-jpa:updating-outbound-gateway entity-manager-factory="entityManagerFactory"
request-channel="createPersonRequestChannel">
<int-jpa:transactional transaction-manager="transactionManager"/>
</int-jpa:updating-outbound-gateway>
<!-- Depending on the selected profile, user can use different JPA Providers -->
<beans profile="default, hibernate">
<import resource="classpath:/META-INF/spring/integration/hibernate-context.xml"/>
</beans>
<beans profile="openjpa">
<import resource="classpath:/META-INF/spring/integration/openjpa-context.xml"/>
</beans>
<beans profile="eclipselink">
<import resource="classpath:/META-INF/spring/integration/eclipselink-context.xml"/>
</beans>
</beans>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "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="%d{HH:mm:ss.SSS} %-5p [%t][%c] %m%n" />
</layout>
</appender>
<!-- Loggers -->
<logger name="org.springframework.integration">
<level value="warn" />
</logger>
<logger name="org.springframework.integration.samples">
<level value="info" />
</logger>
<!-- Root Logger -->
<root>
<priority value="warn" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@@ -0,0 +1,6 @@
create table IF NOT EXISTS USERS(USERNAME varchar(100),PASSWORD varchar(100), EMAIL varchar(100));
create table IF NOT EXISTS DUMMY(DUMMY_VALUE varchar(10));
create table IF NOT EXISTS Person(id integer identity primary key , name varchar(100), gender varchar(1), dateOfBirth date);
INSERT INTO USERS(USERNAME, PASSWORD, EMAIL) VALUES ('a', 'secret', 'spring-integration@awesome.com');
INSERT INTO USERS(USERNAME, PASSWORD, EMAIL) VALUES ('b', 's3cr3t', 'spring@rocks.com');
INSERT INTO USERS(USERNAME, PASSWORD, EMAIL) VALUES ('foo', 'bar', 'foo@bar.de');

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2012 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 org.springframework.integration.samples.jpa;
import java.util.Calendar;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.samples.jpa.service.PersonService;
/**
*
* @author Amol Nayak
*
*/
public class OutboundGatewayTest {
private static final Logger LOGGER = Logger.getLogger(OutboundGatewayTest.class);
@Test
public void insertPersonRecord() {
final ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:/META-INF/spring/integration/spring-integration-context.xml");
final PersonService service = context.getBean(PersonService.class);
LOGGER.info("Creating person Instance");
final Person person = new Person();
Calendar createdDateTime = Calendar.getInstance();
createdDateTime.set(1980, 0, 1);
person.setCreatedDateTime(createdDateTime.getTime());
person.setName("Name Of The Person");
final Person persistedPerson = service.createPerson(person);
Assert.assertNotNull("Expected a non null instance of Person, got null", persistedPerson);
LOGGER.info("\n\tGenerated person with id: " + persistedPerson.getId() + ", with name: " + persistedPerson.getName());
}
}