Skip to content
Open

03 #1

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
========================================================================================================================
README - Spring in Practice Recipe 2.1
README - Spring in Practice Recipe 2.3

Copyright (c) 2013 Manning Publications Co.

Expand All @@ -10,4 +10,4 @@ Blog: http://springinpractice.com/
Code: https://github.com/springinpractice
========================================================================================================================

Shows how to use Spring's JdbcTemplate for data access.
Shows how to use object/relational mapping for database access.
20 changes: 13 additions & 7 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ Code: https://github.com/springinpractice
<version>1.0-RELEASE</version>
</parent>

<artifactId>com.springinpractice.02_01</artifactId>
<artifactId>com.springinpractice.02_03</artifactId>
<packaging>war</packaging>

<name>Spring in Practice Section 2.1</name>
<description>Shows how to use Spring's JdbcTemplate for data access.</description>
<name>Spring in Practice Section 2.3</name>
<description>Shows how to use object/relational mapping for database access.</description>
<url>http://springinpractice.com/</url>

<properties>
Expand All @@ -43,6 +43,13 @@ Code: https://github.com/springinpractice
<artifactId>com.springinpractice.api</artifactId>
<version>1.0-RELEASE</version>
</dependency>
<dependency>
<groupId>com.springinpractice</groupId>
<artifactId>com.springinpractice.deps-hibernate</artifactId>
<version>1.0-RELEASE</version>
<type>pom</type>
<optional>true</optional>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>com.springinpractice.deps-web</artifactId>
Expand All @@ -57,10 +64,6 @@ Code: https://github.com/springinpractice
</dependency>

<!-- For JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.mysql.jdbc</groupId>
<artifactId>com.springsource.com.mysql.jdbc</artifactId>
Expand All @@ -76,6 +79,9 @@ Code: https://github.com/springinpractice
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
<jettyEnvXml>${chapter.conf.dir}/jetty-env.xml</jettyEnvXml>
</configuration>
</plugin>
</plugins>
</build>
Expand Down
4 changes: 0 additions & 4 deletions sample_conf/classes/spring/environment.properties

This file was deleted.

16 changes: 16 additions & 0 deletions sample_conf/jetty-env.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd">
<Configure class="org.mortbay.jetty.webapp.WebAppContext">
<New id="Sip02DS" class="org.mortbay.jetty.plus.naming.Resource">
<Arg></Arg>
<Arg>jdbc/Sip02DS</Arg>
<Arg>
<New class="org.apache.commons.dbcp.BasicDataSource">
<Set name="driverClassName">com.mysql.jdbc.Driver</Set>
<Set name="url">jdbc:mysql://localhost:3306/sip02?autoReconnect=true</Set>
<Set name="username">sip</Set>
<Set name="password">sip</Set>
</New>
</Arg>
</New>
</Configure>
21 changes: 21 additions & 0 deletions src/main/java/com/springinpractice/ch02/model/Contact.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@
*/
package com.springinpractice.ch02.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
Expand All @@ -17,19 +25,28 @@
/**
* @author Willie Wheeler (willie.wheeler@gmail.com)
*/
@Entity
@Table(name = "contact")
@NamedQuery(
name = "findContactsByEmail",
query = "from Contact where email like :email")
public class Contact {
private Long id;
private String lastName;
private String firstName;
private String middleInitial;
private String email;

@Id
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() { return id; }

public void setId(Long id) { this.id = id; }

@NotNull
@Length(min = 1, max = 40)
@Column(name = "last_name")
public String getLastName() { return lastName; }

public void setLastName(String lastName) {
Expand All @@ -38,26 +55,30 @@ public void setLastName(String lastName) {

@NotNull
@Length(min = 1, max = 40)
@Column(name = "first_name")
public String getFirstName() { return firstName; }

public void setFirstName(String firstName) {
this.firstName = StringUtils.cleanup(firstName);
}

@Length(max = 1)
@Column(name = "mi")
public String getMiddleInitial() { return middleInitial; }

public void setMiddleInitial(String mi) {
this.middleInitial = StringUtils.cleanup(mi);
}

@Email
@Column
public String getEmail() { return email; }

public void setEmail(String email) {
this.email = StringUtils.cleanup(email);
}

@Transient
public String getFullName() {
String fullName = lastName + ", " + firstName;
if (! (middleInitial == null || "".equals(middleInitial.trim()))) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,14 @@

import static org.springframework.util.Assert.notNull;

import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.springinpractice.ch02.model.Contact;
import com.springinpractice.ch02.service.ContactService;
Expand All @@ -31,71 +28,53 @@
* @author Willie Wheeler (willie.wheeler@gmail.com)
*/
@Service
@Transactional
public class ContactServiceImpl implements ContactService {
private static final String CREATE_SQL =
"insert into contact (last_name, first_name, mi, email) values (:lastName, :firstName, :mi, :email)";
private static final String FIND_ALL_SQL =
"select id, last_name, first_name, mi, email from contact";
private static final String FIND_ALL_BY_EMAIL_LIKE_SQL =
"select id, last_name, first_name, mi, email from contact where email like :email";
private static final String FIND_ONE_SQL =
"select id, last_name, first_name, mi, email from contact where id = :id";
private static final String UPDATE_SQL =
"update contact set last_name = :lastName, first_name = :firstName, mi = :mi, email = :email " +
"where id = :id";
private static final String DELETE_SQL =
"delete from contact where id = :id";

@Inject private NamedParameterJdbcOperations jdbcTemplate;
@Inject private ContactRowMapper contactRowMapper;
@Inject private SessionFactory sessionFactory;

@Override
public void createContact(Contact contact) {
notNull(contact, "contact can't be null");
SqlParameterSource params = new MapSqlParameterSource()
.addValue("lastName", contact.getLastName())
.addValue("firstName", contact.getFirstName())
.addValue("mi", contact.getMiddleInitial())
.addValue("email", contact.getEmail());
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(CREATE_SQL, params, keyHolder);
contact.setId(keyHolder.getKey().longValue());
getSession().save(contact);
}

@Override
@SuppressWarnings("unchecked")
public List<Contact> getContacts() {
return jdbcTemplate.query(FIND_ALL_SQL, new HashMap<String, Object>(), contactRowMapper);
return getSession()
.createQuery("from Contact")
.list();
}

@Override
@SuppressWarnings("unchecked")
public List<Contact> getContactsByEmail(String email) {
notNull(email, "email can't be null");
SqlParameterSource params = new MapSqlParameterSource("email", "%" + email + "%");
return jdbcTemplate.query(FIND_ALL_BY_EMAIL_LIKE_SQL, params, contactRowMapper);
return getSession()
.getNamedQuery("findContactsByEmail")
.setString("email", "%" + email + "%")
.list();
}

@Override
public Contact getContact(Long id) {
notNull(id, "id can't be null");
SqlParameterSource params = new MapSqlParameterSource("id", id);
return jdbcTemplate.queryForObject(FIND_ONE_SQL, params, contactRowMapper);
return (Contact) getSession().get(Contact.class, id);
}

@Override
public void updateContact(Contact contact) {
notNull(contact, "contact can't be null");
SqlParameterSource params = new MapSqlParameterSource()
.addValue("id", contact.getId())
.addValue("lastName", contact.getLastName())
.addValue("firstName", contact.getFirstName())
.addValue("mi", contact.getMiddleInitial())
.addValue("email", contact.getEmail());
jdbcTemplate.update(UPDATE_SQL, params);
getSession().update(contact);
}

@Override
public void deleteContact(Long id) {
notNull(id, "id can't be null");
jdbcTemplate.update(DELETE_SQL, new MapSqlParameterSource("id", id));
getSession().delete(getContact(id));
}

private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
39 changes: 27 additions & 12 deletions src/main/resources/spring/beans-service.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,41 @@ Code: https://github.com/springinpractice
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">

<context:property-placeholder location="classpath:/spring/environment.properties" />
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/Sip02DS" resource-ref="true" />

<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${dataSource.driverClassName}"
p:url="${dataSource.url}"
p:username="${dataSource.username}"
p:password="${dataSource.password}" />
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">false</prop>
</util:properties>

<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
c:dataSource-ref="dataSource" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="com.springinpractice.ch02.model"
p:hibernateProperties-ref="hibernateProperties" />

<context:component-scan base-package="com.springinpractice.ch02.service" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />

<tx:annotation-driven />

<context:component-scan base-package="com.springinpractice.ch02.service.impl" />
</beans>
4 changes: 2 additions & 2 deletions src/main/webapp/WEB-INF/web.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
</context-param>
<context-param>
<param-name>recipe</param-name>
<param-value>2.1</param-value>
<param-value>2.3</param-value>
</context-param>
<context-param>
<param-name>aboutThisRecipe</param-name>
<param-value><![CDATA[
<p>Shows how to use Spring's JdbcTemplate for data access.</p>
<p>Shows how to use object/relational mapping for database access.</p>
]]></param-value>
</context-param>

Expand Down