migrated from SimpleJdbcTemplate to JdbcTemplate

This commit is contained in:
Mic 2013-01-14 22:13:04 +08:00
parent 4e35adb6b0
commit 608c42f74b
15 changed files with 108 additions and 207 deletions

View file

@ -15,6 +15,7 @@ import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
@ -42,7 +43,7 @@ import org.springframework.transaction.annotation.Transactional;
* {@link ParameterizedBeanPropertyRowMapper} which provide automatic mapping
* between JavaBean properties and JDBC parameters or query results.
*
* <p>SimpleJdbcClinic is a rewrite of the AbstractJdbcClinic which was the base
* <p>JdbcClinic is a rewrite of the AbstractJdbcClinic which was the base
* class for JDBC implementations of the Clinic interface for Spring 2.0.
*
* @author Ken Krebs
@ -54,11 +55,12 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Service
@ManagedResource("petclinic:type=Clinic")
public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
public class JdbcClinic implements Clinic, JdbcClinicMBean {
private final Logger logger = LoggerFactory.getLogger(getClass());
private JdbcTemplate simpleJdbcTemplate;
private JdbcTemplate jdbcTemplate;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private SimpleJdbcInsert insertOwner;
private SimpleJdbcInsert insertPet;
@ -69,7 +71,8 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
@Autowired
public void init(DataSource dataSource) {
this.simpleJdbcTemplate = new JdbcTemplate(dataSource);
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
this.insertOwner = new SimpleJdbcInsert(dataSource)
.withTableName("owners")
@ -95,18 +98,18 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
// Retrieve the list of all vets.
this.vets.clear();
this.vets.addAll(this.simpleJdbcTemplate.query(
this.vets.addAll(this.jdbcTemplate.query(
"SELECT id, first_name, last_name FROM vets ORDER BY last_name,first_name",
ParameterizedBeanPropertyRowMapper.newInstance(Vet.class)));
// Retrieve the list of all possible specialties.
final List<Specialty> specialties = this.simpleJdbcTemplate.query(
final List<Specialty> specialties = this.jdbcTemplate.query(
"SELECT id, name FROM specialties",
ParameterizedBeanPropertyRowMapper.newInstance(Specialty.class));
// Build each vet's list of specialties.
for (Vet vet : this.vets) {
final List<Integer> vetSpecialtiesIds = this.simpleJdbcTemplate.query(
final List<Integer> vetSpecialtiesIds = this.jdbcTemplate.query(
"SELECT specialty_id FROM vet_specialties WHERE vet_id=?",
new ParameterizedRowMapper<Integer>() {
public Integer mapRow(ResultSet rs, int row) throws SQLException {
@ -136,7 +139,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
@Transactional(readOnly = true)
public Collection<PetType> getPetTypes() throws DataAccessException {
return this.simpleJdbcTemplate.query(
return this.jdbcTemplate.query(
"SELECT id, name FROM types ORDER BY name",
ParameterizedBeanPropertyRowMapper.newInstance(PetType.class));
}
@ -149,7 +152,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
*/
@Transactional(readOnly = true)
public Collection<Owner> findOwners(String lastName) throws DataAccessException {
List<Owner> owners = this.simpleJdbcTemplate.query(
List<Owner> owners = this.jdbcTemplate.query(
"SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE last_name like ?",
ParameterizedBeanPropertyRowMapper.newInstance(Owner.class),
lastName + "%");
@ -166,7 +169,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
public Owner findOwner(int id) throws DataAccessException {
Owner owner;
try {
owner = this.simpleJdbcTemplate.queryForObject(
owner = this.jdbcTemplate.queryForObject(
"SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE id=?",
ParameterizedBeanPropertyRowMapper.newInstance(Owner.class),
id);
@ -182,7 +185,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
public Pet findPet(int id) throws DataAccessException {
JdbcPet pet;
try {
pet = this.simpleJdbcTemplate.queryForObject(
pet = this.jdbcTemplate.queryForObject(
"SELECT id, name, birth_date, type_id, owner_id FROM pets WHERE id=?",
new JdbcPetRowMapper(),
id);
@ -205,7 +208,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
owner.setId(newKey.intValue());
}
else {
this.simpleJdbcTemplate.update(
this.namedParameterJdbcTemplate.update(
"UPDATE owners SET first_name=:firstName, last_name=:lastName, address=:address, " +
"city=:city, telephone=:telephone WHERE id=:id",
new BeanPropertySqlParameterSource(owner));
@ -220,7 +223,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
pet.setId(newKey.intValue());
}
else {
this.simpleJdbcTemplate.update(
this.namedParameterJdbcTemplate.update(
"UPDATE pets SET name=:name, birth_date=:birth_date, type_id=:type_id, " +
"owner_id=:owner_id WHERE id=:id",
createPetParameterSource(pet));
@ -240,7 +243,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
}
public void deletePet(int id) throws DataAccessException {
this.simpleJdbcTemplate.update("DELETE FROM pets WHERE id=?", id);
this.jdbcTemplate.update("DELETE FROM pets WHERE id=?", id);
}
// END of Clinic implementation section ************************************
@ -275,7 +278,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
* Loads the {@link Visit} data for the supplied {@link Pet}.
*/
private void loadVisits(JdbcPet pet) {
final List<Visit> visits = this.simpleJdbcTemplate.query(
final List<Visit> visits = this.jdbcTemplate.query(
"SELECT id, visit_date, description FROM visits WHERE pet_id=?",
new ParameterizedRowMapper<Visit>() {
public Visit mapRow(ResultSet rs, int row) throws SQLException {
@ -297,7 +300,7 @@ public class SimpleJdbcClinic implements Clinic, SimpleJdbcClinicMBean {
* {@link Owner}.
*/
private void loadPetsAndVisits(final Owner owner) {
final List<JdbcPet> pets = this.simpleJdbcTemplate.query(
final List<JdbcPet> pets = this.jdbcTemplate.query(
"SELECT id, name, birth_date, type_id, owner_id FROM pets WHERE owner_id=?",
new JdbcPetRowMapper(),
owner.getId().intValue());

View file

@ -6,14 +6,14 @@ package org.springframework.samples.petclinic.jdbc;
*
* @author Rob Harrop
* @author Juergen Hoeller
* @see SimpleJdbcClinic
* @see JdbcClinic
*/
public interface SimpleJdbcClinicMBean {
public interface JdbcClinicMBean {
/**
* Refresh the cache of Vets that the Clinic is holding.
* @see org.springframework.samples.petclinic.Clinic#getVets()
* @see SimpleJdbcClinic#refreshVetsCache()
* @see JdbcClinic#refreshVetsCache()
*/
void refreshVetsCache();

View file

@ -7,7 +7,7 @@ import org.springframework.samples.petclinic.Pet;
* are only relevant for a JDBC implmentation of the Clinic.
*
* @author Juergen Hoeller
* @see SimpleJdbcClinic
* @see JdbcClinic
*/
class JdbcPet extends Pet {

View file

@ -1,3 +1,12 @@
drop table vet_specialties if exists;
drop table vets if exists;
drop table specialties if exists;
drop table visits if exists;
drop table pets if exists;
drop table types if exists;
drop table owners if exists;
CREATE TABLE vets (
id INTEGER IDENTITY PRIMARY KEY,
first_name VARCHAR(30),

View file

@ -19,6 +19,10 @@
<level value="DEBUG" />
</logger>
<logger name="org.springframework.jdbc">
<level value="DEBUG" />
</logger>
<!-- Root Logger -->

View file

@ -56,7 +56,7 @@
<context:mbean-export/>
<!-- PetClinic's central data access object using Spring's SimpleJdbcTemplate -->
<bean id="clinic" class="org.springframework.samples.petclinic.jdbc.SimpleJdbcClinic"/>
<bean id="clinic" class="org.springframework.samples.petclinic.jdbc.JdbcClinic"/>
<!-- Call monitoring aspect that monitors call count and call invocation time -->
<bean id="callMonitor" class="org.springframework.samples.petclinic.aspects.CallMonitoringAspect"/>

View file

@ -480,7 +480,7 @@
<p>
The JDBC implementation of the Clinic interface is
<span style="font-weight: bold; font-style: italic;">org.springframework.samples.petclinic.jdbc.SimpleJdbcClinic</span>,
<span style="font-weight: bold; font-style: italic;">org.springframework.samples.petclinic.jdbc.JdbcClinic</span>,
which uses Java 5 language features,
<strong>org.springframework.jdbc.core.simple.SimpleJdbcTemplate</strong>, and
<strong>org.springframework.jdbc.core.simple.SimpleJdbcInsert</strong>.

View file

@ -81,7 +81,6 @@ import org.springframework.transaction.annotation.Transactional;
* @author Juergen Hoeller
* @author Sam Brannen
*/
@ContextConfiguration
public abstract class AbstractClinicTests {
@Autowired
@ -121,8 +120,8 @@ public abstract class AbstractClinicTests {
assertEquals(0, owners.size());
}
@Test
public void loadOwner() {
@Test @Transactional
public void findOwner() {
Owner o1 = this.clinic.findOwner(1);
assertTrue(o1.getLastName().startsWith("Franklin"));
Owner o10 = this.clinic.findOwner(10);
@ -163,7 +162,7 @@ public abstract class AbstractClinicTests {
}
@Test
public void loadPet() {
public void findPet() {
Collection<PetType> types = this.clinic.getPetTypes();
Pet p7 = this.clinic.findPet(7);
assertTrue(p7.getName().startsWith("Samantha"));
@ -175,7 +174,7 @@ public abstract class AbstractClinicTests {
assertEquals("Peter", p6.getOwner().getFirstName());
}
@Test
@Test @Transactional
public void insertPet() {
Owner o6 = this.clinic.findOwner(6);
int found = o6.getPets().size();
@ -204,7 +203,7 @@ public abstract class AbstractClinicTests {
assertEquals(old + "X", p7.getName());
}
@Test
@Test @Transactional
public void insertVisit() {
Pet p7 = this.clinic.findPet(7);
int found = p7.getVisits().size();

View file

@ -5,6 +5,7 @@ import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.aspects.UsageLogAspect;
import org.springframework.samples.petclinic.jpa.JpaClinicTests;
import org.springframework.test.context.ContextConfiguration;
@ -27,11 +28,14 @@ import static junit.framework.Assert.assertFalse;
*/
@ContextConfiguration(locations={"classpath:spring/applicationContext-jpa.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class UsageLogAspectTests extends JpaClinicTests {
public class UsageLogAspectTests {
@Autowired
private UsageLogAspect usageLogAspect;
@Autowired
private Clinic clinic;
@Test
public void testUsageLogAspectIsInvoked() {

View file

@ -0,0 +1,26 @@
package org.springframework.samples.petclinic.jdbc;
import org.junit.runner.RunWith;
import org.springframework.samples.petclinic.AbstractClinicTests;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <p>
* Integration tests for the {@link JdbcClinic} implementation.
* </p>
* <p>
* "JdbcClinicTests-context.xml" determines the actual beans to test.
* </p>
*
* @author Thomas Risberg
*/
@ContextConfiguration(locations={"classpath:spring/applicationContext-jdbc.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@DirtiesContext
public class JdbcClinicTests extends AbstractClinicTests {
}

View file

@ -1,21 +0,0 @@
package org.springframework.samples.petclinic.jdbc;
import org.springframework.samples.petclinic.AbstractClinicTests;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
/**
* <p>
* Integration tests for the {@link SimpleJdbcClinic} implementation.
* </p>
* <p>
* "SimpleJdbcClinicTests-context.xml" determines the actual beans to test.
* </p>
*
* @author Thomas Risberg
*/
@ContextConfiguration
@DirtiesContext
public class SimpleJdbcClinicTests extends AbstractClinicTests {
}

View file

@ -14,6 +14,7 @@ import javax.persistence.PersistenceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.AbstractClinicTests;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
@ -46,13 +47,13 @@ import org.springframework.transaction.annotation.Transactional;
@ContextConfiguration(locations={"classpath:spring/applicationContext-jpa.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class JpaClinicTests {
public class JpaClinicTests extends AbstractClinicTests {
@PersistenceContext
private EntityManager entityManager;
@Autowired
protected Clinic clinic;
private Clinic clinic;
@Test
@ -65,120 +66,4 @@ public class JpaClinicTests {
}
}
@Test @Transactional
public void testGetVets() {
Collection<Vet> vets = this.clinic.getVets();
Vet v1 = EntityUtils.getById(vets, Vet.class, 2);
assertEquals("Leary", v1.getLastName());
assertEquals(1, v1.getNrOfSpecialties());
assertEquals("radiology", (v1.getSpecialties().get(0)).getName());
Vet v2 = EntityUtils.getById(vets, Vet.class, 3);
assertEquals("Douglas", v2.getLastName());
assertEquals(2, v2.getNrOfSpecialties());
assertEquals("dentistry", (v2.getSpecialties().get(0)).getName());
assertEquals("surgery", (v2.getSpecialties().get(1)).getName());
}
@Test
public void testGetPetTypes() {
Collection<PetType> petTypes = this.clinic.getPetTypes();
PetType t1 = EntityUtils.getById(petTypes, PetType.class, 1);
assertEquals("cat", t1.getName());
PetType t4 = EntityUtils.getById(petTypes, PetType.class, 4);
assertEquals("snake", t4.getName());
}
@Test
public void testFindOwners() {
Collection<Owner> owners = this.clinic.findOwners("Davis");
assertEquals(2, owners.size());
owners = this.clinic.findOwners("Daviss");
assertEquals(0, owners.size());
}
@Test
public void tesFindOwner() {
Owner o1 = this.clinic.findOwner(1);
assertTrue(o1.getLastName().startsWith("Franklin"));
Owner o10 = this.clinic.findOwner(10);
assertEquals("Carlos", o10.getFirstName());
}
@Test
public void testInsertOwner() {
Collection<Owner> owners = this.clinic.findOwners("Schultz");
int found = owners.size();
Owner owner = new Owner();
owner.setLastName("Schultz");
this.clinic.storeOwner(owner);
// assertTrue(!owner.isNew()); -- NOT TRUE FOR TOPLINK (before commit)
owners = this.clinic.findOwners("Schultz");
assertEquals(found + 1, owners.size());
}
@Test
public void testUpdateOwner() throws Exception {
Owner o1 = this.clinic.findOwner(1);
String old = o1.getLastName();
o1.setLastName(old + "X");
this.clinic.storeOwner(o1);
o1 = this.clinic.findOwner(1);
assertEquals(old + "X", o1.getLastName());
}
@Test
public void testFindPet() {
Collection<PetType> types = this.clinic.getPetTypes();
Pet p7 = this.clinic.findPet(7);
assertTrue(p7.getName().startsWith("Samantha"));
assertEquals(EntityUtils.getById(types, PetType.class, 1).getId(), p7.getType().getId());
assertEquals("Jean", p7.getOwner().getFirstName());
Pet p6 = this.clinic.findPet(6);
assertEquals("George", p6.getName());
assertEquals(EntityUtils.getById(types, PetType.class, 4).getId(), p6.getType().getId());
assertEquals("Peter", p6.getOwner().getFirstName());
}
@Test @Transactional
public void testInsertPet() {
Owner o6 = this.clinic.findOwner(6);
int found = o6.getPets().size();
Pet pet = new Pet();
pet.setName("bowser");
Collection<PetType> types = this.clinic.getPetTypes();
pet.setType(EntityUtils.getById(types, PetType.class, 2));
pet.setBirthDate(new Date());
o6.addPet(pet);
assertEquals(found + 1, o6.getPets().size());
this.clinic.storeOwner(o6);
// assertTrue(!pet.isNew()); -- NOT TRUE FOR TOPLINK (before commit)
o6 = this.clinic.findOwner(6);
assertEquals(found + 1, o6.getPets().size());
}
@Test
public void testUpdatePet() throws Exception {
Pet p7 = this.clinic.findPet(7);
String old = p7.getName();
p7.setName(old + "X");
this.clinic.storePet(p7);
p7 = this.clinic.findPet(7);
assertEquals(old + "X", p7.getName());
}
@Test @Transactional
public void testInsertVisit() {
Pet p7 = this.clinic.findPet(7);
int found = p7.getVisits().size();
Visit visit = new Visit();
p7.addVisit(visit);
visit.setDescription("test");
this.clinic.storePet(p7);
// assertTrue(!visit.isNew()); -- NOT TRUE FOR TOPLINK (before commit)
p7 = this.clinic.findPet(7);
assertEquals(found + 1, p7.getVisits().size());
}
}

View file

@ -1,27 +0,0 @@
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<context:annotation-config/>
<tx:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}"/>
<jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">
<jdbc:script location="${jdbc.initLocation}"/>
<jdbc:script location="${jdbc.dataLocation}"/>
</jdbc:initialize-database>
</beans>

View file

@ -0,0 +1,30 @@
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:property-placeholder location="classpath:spring/jdbc.properties"/>
<context:annotation-config/>
<tx:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}"/>
<jdbc:initialize-database data-source="dataSource" ignore-failures="ALL">
<jdbc:script location="${jdbc.initLocation}"/>
<jdbc:script location="${jdbc.dataLocation}"/>
</jdbc:initialize-database>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />
<bean class="org.springframework.samples.petclinic.jdbc.JdbcClinic" />
</beans>

View file

@ -1,11 +0,0 @@
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />
<bean class="org.springframework.samples.petclinic.jdbc.SimpleJdbcClinic" />
</beans>