Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2016-03-13 23:24:02 -05:00
commit 6b5645c19e
29 changed files with 474 additions and 275 deletions

View File

@ -9,8 +9,8 @@
<properties>
<jee.version>7.0</jee.version>
<oracle.version>11.2.0.4</oracle.version>
<hibernate.version>5.1.0.Final</hibernate.version>
<mysql.version>5.1.38</mysql.version>
</properties>
<build>
@ -33,29 +33,6 @@
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>install-oracle-jdbc</id>
<goals>
<goal>install-file</goal>
</goals>
<phase>clean</phase>
<configuration>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${oracle.version}</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
<createChecksum>true</createChecksum>
<file>${project.basedir}/src/lib/ojdbc6.jar</file>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ -76,20 +53,6 @@
<version>${hibernate.version}</version>
</dependency>
<!-- Oracle JDBC -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${oracle.version}</version>
</dependency>
<!-- Postgres JDBC -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1208</version>
</dependency>
<!-- MySql JDBC -->
<dependency>

View File

@ -1,25 +1,27 @@
package com.baeldung.jpa.model;
import javax.persistence.*;
/**
* Created by Giuseppe Bueti on 22/02/2016.
*/
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.Table;
@Entity
@Table(name = "CAR")
@NamedStoredProcedureQueries({
@NamedStoredProcedureQuery(name = "findByModelProcedure", procedureName = "FIND_CAR_BY_MODEL", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "data", type = Car.class, mode = ParameterMode.REF_CURSOR),
@StoredProcedureParameter(name = "p_model", type = String.class, mode = ParameterMode.IN) }),
@NamedStoredProcedureQuery(name = "findByYearProcedure", procedureName = "FIND_CAR_BY_YEAR", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "data", type = Car.class, mode = ParameterMode.REF_CURSOR),
@StoredProcedureParameter(name = "p_year", type = Integer.class, mode = ParameterMode.IN) }) })
@NamedStoredProcedureQuery(name = "findByYearProcedure", procedureName = "FIND_CAR_BY_YEAR", resultClasses = { Car.class }, parameters = { @StoredProcedureParameter(name = "p_year", type = Integer.class, mode = ParameterMode.IN) }) })
public class Car {
private long id;
private String model;
private Integer year;
public Car(String model, Integer year) {
public Car(final String model, final Integer year) {
this.model = model;
this.year = year;
}
@ -28,15 +30,13 @@ public class Car {
}
@Id
@SequenceGenerator(name = "CarIdSequence", sequenceName = "SEQ_CAR_ID", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CarIdSequence")
// @GeneratedValue(strategy = GenerationType.IDENTITY) -- for MySQL
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false, scale = 0)
public long getId() {
return id;
}
public void setId(long id) {
public void setId(final long id) {
this.id = id;
}
@ -45,7 +45,7 @@ public class Car {
return model;
}
public void setModel(String model) {
public void setModel(final String model) {
this.model = model;
}
@ -54,7 +54,7 @@ public class Car {
return year;
}
public void setYear(Integer year) {
public void setYear(final Integer year) {
this.year = year;
}
}

View File

@ -7,16 +7,16 @@ public class QueryParameter {
private Map<String, Object> parameters = null;
private QueryParameter(String name, Object value) {
private QueryParameter(final String name, final Object value) {
this.parameters = new HashMap<>();
this.parameters.put(name, value);
}
public static QueryParameter with(String name, Object value) {
public static QueryParameter with(final String name, final Object value) {
return new QueryParameter(name, value);
}
public QueryParameter and(String name, Object value) {
public QueryParameter and(final String name, final Object value) {
this.parameters.put(name, value);
return this;
}
@ -24,4 +24,5 @@ public class QueryParameter {
public Map<String, Object> parameters() {
return this.parameters;
}
}

View File

@ -9,22 +9,12 @@
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.url" value="jdbc:oracle:thin:@//127.0.0.1:1521/xe" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" />
<property name="hibernate.connection.username" value="JPA" />
<property name="hibernate.connection.password" value="JPA" />
<property name="hibernate.show_sql" value="true" />
</properties>
<!-- MySQL properties configuration -->
<!--properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/jpa" />
<property name="javax.persistence.jdbc.user" value="jpa" />
<property name="javax.persistence.jdbc.password" value="bagnara.82" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
<property name="javax.persistence.jdbc.user" value="baeldung" />
<property name="javax.persistence.jdbc.password" value="YourPassword" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties-->
</properties>
</persistence-unit>
</persistence>

View File

@ -1,7 +0,0 @@
create or replace PROCEDURE FIND_CAR_BY_YEAR ( p_year IN NUMBER, data OUT SYS_REFCURSOR ) AS
BEGIN
OPEN data FOR
SELECT ID, MODEL, YEAR
FROM CAR
WHERE YEAR = p_year;
END FIND_CAR_BY_YEAR;

View File

@ -1,34 +0,0 @@
CREATE TABLESPACE JPA DATAFILE 'C:\oraclexe\app\oracle\oradata\XE\JPA.DBF' SIZE 100M AUTOEXTEND ON MAXSIZE 2048M;
--DROP USER JPA CASCADE;
CREATE USER JPA IDENTIFIED BY JPA DEFAULT TABLESPACE JPA;
ALTER USER JPA QUOTA UNLIMITED ON "JPA" ACCOUNT UNLOCK;
GRANT CREATE SESSION TO "JPA";
GRANT ALTER SESSION TO "JPA";
GRANT CREATE TABLE TO "JPA";
GRANT CREATE TRIGGER TO "JPA";
GRANT CREATE VIEW TO "JPA";
GRANT CREATE DIMENSION TO "JPA";
GRANT CREATE CLUSTER TO "JPA";
GRANT CREATE INDEXTYPE TO "JPA";
GRANT CREATE ROLE TO "JPA";
GRANT CREATE SEQUENCE TO "JPA";
GRANT CREATE TYPE TO "JPA";
GRANT CREATE MATERIALIZED VIEW TO "JPA";
GRANT CREATE PROCEDURE TO "JPA";
GRANT CREATE SYNONYM TO "JPA";
CREATE SEQUENCE SEQ_CAR_ID INCREMENT BY 1 START WITH 1 MAXVALUE 999999999999999 MINVALUE 1;
CREATE TABLE CAR
(
ID NUMBER NOT NULL,
MODEL VARCHAR2(50) NOT NULL,
YEAR NUMBER(4) NOT NULL
);
ALTER TABLE CAR ADD CONSTRAINT CAR_PK PRIMARY KEY ( ID );
commit;

View File

@ -1,5 +1,5 @@
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('123456', 'Camaro', '2012');
INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('12112', 'Fiat Panda', '2000');
INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('111000', 'Fiat Punto', '2007');
INSERT INTO "JPA"."CAR" (ID, MODEL, YEAR) VALUES ('3382', 'Citroen C3', '2009');
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('12112', 'Fiat Panda', '2000');
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('111000', 'Fiat Punto', '2007');
INSERT INTO CAR (ID, MODEL, YEAR) VALUES ('3382', 'Citroen C3', '2009');
commit;

View File

@ -1,13 +1,20 @@
package com.baeldung.jpa.storedprocedure;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.ParameterMode;
import javax.persistence.Persistence;
import javax.persistence.StoredProcedureQuery;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.jpa.model.Car;
import org.junit.*;
import javax.persistence.*;
/**
* Created by Giuseppe Bueti on 23/02/2016.
*/
public class StoredProcedureTest {
private static EntityManagerFactory factory = null;
@ -25,13 +32,13 @@ public class StoredProcedureTest {
@Test
public void createCarTest() {
EntityTransaction transaction = entityManager.getTransaction();
final EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
Car car = new Car("Fiat Punto", 2015);
final Car car = new Car("Fiat Marea", 2015);
entityManager.persist(car);
transaction.commit();
} catch (Exception e) {
} catch (final Exception e) {
System.out.println(e.getCause());
if (transaction.isActive()) {
transaction.rollback();
@ -40,31 +47,15 @@ public class StoredProcedureTest {
}
@Test
public void findCarsByYear() {
public void findCarsByYearNamedProcedure() {
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015);
final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015);
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
@Test
public void findCarsByModel() {
final StoredProcedureQuery findByModelProcedure = entityManager.createNamedStoredProcedureQuery("findByModelProcedure");
StoredProcedureQuery storedProcedure = findByModelProcedure.setParameter("p_model", "Camaro");
storedProcedure.getResultList().forEach(c -> Assert.assertEquals("Camaro", ((Car) c).getModel()));
}
@Test
public void findCarsByYearNoNamedStored() {
StoredProcedureQuery findByYearProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter("data", Void.class, ParameterMode.REF_CURSOR)
.registerStoredProcedureParameter("p_year", Integer.class, ParameterMode.IN).setParameter("p_year", 2015);
findByYearProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}
@Test
@Ignore
public void findCarsByYearMySql() {
StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015);
public void findCarsByYearNoNamed() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015);
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
}

View File

@ -9,23 +9,13 @@
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.model.Car</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.url" value="jdbc:oracle:thin:@//127.0.0.1:1521/xe" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" />
<property name="hibernate.connection.username" value="JPA" />
<property name="hibernate.connection.password" value="JPA" />
<property name="hibernate.show_sql" value="true" />
</properties>
<!-- MySQL properties configuration -->
<!--properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/jpa" />
<property name="javax.persistence.jdbc.user" value="jpa" />
<property name="javax.persistence.jdbc.password" value="bagnara.82" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
<property name="javax.persistence.jdbc.user" value="baeldung" />
<property name="javax.persistence.jdbc.password" value="YourPassword" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties-->
</properties>
</persistence-unit>
</persistence>

View File

@ -6,6 +6,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="target/metamodel"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>

View File

@ -1,11 +1,10 @@
package org.baeldung.dao;
import org.baeldung.entity.Person;
import javax.persistence.Tuple;
import java.util.List;
import java.util.Map;
import org.baeldung.entity.Person;
public interface PersonDao {
public Person save(Person person);

View File

@ -1,18 +1,17 @@
package org.baeldung.dao;
import com.mysema.query.group.GroupBy;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.jpa.impl.JPAQueryFactory;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.baeldung.entity.Person;
import org.baeldung.entity.QPerson;
import org.springframework.stereotype.Repository;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import java.util.List;
import java.util.Map;
import com.mysema.query.group.GroupBy;
import com.mysema.query.jpa.impl.JPAQuery;
@Repository
public class PersonDaoImpl implements PersonDao {
@ -20,49 +19,48 @@ public class PersonDaoImpl implements PersonDao {
@PersistenceContext
private EntityManager em;
public Person save(Person person) {
@Override
public Person save(final Person person) {
em.persist(person);
return person;
}
@Override
public List<Person> findPersonsByFirstnameQueryDSL(String firstname) {
JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person;
public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) {
final JPAQuery query = new JPAQuery(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).list(person);
}
@Override
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(String firstname, String surname) {
JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person;
public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) {
final JPAQuery query = new JPAQuery(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname).and(
person.surname.eq(surname))).list(person);
return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).list(person);
}
@Override
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(String firstname) {
JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person;
public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) {
final JPAQuery query = new JPAQuery(em);
final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).orderBy(
person.surname.desc()).list(person);
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).list(person);
}
@Override
public int findMaxAge() {
JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person;
final JPAQuery query = new JPAQuery(em);
final QPerson person = QPerson.person;
return query.from(person).list(person.age.max()).get(0);
}
@Override
public Map<String, Integer> findMaxAgeByName() {
JPAQuery query = new JPAQuery(em);
QPerson person = QPerson.person;
final JPAQuery query = new JPAQuery(em);
final QPerson person = QPerson.person;
return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age)));
}

View File

@ -1,6 +1,10 @@
package org.baeldung.entity;
import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@ -21,12 +25,12 @@ public class Person {
Person() {
}
public Person(String firstname, String surname) {
public Person(final String firstname, final String surname) {
this.firstname = firstname;
this.surname = surname;
}
public Person(String firstname, String surname, int age) {
public Person(final String firstname, final String surname, final int age) {
this(firstname, surname);
this.age = age;
}
@ -35,7 +39,7 @@ public class Person {
return id;
}
public void setId(Long id) {
public void setId(final Long id) {
this.id = id;
}
@ -43,7 +47,7 @@ public class Person {
return firstname;
}
public void setFirstname(String firstname) {
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
@ -51,7 +55,7 @@ public class Person {
return surname;
}
public void setSurname(String surname) {
public void setSurname(final String surname) {
this.surname = surname;
}
@ -59,7 +63,7 @@ public class Person {
return age;
}
public void setAge(int age) {
public void setAge(final int age) {
this.age = age;
}
}

View File

@ -1,6 +1,7 @@
package org.baeldung.dao;
import junit.framework.Assert;
import java.util.Map;
import org.baeldung.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -10,47 +11,48 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import java.util.Map;
import junit.framework.Assert;
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(defaultRollback=true)
@TransactionConfiguration(defaultRollback = true)
public class PersonDaoTest {
@Autowired
private PersonDao personDao;
//
@Test
public void testCreation() {
personDao.save(new Person("Erich", "Gamma"));
Person person = new Person("Kent", "Beck");
final Person person = new Person("Kent", "Beck");
personDao.save(person);
personDao.save(new Person("Ralph", "Johnson"));
Person personFromDb = personDao.findPersonsByFirstnameQueryDSL("Kent").get(0);
final Person personFromDb = personDao.findPersonsByFirstnameQueryDSL("Kent").get(0);
Assert.assertEquals(person.getId(), personFromDb.getId());
}
@Test
public void testMultipleFilter() {
personDao.save(new Person("Erich", "Gamma"));
Person person = personDao.save(new Person("Ralph", "Beck"));
Person person2 = personDao.save(new Person("Ralph", "Johnson"));
final Person person = personDao.save(new Person("Ralph", "Beck"));
final Person person2 = personDao.save(new Person("Ralph", "Johnson"));
Person personFromDb = personDao.findPersonsByFirstnameAndSurnameQueryDSL("Ralph", "Johnson").get(0);
final Person personFromDb = personDao.findPersonsByFirstnameAndSurnameQueryDSL("Ralph", "Johnson").get(0);
Assert.assertNotSame(person.getId(), personFromDb.getId());
Assert.assertEquals(person2.getId(), personFromDb.getId());
}
@Test
public void testOrdering() {
Person person = personDao.save(new Person("Kent", "Gamma"));
final Person person = personDao.save(new Person("Kent", "Gamma"));
personDao.save(new Person("Ralph", "Johnson"));
Person person2 = personDao.save(new Person("Kent", "Zivago"));
final Person person2 = personDao.save(new Person("Kent", "Zivago"));
Person personFromDb = personDao.findPersonsByFirstnameInDescendingOrderQueryDSL("Kent").get(0);
final Person personFromDb = personDao.findPersonsByFirstnameInDescendingOrderQueryDSL("Kent").get(0);
Assert.assertNotSame(person.getId(), personFromDb.getId());
Assert.assertEquals(person2.getId(), personFromDb.getId());
}
@ -61,7 +63,7 @@ public class PersonDaoTest {
personDao.save(new Person("Ralph", "Johnson", 35));
personDao.save(new Person("Kent", "Zivago", 30));
int maxAge = personDao.findMaxAge();
final int maxAge = personDao.findMaxAge();
Assert.assertTrue(maxAge == 35);
}
@ -71,7 +73,7 @@ public class PersonDaoTest {
personDao.save(new Person("Ralph", "Johnson", 35));
personDao.save(new Person("Kent", "Zivago", 30));
Map<String, Integer> maxAge = personDao.findMaxAgeByName();
final Map<String, Integer> maxAge = personDao.findMaxAgeByName();
Assert.assertTrue(maxAge.size() == 2);
Assert.assertSame(35, maxAge.get("Ralph"));
Assert.assertSame(30, maxAge.get("Kent"));

View File

@ -99,6 +99,19 @@
<artifactId>thymeleaf</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<!-- Json conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,51 @@
package org.baeldung.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private long id;
private String name;
private String contactNumber;
public Employee() {
super();
}
public Employee(final long id, final String name, final String contactNumber) {
this.id = id;
this.name = name;
this.contactNumber = contactNumber;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(final String contactNumber) {
this.contactNumber = contactNumber;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + "]";
}
}

View File

@ -0,0 +1,53 @@
package org.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
public class ContentManagementWebConfig extends WebMvcConfigurerAdapter {
public ContentManagementWebConfig() {
super();
}
// API
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true).
favorParameter(false).
parameterName("mediaType").
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.TEXT_HTML).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("html", MediaType.TEXT_HTML).
mediaType("json", MediaType.APPLICATION_JSON);
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
}

View File

@ -0,0 +1,55 @@
package org.baeldung.web.controller;
import java.util.HashMap;
import java.util.Map;
import org.baeldung.model.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class EmployeeController {
Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET)
public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) {
model.addAttribute("name", employeeMap.get(Id).getName());
model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber());
model.addAttribute("id", employeeMap.get(Id).getId());
return "employeeView";
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}

View File

@ -0,0 +1,33 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Example - Register an Employee</title>
</head>
<body>
<h3>Welcome, Enter The Employee Details</h3>
<form:form method="POST" action="/spring-mvc-java/addEmployee" modelAttribute="employee">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="contactNumber">Contact Number</form:label></td>
<td><form:input path="contactNumber" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>

View File

@ -0,0 +1,24 @@
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Employee Information</h2>
<table>
<tr>
<td>Name :</td>
<td>${name}</td>
</tr>
<tr>
<td>ID :</td>
<td>${id}</td>
</tr>
<tr>
<td>Contact Number :</td>
<td>${contactNumber}</td>
</tr>
</table>
</body>
</html>

View File

@ -98,6 +98,18 @@
<scope>test</scope>
</dependency>
<!-- Json conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
</dependencies>
<build>

View File

@ -1,34 +1,56 @@
package com.baeldung.spring.controller;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import com.baeldung.spring.form.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.baeldung.spring.form.Employee;
@Controller
public class EmployeeController {
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
return "employeeView";
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/employee/{Id}", method = RequestMethod.GET)
public String getEmployeeByIdHtmlView(@PathVariable final long Id, final ModelMap model) {
model.addAttribute("name", employeeMap.get(Id).getName());
model.addAttribute("contactNumber", employeeMap.get(Id).getContactNumber());
model.addAttribute("id", employeeMap.get(Id).getId());
return "employeeView";
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}

View File

@ -2,7 +2,9 @@ package com.baeldung.spring.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private long id;

View File

@ -0,0 +1,43 @@
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<context:component-scan base-package="org.baeldung.spring.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:view-controller path="/sample.html" view-name="sample" />
<!-- Content strategy using path extension -->
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true" />
<property name="favorParameter" value="false"/>
<property name="parameterName" value="mediaType"/>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="text/html" />
<property name="useJaf" value="false" />
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
</beans>

View File

@ -25,7 +25,7 @@ public class MyUserDetailsService implements UserDetailsService {
private final Log logger = LogFactory.getLog(this.getClass());
private Map<String, User> availableUsers = new HashMap<String, User>();
private final Map<String, User> availableUsers = new HashMap<String, User>();
public MyUserDetailsService() {
@ -33,12 +33,13 @@ public class MyUserDetailsService implements UserDetailsService {
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
logger.info("Load user by username " + username);
UserDetails user = availableUsers.get(username);
final UserDetails user = availableUsers.get(username);
if (user == null) {
throw new UsernameNotFoundException("Username not found");
} else {
@ -52,7 +53,6 @@ public class MyUserDetailsService implements UserDetailsService {
* in database or retrieved from another system).
*/
private void populateDemoUsers() {
logger.info("Populate demo users");
availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER)));
@ -70,12 +70,11 @@ public class MyUserDetailsService implements UserDetailsService {
* Role names user is assigned to
* @return User
*/
private User createUser(String username, String password, List<SecurityRole> roles) {
private User createUser(final String username, final String password, final List<SecurityRole> roles) {
logger.info("Create user " + username);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (SecurityRole role : roles) {
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (final SecurityRole role : roles) {
authorities.add(new SimpleGrantedAuthority(role.toString()));
}
return new User(username, password, true, true, true, true, authorities);

View File

@ -18,11 +18,13 @@ import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
public class DatabaseConfig {
public class PersistenceConfig {
@Autowired
private Environment env;
//
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
@ -32,4 +34,5 @@ public class DatabaseConfig {
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
}

View File

@ -1,11 +1,9 @@
package org.baeldung.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
* Spring Security Configuration.
@ -15,9 +13,6 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand
@ImportResource({ "classpath:webSecurityConfig.xml" })
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationSuccessHandler mySimpleUrlAuthenticationSuccessHandler;
public SecurityConfig() {
super();
}

View File

@ -1,55 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd">
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd"
>
<http use-expressions="true">
<intercept-url pattern="/anonymous*" access="isAnonymous()" />
<intercept-url pattern="/login*" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
<intercept-url pattern="/anonymous*" access="isAnonymous()"/>
<intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page='/login.html' authentication-success-handler-ref="mySimpleUrlAuthenticationSuccessHandler" authentication-failure-url="/login.html?error=true" />
<form-login login-page='/login.html' authentication-success-handler-ref="mySimpleUrlAuthenticationSuccessHandler" authentication-failure-url="/login.html?error=true"/>
<logout delete-cookies="JSESSIONID" />
<logout delete-cookies="JSESSIONID"/>
<remember-me data-source-ref="dataSource" token-validity-seconds="86400"/>
<remember-me data-source-ref="dataSource" token-validity-seconds="86400"/>
</http>
<!-- create H2 embedded database table on startup -->
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:/persisted_logins_create_table.sql"/>
</jdbc:embedded-database>
<jdbc:script location="classpath:/persisted_logins_create_table.sql"/>
</jdbc:embedded-database>
<!-- Persistent Remember Me Service -->
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<beans:constructor-arg value="myAppKey" />
<beans:constructor-arg ref="jdbcTokenRepository" />
<beans:constructor-arg ref="myUserDetailsService" />
</beans:bean>
<!-- Uses a database table to maintain a set of persistent login data -->
<beans:bean id="jdbcTokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<beans:property name="createTableOnStartup" value="false" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<!-- Authentication Manager (uses same UserDetailsService as RememberMeService)-->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailsService">
</authentication-provider>
</authentication-manager>
<!-- Persistent Remember Me Service -->
<beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<beans:constructor-arg value="myAppKey"/>
<beans:constructor-arg ref="jdbcTokenRepository"/>
<beans:constructor-arg ref="myUserDetailsService"/>
</beans:bean>
<!-- Uses a database table to maintain a set of persistent login data -->
<beans:bean id="jdbcTokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<beans:property name="createTableOnStartup" value="false"/>
<beans:property name="dataSource" ref="dataSource"/>
</beans:bean>
<!-- Authentication Manager (uses same UserDetailsService as RememberMeService) -->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="myUserDetailsService">
</authentication-provider>
</authentication-manager>
</beans:beans>