Rename modules {org.springframework.*=>spring-*}
This renaming more intuitively expresses the relationship between
subprojects and the JAR artifacts they produce.
Tracking history across these renames is possible, but it requires
use of the --follow flag to `git log`, for example
$ git log spring-aop/src/main/java/org/springframework/aop/Advisor.java
will show history up until the renaming event, where
$ git log --follow spring-aop/src/main/java/org/springframework/aop/Advisor.java
will show history for all changes to the file, before and after the
renaming.
See http://chrisbeams.com/git-diff-across-renamed-directories
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans;
|
||||
|
||||
import org.springframework.core.enums.ShortCodedLabeledEnum;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class Colour extends ShortCodedLabeledEnum {
|
||||
|
||||
public static final Colour RED = new Colour(0, "RED");
|
||||
public static final Colour BLUE = new Colour(1, "BLUE");
|
||||
public static final Colour GREEN = new Colour(2, "GREEN");
|
||||
public static final Colour PURPLE = new Colour(3, "PURPLE");
|
||||
|
||||
private Colour(int code, String label) {
|
||||
super(code, label);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
public interface INestedTestBean {
|
||||
|
||||
public String getCompany();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
public interface IOther {
|
||||
|
||||
void absquatulate();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Interface used for {@link org.springframework.beans.TestBean}.
|
||||
*
|
||||
* <p>Two methods are the same as on Person, but if this
|
||||
* extends person it breaks quite a few tests..
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public interface ITestBean {
|
||||
|
||||
int getAge();
|
||||
|
||||
void setAge(int age);
|
||||
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
ITestBean getSpouse();
|
||||
|
||||
void setSpouse(ITestBean spouse);
|
||||
|
||||
ITestBean[] getSpouses();
|
||||
|
||||
String[] getStringArray();
|
||||
|
||||
void setStringArray(String[] stringArray);
|
||||
|
||||
/**
|
||||
* Throws a given (non-null) exception.
|
||||
*/
|
||||
void exceptional(Throwable t) throws Throwable;
|
||||
|
||||
Object returnsThis();
|
||||
|
||||
INestedTestBean getDoctor();
|
||||
|
||||
INestedTestBean getLawyer();
|
||||
|
||||
IndexedTestBean getNestedIndexedBean();
|
||||
|
||||
/**
|
||||
* Increment the age by one.
|
||||
* @return the previous age
|
||||
*/
|
||||
int haveBirthday();
|
||||
|
||||
void unreliableFileOperation() throws IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.beans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 11.11.2003
|
||||
*/
|
||||
public class IndexedTestBean {
|
||||
|
||||
private TestBean[] array;
|
||||
|
||||
private Collection collection;
|
||||
|
||||
private List list;
|
||||
|
||||
private Set set;
|
||||
|
||||
private SortedSet sortedSet;
|
||||
|
||||
private Map map;
|
||||
|
||||
private SortedMap sortedMap;
|
||||
|
||||
|
||||
public IndexedTestBean() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
public IndexedTestBean(boolean populate) {
|
||||
if (populate) {
|
||||
populate();
|
||||
}
|
||||
}
|
||||
|
||||
public void populate() {
|
||||
TestBean tb0 = new TestBean("name0", 0);
|
||||
TestBean tb1 = new TestBean("name1", 0);
|
||||
TestBean tb2 = new TestBean("name2", 0);
|
||||
TestBean tb3 = new TestBean("name3", 0);
|
||||
TestBean tb4 = new TestBean("name4", 0);
|
||||
TestBean tb5 = new TestBean("name5", 0);
|
||||
TestBean tb6 = new TestBean("name6", 0);
|
||||
TestBean tb7 = new TestBean("name7", 0);
|
||||
TestBean tbX = new TestBean("nameX", 0);
|
||||
TestBean tbY = new TestBean("nameY", 0);
|
||||
this.array = new TestBean[] {tb0, tb1};
|
||||
this.list = new ArrayList();
|
||||
this.list.add(tb2);
|
||||
this.list.add(tb3);
|
||||
this.set = new TreeSet();
|
||||
this.set.add(tb6);
|
||||
this.set.add(tb7);
|
||||
this.map = new HashMap();
|
||||
this.map.put("key1", tb4);
|
||||
this.map.put("key2", tb5);
|
||||
this.map.put("key.3", tb5);
|
||||
List list = new ArrayList();
|
||||
list.add(tbX);
|
||||
list.add(tbY);
|
||||
this.map.put("key4", list);
|
||||
}
|
||||
|
||||
|
||||
public TestBean[] getArray() {
|
||||
return array;
|
||||
}
|
||||
|
||||
public void setArray(TestBean[] array) {
|
||||
this.array = array;
|
||||
}
|
||||
|
||||
public Collection getCollection() {
|
||||
return collection;
|
||||
}
|
||||
|
||||
public void setCollection(Collection collection) {
|
||||
this.collection = collection;
|
||||
}
|
||||
|
||||
public List getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Set getSet() {
|
||||
return set;
|
||||
}
|
||||
|
||||
public void setSet(Set set) {
|
||||
this.set = set;
|
||||
}
|
||||
|
||||
public SortedSet getSortedSet() {
|
||||
return sortedSet;
|
||||
}
|
||||
|
||||
public void setSortedSet(SortedSet sortedSet) {
|
||||
this.sortedSet = sortedSet;
|
||||
}
|
||||
|
||||
public Map getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
public void setMap(Map map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public SortedMap getSortedMap() {
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
public void setSortedMap(SortedMap sortedMap) {
|
||||
this.sortedMap = sortedMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
/**
|
||||
* Simple nested test bean used for testing bean factories, AOP framework etc.
|
||||
*
|
||||
* @author Trevor D. Cook
|
||||
* @since 30.09.2003
|
||||
*/
|
||||
public class NestedTestBean implements INestedTestBean {
|
||||
|
||||
private String company = "";
|
||||
|
||||
public NestedTestBean() {
|
||||
}
|
||||
|
||||
public NestedTestBean(String company) {
|
||||
setCompany(company);
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = (company != null ? company : "");
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof NestedTestBean)) {
|
||||
return false;
|
||||
}
|
||||
NestedTestBean ntb = (NestedTestBean) obj;
|
||||
return this.company.equals(ntb.company);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.company.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "NestedTestBean: " + this.company;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* Simple test bean used for testing bean factories, the AOP framework etc.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 15 April 2001
|
||||
*/
|
||||
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
|
||||
|
||||
private String beanName;
|
||||
|
||||
private String country;
|
||||
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
private boolean postProcessed;
|
||||
|
||||
private String name;
|
||||
|
||||
private String sex;
|
||||
|
||||
private int age;
|
||||
|
||||
private boolean jedi;
|
||||
|
||||
private ITestBean[] spouses;
|
||||
|
||||
private String touchy;
|
||||
|
||||
private String[] stringArray;
|
||||
|
||||
private Integer[] someIntegerArray;
|
||||
|
||||
private Date date = new Date();
|
||||
|
||||
private Float myFloat = new Float(0.0);
|
||||
|
||||
private Collection friends = new LinkedList();
|
||||
|
||||
private Set someSet = new HashSet();
|
||||
|
||||
private Map someMap = new HashMap();
|
||||
|
||||
private List someList = new ArrayList();
|
||||
|
||||
private Properties someProperties = new Properties();
|
||||
|
||||
private INestedTestBean doctor = new NestedTestBean();
|
||||
|
||||
private INestedTestBean lawyer = new NestedTestBean();
|
||||
|
||||
private IndexedTestBean nestedIndexedBean;
|
||||
|
||||
private boolean destroyed;
|
||||
|
||||
private Number someNumber;
|
||||
|
||||
private Colour favouriteColour;
|
||||
|
||||
private Boolean someBoolean;
|
||||
|
||||
private List otherColours;
|
||||
|
||||
private List pets;
|
||||
|
||||
|
||||
public TestBean() {
|
||||
}
|
||||
|
||||
public TestBean(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public TestBean(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse, Properties someProperties) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public TestBean(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public TestBean(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public TestBean(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public TestBean(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
public BeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
public void setPostProcessed(boolean postProcessed) {
|
||||
this.postProcessed = postProcessed;
|
||||
}
|
||||
|
||||
public boolean isPostProcessed() {
|
||||
return postProcessed;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSex() {
|
||||
return sex;
|
||||
}
|
||||
|
||||
public void setSex(String sex) {
|
||||
this.sex = sex;
|
||||
if (this.name == null) {
|
||||
this.name = sex;
|
||||
}
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public boolean isJedi() {
|
||||
return jedi;
|
||||
}
|
||||
|
||||
public void setJedi(boolean jedi) {
|
||||
this.jedi = jedi;
|
||||
}
|
||||
|
||||
public ITestBean getSpouse() {
|
||||
return (spouses != null ? spouses[0] : null);
|
||||
}
|
||||
|
||||
public void setSpouse(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public ITestBean[] getSpouses() {
|
||||
return spouses;
|
||||
}
|
||||
|
||||
public String getTouchy() {
|
||||
return touchy;
|
||||
}
|
||||
|
||||
public void setTouchy(String touchy) throws Exception {
|
||||
if (touchy.indexOf('.') != -1) {
|
||||
throw new Exception("Can't contain a .");
|
||||
}
|
||||
if (touchy.indexOf(',') != -1) {
|
||||
throw new NumberFormatException("Number format exception: contains a ,");
|
||||
}
|
||||
this.touchy = touchy;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String[] getStringArray() {
|
||||
return stringArray;
|
||||
}
|
||||
|
||||
public void setStringArray(String[] stringArray) {
|
||||
this.stringArray = stringArray;
|
||||
}
|
||||
|
||||
public Integer[] getSomeIntegerArray() {
|
||||
return someIntegerArray;
|
||||
}
|
||||
|
||||
public void setSomeIntegerArray(Integer[] someIntegerArray) {
|
||||
this.someIntegerArray = someIntegerArray;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Float getMyFloat() {
|
||||
return myFloat;
|
||||
}
|
||||
|
||||
public void setMyFloat(Float myFloat) {
|
||||
this.myFloat = myFloat;
|
||||
}
|
||||
|
||||
public Collection getFriends() {
|
||||
return friends;
|
||||
}
|
||||
|
||||
public void setFriends(Collection friends) {
|
||||
this.friends = friends;
|
||||
}
|
||||
|
||||
public Set getSomeSet() {
|
||||
return someSet;
|
||||
}
|
||||
|
||||
public void setSomeSet(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public Map getSomeMap() {
|
||||
return someMap;
|
||||
}
|
||||
|
||||
public void setSomeMap(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public List getSomeList() {
|
||||
return someList;
|
||||
}
|
||||
|
||||
public void setSomeList(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public Properties getSomeProperties() {
|
||||
return someProperties;
|
||||
}
|
||||
|
||||
public void setSomeProperties(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public INestedTestBean getDoctor() {
|
||||
return doctor;
|
||||
}
|
||||
|
||||
public void setDoctor(INestedTestBean doctor) {
|
||||
this.doctor = doctor;
|
||||
}
|
||||
|
||||
public INestedTestBean getLawyer() {
|
||||
return lawyer;
|
||||
}
|
||||
|
||||
public void setLawyer(INestedTestBean lawyer) {
|
||||
this.lawyer = lawyer;
|
||||
}
|
||||
|
||||
public Number getSomeNumber() {
|
||||
return someNumber;
|
||||
}
|
||||
|
||||
public void setSomeNumber(Number someNumber) {
|
||||
this.someNumber = someNumber;
|
||||
}
|
||||
|
||||
public Colour getFavouriteColour() {
|
||||
return favouriteColour;
|
||||
}
|
||||
|
||||
public void setFavouriteColour(Colour favouriteColour) {
|
||||
this.favouriteColour = favouriteColour;
|
||||
}
|
||||
|
||||
public Boolean getSomeBoolean() {
|
||||
return someBoolean;
|
||||
}
|
||||
|
||||
public void setSomeBoolean(Boolean someBoolean) {
|
||||
this.someBoolean = someBoolean;
|
||||
}
|
||||
|
||||
public IndexedTestBean getNestedIndexedBean() {
|
||||
return nestedIndexedBean;
|
||||
}
|
||||
|
||||
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
|
||||
this.nestedIndexedBean = nestedIndexedBean;
|
||||
}
|
||||
|
||||
public List getOtherColours() {
|
||||
return otherColours;
|
||||
}
|
||||
|
||||
public void setOtherColours(List otherColours) {
|
||||
this.otherColours = otherColours;
|
||||
}
|
||||
|
||||
public List getPets() {
|
||||
return pets;
|
||||
}
|
||||
|
||||
public void setPets(List pets) {
|
||||
this.pets = pets;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#exceptional(Throwable)
|
||||
*/
|
||||
public void exceptional(Throwable t) throws Throwable {
|
||||
if (t != null) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
public void unreliableFileOperation() throws IOException {
|
||||
throw new IOException();
|
||||
}
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#returnsThis()
|
||||
*/
|
||||
public Object returnsThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.IOther#absquatulate()
|
||||
*/
|
||||
public void absquatulate() {
|
||||
}
|
||||
|
||||
public int haveBirthday() {
|
||||
return age++;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean wasDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (other == null || !(other instanceof TestBean)) {
|
||||
return false;
|
||||
}
|
||||
TestBean tb2 = (TestBean) other;
|
||||
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.age;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (this.name != null && other instanceof TestBean) {
|
||||
return this.name.compareTo(((TestBean) other).getName());
|
||||
}
|
||||
else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* AbstractJdbcTests.java
|
||||
*
|
||||
* Copyright (C) 2002 by Interprise Software. All rights reserved.
|
||||
*/
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
/**
|
||||
* @author Trevor D. Cook
|
||||
*/
|
||||
public abstract class AbstractJdbcTests extends TestCase {
|
||||
|
||||
protected MockControl ctrlDataSource;
|
||||
protected DataSource mockDataSource;
|
||||
protected MockControl ctrlConnection;
|
||||
protected Connection mockConnection;
|
||||
|
||||
/**
|
||||
* Set to true if the user wants verification, indicated
|
||||
* by a call to replay(). We need to make this optional,
|
||||
* otherwise we setUp() will always result in verification failures
|
||||
*/
|
||||
private boolean shouldVerify;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
this.shouldVerify = false;
|
||||
super.setUp();
|
||||
|
||||
ctrlConnection = MockControl.createControl(Connection.class);
|
||||
mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setDefaultReturnValue(null);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setDefaultVoidCallable();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDataSource.replay();
|
||||
ctrlConnection.replay();
|
||||
this.shouldVerify = true;
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
|
||||
// we shouldn't verify unless the user called replay()
|
||||
if (shouldVerify()) {
|
||||
ctrlDataSource.verify();
|
||||
//ctrlConnection.verify();
|
||||
}
|
||||
}
|
||||
|
||||
protected boolean shouldVerify() {
|
||||
return this.shouldVerify;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class Customer {
|
||||
|
||||
private int id;
|
||||
|
||||
private String forename;
|
||||
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getForename() {
|
||||
return forename;
|
||||
}
|
||||
|
||||
public void setForename(String forename) {
|
||||
this.forename = forename;
|
||||
}
|
||||
|
||||
|
||||
public String toString() {
|
||||
return "Customer: id=" + id + "; forename=" + forename;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.jdbc.config;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public class InitializeDatabaseIntegrationTests {
|
||||
|
||||
private String enabled;
|
||||
private ClassPathXmlApplicationContext context;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
enabled = System.setProperty("ENABLED", "true");
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() {
|
||||
if (enabled != null) {
|
||||
System.setProperty("ENABLED", enabled);
|
||||
} else {
|
||||
System.clearProperty("ENABLED");
|
||||
}
|
||||
if (context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateEmbeddedDatabase() throws Exception {
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml");
|
||||
assertCorrectSetup(context.getBean("dataSource", DataSource.class));
|
||||
}
|
||||
|
||||
@Test(expected = BadSqlGrammarException.class)
|
||||
public void testDisableCreateEmbeddedDatabase() throws Exception {
|
||||
System.setProperty("ENABLED", "false");
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-config.xml");
|
||||
assertCorrectSetup(context.getBean("dataSource", DataSource.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIgnoreFailedDrops() throws Exception {
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-fail-config.xml");
|
||||
assertCorrectSetup(context.getBean("dataSource", DataSource.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testScriptNameWithPattern() throws Exception {
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-pattern-config.xml");
|
||||
DataSource dataSource = context.getBean("dataSource", DataSource.class);
|
||||
assertCorrectSetup(dataSource);
|
||||
JdbcTemplate t = new JdbcTemplate(dataSource);
|
||||
assertEquals("Dave", t.queryForObject("select name from T_TEST", String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testScriptNameWithPlaceholder() throws Exception {
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-placeholder-config.xml");
|
||||
DataSource dataSource = context.getBean("dataSource", DataSource.class);
|
||||
assertCorrectSetup(dataSource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testScriptNameWithExpressions() throws Exception {
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-expression-config.xml");
|
||||
DataSource dataSource = context.getBean("dataSource", DataSource.class);
|
||||
assertCorrectSetup(dataSource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCacheInitialization() throws Exception {
|
||||
context = new ClassPathXmlApplicationContext("org/springframework/jdbc/config/jdbc-initialize-cache-config.xml");
|
||||
assertCorrectSetup(context.getBean("dataSource", DataSource.class));
|
||||
CacheData cache = context.getBean(CacheData.class);
|
||||
assertEquals(1, cache.getCachedData().size());
|
||||
}
|
||||
|
||||
private void assertCorrectSetup(DataSource dataSource) {
|
||||
JdbcTemplate t = new JdbcTemplate(dataSource);
|
||||
assertEquals(1, t.queryForInt("select count(*) from T_TEST"));
|
||||
}
|
||||
|
||||
public static class CacheData implements InitializingBean {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private List<Map<String,Object>> cache;
|
||||
|
||||
public void setDataSource(DataSource dataSource) {
|
||||
this.jdbcTemplate = new JdbcTemplate(dataSource);
|
||||
}
|
||||
|
||||
public List<Map<String,Object>> getCachedData() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
cache = jdbcTemplate.queryForList("SELECT * FROM T_TEST");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.jdbc.config;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
import org.springframework.beans.PropertyValue;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean;
|
||||
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class JdbcNamespaceIntegrationTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException expected = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void testCreateEmbeddedDatabase() throws Exception {
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-config.xml");
|
||||
assertCorrectSetup(context, "dataSource", "h2DataSource", "derbyDataSource");
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateEmbeddedDatabaseAgain() throws Exception {
|
||||
// If Derby isn't cleaned up properly this will fail...
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-config.xml");
|
||||
assertCorrectSetup(context, "derbyDataSource");
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateWithResourcePattern() throws Exception {
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-config-pattern.xml");
|
||||
assertCorrectSetup(context, "dataSource");
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateWithEndings() throws Exception {
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-initialize-endings-config.xml");
|
||||
assertCorrectSetup(context, 2, "dataSource");
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateWithEndingsNested() throws Exception {
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-initialize-endings-nested-config.xml");
|
||||
assertCorrectSetup(context, 2, "dataSource");
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateAndDestroy() throws Exception {
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-destroy-config.xml");
|
||||
try {
|
||||
DataSource dataSource = context.getBean(DataSource.class);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
|
||||
context.getBean(DataSourceInitializer.class).destroy();
|
||||
expected.expect(BadSqlGrammarException.class); // Table has been dropped
|
||||
assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
|
||||
}
|
||||
finally {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateAndDestroyNested() throws Exception {
|
||||
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"org/springframework/jdbc/config/jdbc-destroy-nested-config.xml");
|
||||
try {
|
||||
DataSource dataSource = context.getBean(DataSource.class);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
|
||||
context.getBean(EmbeddedDatabaseFactoryBean.class).destroy();
|
||||
expected.expect(BadSqlGrammarException.class); // Table has been dropped
|
||||
assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
|
||||
}
|
||||
finally {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleDataSourcesHaveDifferentDatabaseNames() throws Exception {
|
||||
DefaultListableBeanFactory factory = new XmlBeanFactory(new ClassPathResource(
|
||||
"org/springframework/jdbc/config/jdbc-config-multiple-datasources.xml"));
|
||||
assertBeanPropertyValueOf("databaseName", "firstDataSource", factory);
|
||||
assertBeanPropertyValueOf("databaseName", "secondDataSource", factory);
|
||||
}
|
||||
|
||||
private void assertBeanPropertyValueOf(String propertyName, String expected, DefaultListableBeanFactory factory) {
|
||||
BeanDefinition bean = factory.getBeanDefinition(expected);
|
||||
PropertyValue value = bean.getPropertyValues().getPropertyValue(propertyName);
|
||||
assertThat(value, is(notNullValue()));
|
||||
assertThat(value.getValue().toString(), is(expected));
|
||||
}
|
||||
|
||||
private void assertCorrectSetup(ConfigurableApplicationContext context, String... dataSources) {
|
||||
assertCorrectSetup(context, 1, dataSources);
|
||||
}
|
||||
|
||||
private void assertCorrectSetup(ConfigurableApplicationContext context, int count, String... dataSources) {
|
||||
try {
|
||||
for (String dataSourceName : dataSources) {
|
||||
DataSource dataSource = context.getBean(dataSourceName, DataSource.class);
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
assertEquals(count, template.queryForInt("select count(*) from T_TEST"));
|
||||
}
|
||||
}
|
||||
finally {
|
||||
context.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.jdbc.core.test.ConcretePerson;
|
||||
import org.springframework.jdbc.core.test.Person;
|
||||
import org.springframework.jdbc.core.test.SpacePerson;
|
||||
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
|
||||
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
|
||||
|
||||
/**
|
||||
* Mock object based abstract class for RowMapper tests.
|
||||
* Initializes mock objects and verifies results.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public abstract class AbstractRowMapperTests extends TestCase {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
protected MockControl conControl;
|
||||
protected Connection con;
|
||||
protected MockControl conControl2;
|
||||
protected Connection con2;
|
||||
protected MockControl conControl3;
|
||||
protected Connection con3;
|
||||
|
||||
protected MockControl rsmdControl;
|
||||
protected ResultSetMetaData rsmd;
|
||||
protected MockControl rsControl;
|
||||
protected ResultSet rs;
|
||||
protected MockControl stmtControl;
|
||||
protected Statement stmt;
|
||||
protected JdbcTemplate jdbcTemplate;
|
||||
|
||||
protected MockControl rsmdControl2;
|
||||
protected ResultSetMetaData rsmd2;
|
||||
protected MockControl rsControl2;
|
||||
protected ResultSet rs2;
|
||||
protected MockControl stmtControl2;
|
||||
protected Statement stmt2;
|
||||
protected JdbcTemplate jdbcTemplate2;
|
||||
|
||||
protected MockControl rsmdControl3;
|
||||
protected ResultSetMetaData rsmd3;
|
||||
protected MockControl rsControl3;
|
||||
protected ResultSet rs3;
|
||||
protected MockControl stmtControl3;
|
||||
protected Statement stmt3;
|
||||
protected JdbcTemplate jdbcTemplate3;
|
||||
|
||||
protected void setUp() throws SQLException {
|
||||
conControl = MockControl.createControl(Connection.class);
|
||||
con = (Connection) conControl.getMock();
|
||||
con.isClosed();
|
||||
conControl.setDefaultReturnValue(false);
|
||||
|
||||
rsmdControl = MockControl.createControl(ResultSetMetaData.class);
|
||||
rsmd = (ResultSetMetaData)rsmdControl.getMock();
|
||||
rsmd.getColumnCount();
|
||||
rsmdControl.setReturnValue(4, 1);
|
||||
rsmd.getColumnLabel(1);
|
||||
rsmdControl.setReturnValue("name", 1);
|
||||
rsmd.getColumnLabel(2);
|
||||
rsmdControl.setReturnValue("age", 1);
|
||||
rsmd.getColumnLabel(3);
|
||||
rsmdControl.setReturnValue("birth_date", 1);
|
||||
rsmd.getColumnLabel(4);
|
||||
rsmdControl.setReturnValue("balance", 1);
|
||||
rsmdControl.replay();
|
||||
|
||||
rsControl = MockControl.createControl(ResultSet.class);
|
||||
rs = (ResultSet) rsControl.getMock();
|
||||
rs.getMetaData();
|
||||
rsControl.setReturnValue(rsmd, 1);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 1);
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue("Bubba", 1);
|
||||
rs.wasNull();
|
||||
rsControl.setReturnValue(false, 1);
|
||||
rs.getLong(2);
|
||||
rsControl.setReturnValue(22, 1);
|
||||
rs.getTimestamp(3);
|
||||
rsControl.setReturnValue(new Timestamp(1221222L), 1);
|
||||
rs.getBigDecimal(4);
|
||||
rsControl.setReturnValue(new BigDecimal("1234.56"), 1);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(false, 1);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(1);
|
||||
rsControl.replay();
|
||||
|
||||
stmtControl = MockControl.createControl(Statement.class);
|
||||
stmt = (Statement) stmtControl.getMock();
|
||||
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 1);
|
||||
stmt.executeQuery("select name, age, birth_date, balance from people");
|
||||
stmtControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
stmt.getWarnings();
|
||||
stmtControl.setReturnValue(null, 1);
|
||||
}
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
|
||||
conControl2 = MockControl.createControl(Connection.class);
|
||||
con2 = (Connection) conControl2.getMock();
|
||||
con2.isClosed();
|
||||
conControl2.setDefaultReturnValue(false);
|
||||
|
||||
rsmdControl2 = MockControl.createControl(ResultSetMetaData.class);
|
||||
rsmd2 = (ResultSetMetaData)rsmdControl2.getMock();
|
||||
rsmd2.getColumnCount();
|
||||
rsmdControl2.setReturnValue(4, 2);
|
||||
rsmd2.getColumnLabel(1);
|
||||
rsmdControl2.setReturnValue("name", 2);
|
||||
rsmd2.getColumnLabel(2);
|
||||
rsmdControl2.setReturnValue("age", 2);
|
||||
rsmd2.getColumnLabel(3);
|
||||
rsmdControl2.setReturnValue("birth_date", 1);
|
||||
rsmd2.getColumnLabel(4);
|
||||
rsmdControl2.setReturnValue("balance", 1);
|
||||
rsmdControl2.replay();
|
||||
|
||||
rsControl2 = MockControl.createControl(ResultSet.class);
|
||||
rs2 = (ResultSet) rsControl2.getMock();
|
||||
rs2.getMetaData();
|
||||
rsControl2.setReturnValue(rsmd2, 2);
|
||||
rs2.next();
|
||||
rsControl2.setReturnValue(true, 2);
|
||||
rs2.getString(1);
|
||||
rsControl2.setReturnValue("Bubba", 2);
|
||||
rs2.wasNull();
|
||||
rsControl2.setReturnValue(true, 2);
|
||||
rs2.getLong(2);
|
||||
rsControl2.setReturnValue(0, 2);
|
||||
rs2.getTimestamp(3);
|
||||
rsControl2.setReturnValue(new Timestamp(1221222L), 1);
|
||||
rs2.getBigDecimal(4);
|
||||
rsControl2.setReturnValue(new BigDecimal("1234.56"), 1);
|
||||
rs2.next();
|
||||
rsControl2.setReturnValue(false, 1);
|
||||
rs2.close();
|
||||
rsControl2.setVoidCallable(2);
|
||||
rsControl2.replay();
|
||||
|
||||
stmtControl2 = MockControl.createControl(Statement.class);
|
||||
stmt2 = (Statement) stmtControl2.getMock();
|
||||
|
||||
con2.createStatement();
|
||||
conControl2.setReturnValue(stmt2, 2);
|
||||
stmt2.executeQuery("select name, null as age, birth_date, balance from people");
|
||||
stmtControl2.setReturnValue(rs2, 2);
|
||||
if (debugEnabled) {
|
||||
stmt2.getWarnings();
|
||||
stmtControl2.setReturnValue(null, 2);
|
||||
}
|
||||
stmt2.close();
|
||||
stmtControl2.setVoidCallable(2);
|
||||
|
||||
conControl2.replay();
|
||||
stmtControl2.replay();
|
||||
|
||||
conControl3 = MockControl.createControl(Connection.class);
|
||||
con3 = (Connection) conControl3.getMock();
|
||||
con3.isClosed();
|
||||
conControl3.setDefaultReturnValue(false);
|
||||
|
||||
rsmdControl3 = MockControl.createControl(ResultSetMetaData.class);
|
||||
rsmd3 = (ResultSetMetaData)rsmdControl3.getMock();
|
||||
rsmd3.getColumnCount();
|
||||
rsmdControl3.setReturnValue(4, 1);
|
||||
rsmd3.getColumnLabel(1);
|
||||
rsmdControl3.setReturnValue("Last Name", 1);
|
||||
rsmd3.getColumnLabel(2);
|
||||
rsmdControl3.setReturnValue("age", 1);
|
||||
rsmd3.getColumnLabel(3);
|
||||
rsmdControl3.setReturnValue("birth_date", 1);
|
||||
rsmd3.getColumnLabel(4);
|
||||
rsmdControl3.setReturnValue("balance", 1);
|
||||
rsmdControl3.replay();
|
||||
|
||||
rsControl3 = MockControl.createControl(ResultSet.class);
|
||||
rs3 = (ResultSet) rsControl3.getMock();
|
||||
rs3.getMetaData();
|
||||
rsControl3.setReturnValue(rsmd3, 1);
|
||||
rs3.next();
|
||||
rsControl3.setReturnValue(true, 1);
|
||||
rs3.getString(1);
|
||||
rsControl3.setReturnValue("Gagarin", 1);
|
||||
rs3.wasNull();
|
||||
rsControl3.setReturnValue(false, 1);
|
||||
rs3.getLong(2);
|
||||
rsControl3.setReturnValue(22, 1);
|
||||
rs3.getTimestamp(3);
|
||||
rsControl3.setReturnValue(new Timestamp(1221222L), 1);
|
||||
rs3.getBigDecimal(4);
|
||||
rsControl3.setReturnValue(new BigDecimal("1234.56"), 1);
|
||||
rs3.next();
|
||||
rsControl3.setReturnValue(false, 1);
|
||||
rs3.close();
|
||||
rsControl3.setVoidCallable(1);
|
||||
rsControl3.replay();
|
||||
|
||||
stmtControl3 = MockControl.createControl(Statement.class);
|
||||
stmt3 = (Statement) stmtControl3.getMock();
|
||||
|
||||
con3.createStatement();
|
||||
conControl3.setReturnValue(stmt3, 1);
|
||||
stmt3.executeQuery("select last_name as \"Last Name\", age, birth_date, balance from people");
|
||||
stmtControl3.setReturnValue(rs3, 1);
|
||||
if (debugEnabled) {
|
||||
stmt3.getWarnings();
|
||||
stmtControl3.setReturnValue(null, 1);
|
||||
}
|
||||
stmt3.close();
|
||||
stmtControl3.setVoidCallable(1);
|
||||
|
||||
conControl3.replay();
|
||||
stmtControl3.replay();
|
||||
|
||||
jdbcTemplate = new JdbcTemplate();
|
||||
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
|
||||
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
|
||||
jdbcTemplate.afterPropertiesSet();
|
||||
|
||||
jdbcTemplate2 = new JdbcTemplate();
|
||||
jdbcTemplate2.setDataSource(new SingleConnectionDataSource(con2, false));
|
||||
jdbcTemplate2.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
|
||||
jdbcTemplate2.afterPropertiesSet();
|
||||
|
||||
jdbcTemplate3 = new JdbcTemplate();
|
||||
jdbcTemplate3.setDataSource(new SingleConnectionDataSource(con3, false));
|
||||
jdbcTemplate3.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
|
||||
jdbcTemplate3.afterPropertiesSet();
|
||||
}
|
||||
|
||||
protected void verifyPerson(Person bean) {
|
||||
verify();
|
||||
assertEquals("Bubba", bean.getName());
|
||||
assertEquals(22L, bean.getAge());
|
||||
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
|
||||
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
|
||||
}
|
||||
|
||||
protected void verifyPersonWithZeroAge(Person bean) {
|
||||
conControl2.verify();
|
||||
rsControl2.verify();
|
||||
rsmdControl2.verify();
|
||||
stmtControl2.verify();
|
||||
assertEquals("Bubba", bean.getName());
|
||||
assertEquals(0L, bean.getAge());
|
||||
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
|
||||
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
|
||||
}
|
||||
|
||||
protected void verifyConcretePerson(ConcretePerson bean) {
|
||||
verify();
|
||||
assertEquals("Bubba", bean.getName());
|
||||
assertEquals(22L, bean.getAge());
|
||||
assertEquals(new java.util.Date(1221222L), bean.getBirth_date());
|
||||
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
|
||||
}
|
||||
|
||||
protected void verifySpacePerson(SpacePerson bean) {
|
||||
conControl3.verify();
|
||||
rsControl3.verify();
|
||||
rsmdControl3.verify();
|
||||
stmtControl3.verify();
|
||||
assertEquals("Gagarin", bean.getLastName());
|
||||
assertEquals(22L, bean.getAge());
|
||||
assertEquals(new java.util.Date(1221222L), bean.getBirthDate());
|
||||
assertEquals(new BigDecimal("1234.56"), bean.getBalance());
|
||||
}
|
||||
|
||||
private void verify() {
|
||||
conControl.verify();
|
||||
rsControl.verify();
|
||||
rsmdControl.verify();
|
||||
stmtControl.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package org.springframework.jdbc.core;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public abstract class BatchUpdateTestHelper {
|
||||
|
||||
public static void prepareBatchUpdateMocks(String sqlToUse, Object ids, int[] sqlTypes,
|
||||
int[] rowsAffected,
|
||||
MockControl ctrlDataSource, DataSource mockDataSource, MockControl ctrlConnection, Connection mockConnection,
|
||||
MockControl ctrlPreparedStatement,
|
||||
PreparedStatement mockPreparedStatement, MockControl ctrlDatabaseMetaData, DatabaseMetaData mockDatabaseMetaData)
|
||||
throws SQLException {
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setDefaultReturnValue(null);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setDefaultVoidCallable();
|
||||
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
mockPreparedStatement.getConnection();
|
||||
ctrlPreparedStatement.setReturnValue(mockConnection);
|
||||
int idLength = 0;
|
||||
if (ids instanceof SqlParameterSource[]) {
|
||||
idLength = ((SqlParameterSource[])ids).length;
|
||||
}
|
||||
else if (ids instanceof Map[]) {
|
||||
idLength = ((Map[])ids).length;
|
||||
}
|
||||
else {
|
||||
idLength = ((List)ids).size();
|
||||
}
|
||||
|
||||
for (int i = 0; i < idLength; i++) {
|
||||
if (ids instanceof SqlParameterSource[]) {
|
||||
if (sqlTypes != null) {
|
||||
mockPreparedStatement.setObject(1, ((SqlParameterSource[])ids)[i].getValue("id"), sqlTypes[0]);
|
||||
}
|
||||
else {
|
||||
mockPreparedStatement.setObject(1, ((SqlParameterSource[])ids)[i].getValue("id"));
|
||||
}
|
||||
}
|
||||
else if (ids instanceof Map[]) {
|
||||
if (sqlTypes != null) {
|
||||
mockPreparedStatement.setObject(1, ((Map[])ids)[i].get("id"), sqlTypes[0]);
|
||||
}
|
||||
else {
|
||||
mockPreparedStatement.setObject(1, ((Map[])ids)[i].get("id"));
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (sqlTypes != null) {
|
||||
mockPreparedStatement.setObject(1, ((Object[])((List)ids).get(i))[0], sqlTypes[0]);
|
||||
}
|
||||
else {
|
||||
mockPreparedStatement.setObject(1, ((Object[])((List)ids).get(i))[0]);
|
||||
}
|
||||
}
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.addBatch();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
}
|
||||
mockPreparedStatement.executeBatch();
|
||||
ctrlPreparedStatement.setReturnValue(rowsAffected);
|
||||
if (LogFactory.getLog(JdbcTemplate.class).isDebugEnabled()) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MySQL");
|
||||
mockDatabaseMetaData.supportsBatchUpdates();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(mockDatabaseMetaData, 2);
|
||||
}
|
||||
|
||||
public static void replayBatchUpdateMocks(MockControl ctrlDataSource,
|
||||
MockControl ctrlConnection,
|
||||
MockControl ctrlPreparedStatement,
|
||||
MockControl ctrlDatabaseMetaData) {
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlDataSource.replay();
|
||||
ctrlConnection.replay();
|
||||
}
|
||||
|
||||
public static void verifyBatchUpdateMocks(MockControl ctrlPreparedStatement, MockControl ctrlDatabaseMetaData) {
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.jdbc.core.test.ConcretePerson;
|
||||
import org.springframework.jdbc.core.test.ExtendedPerson;
|
||||
import org.springframework.jdbc.core.test.Person;
|
||||
import org.springframework.jdbc.core.test.SpacePerson;
|
||||
import org.springframework.beans.TypeMismatchException;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class BeanPropertyRowMapperTests extends AbstractRowMapperTests {
|
||||
|
||||
public void testOverridingClassDefinedForMapping() {
|
||||
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
|
||||
try {
|
||||
mapper.setMappedClass(Long.class);
|
||||
fail("Setting new class should have thrown InvalidDataAccessApiUsageException");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
}
|
||||
try {
|
||||
mapper.setMappedClass(Person.class);
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
fail("Setting same class should not have thrown InvalidDataAccessApiUsageException");
|
||||
}
|
||||
}
|
||||
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(Person.class));
|
||||
assertEquals(1, result.size());
|
||||
Person bean = (Person) result.get(0);
|
||||
verifyPerson(bean);
|
||||
}
|
||||
|
||||
public void testMappingWithInheritance() throws SQLException {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(ConcretePerson.class));
|
||||
assertEquals(1, result.size());
|
||||
ConcretePerson bean = (ConcretePerson) result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
}
|
||||
|
||||
public void testMappingWithNoUnpopulatedFieldsFound() throws SQLException {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(ConcretePerson.class, true));
|
||||
assertEquals(1, result.size());
|
||||
ConcretePerson bean = (ConcretePerson) result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
}
|
||||
|
||||
public void testMappingWithUnpopulatedFieldsNotChecked() throws SQLException {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(ExtendedPerson.class));
|
||||
assertEquals(1, result.size());
|
||||
ExtendedPerson bean = (ExtendedPerson) result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
}
|
||||
|
||||
public void testMappingWithUnpopulatedFieldsNotAccepted() throws SQLException {
|
||||
try {
|
||||
List result = jdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(ExtendedPerson.class, true));
|
||||
fail("Should have thrown InvalidDataAccessApiUsageException because of missing field");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testMappingNullValue() throws SQLException {
|
||||
BeanPropertyRowMapper mapper = new BeanPropertyRowMapper(Person.class);
|
||||
try {
|
||||
List result1 = jdbcTemplate2.query("select name, null as age, birth_date, balance from people",
|
||||
mapper);
|
||||
fail("Should have thrown TypeMismatchException because of null value");
|
||||
}
|
||||
catch (TypeMismatchException ex) {
|
||||
// expected
|
||||
}
|
||||
mapper.setPrimitivesDefaultedForNullValue(true);
|
||||
List result2 = jdbcTemplate2.query("select name, null as age, birth_date, balance from people",
|
||||
mapper);
|
||||
assertEquals(1, result2.size());
|
||||
Person bean = (Person) result2.get(0);
|
||||
verifyPersonWithZeroAge(bean);
|
||||
}
|
||||
|
||||
public void testQueryWithSpaceInColumnName() throws SQLException {
|
||||
List result = jdbcTemplate3.query("select last_name as \"Last Name\", age, birth_date, balance from people",
|
||||
new BeanPropertyRowMapper(SpacePerson.class));
|
||||
assertEquals(1, result.size());
|
||||
SpacePerson bean = (SpacePerson) result.get(0);
|
||||
verifySpacePerson(bean);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,983 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.dao.IncorrectResultSizeDataAccessException;
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 19.12.2004
|
||||
*/
|
||||
public class JdbcTemplateQueryTests extends AbstractJdbcTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private MockControl ctrlStatement;
|
||||
private Statement mockStatement;
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
private MockControl ctrlResultSetMetaData;
|
||||
private ResultSetMetaData mockResultSetMetaData;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
ctrlStatement = MockControl.createControl(Statement.class);
|
||||
mockStatement = (Statement) ctrlStatement.getMock();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
|
||||
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlStatement.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlResultSet.replay();
|
||||
ctrlResultSetMetaData.replay();
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
ctrlStatement.verify();
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlResultSet.verify();
|
||||
ctrlResultSetMetaData.verify();
|
||||
}
|
||||
}
|
||||
|
||||
public void testQueryForList() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1, 2);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 2);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData, 2);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(12));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql);
|
||||
assertEquals("All rows returned", 2, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
assertEquals("Second row is Integer", 12, ((Integer)((Map)li.get(1)).get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForListWithEmptyResult() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
|
||||
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
List li = template.queryForList(sql);
|
||||
assertEquals("All rows returned", 0, li.size());
|
||||
}
|
||||
|
||||
public void testQueryForListWithSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForListWithIntegerElement() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(11);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql, Integer.class);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("Element is Integer", 11, ((Integer) li.get(0)).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForMapWithSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
Map map = template.queryForMap(sql);
|
||||
assertEquals("Wow is Integer", 11, ((Integer) map.get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForObjectThrowsIncorrectResultSizeForMoreThanOneRow() throws Exception {
|
||||
String sql = "select pass from t_account where first_name='Alef'";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getString(1);
|
||||
ctrlResultSet.setReturnValue("pass");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSet.getString(1);
|
||||
ctrlResultSet.setReturnValue("pass");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
try {
|
||||
template.queryForObject(sql, String.class);
|
||||
fail("Should have thrown IncorrectResultSizeDataAccessException");
|
||||
}
|
||||
catch (IncorrectResultSizeDataAccessException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithRowMapper() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
Object o = template.queryForObject(sql, new RowMapper() {
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return new Integer(rs.getInt(1));
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithString() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getString(1);
|
||||
ctrlResultSet.setReturnValue("myvalue");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
assertEquals("myvalue", template.queryForObject(sql, String.class));
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithBigInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue("22");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
assertEquals(new BigInteger("22"), template.queryForObject(sql, BigInteger.class));
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithBigDecimal() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getBigDecimal(1);
|
||||
ctrlResultSet.setReturnValue(new BigDecimal(22.5));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
assertEquals(new BigDecimal(22.5), template.queryForObject(sql, BigDecimal.class));
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
assertEquals(new Integer(22), template.queryForObject(sql, Integer.class));
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithIntegerAndNull() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(0);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
assertNull(template.queryForObject(sql, Integer.class));
|
||||
}
|
||||
|
||||
public void testQueryForInt() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
int i = template.queryForInt(sql);
|
||||
assertEquals("Return of an int", 22, i);
|
||||
}
|
||||
|
||||
public void testQueryForLong() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getLong(1);
|
||||
ctrlResultSet.setReturnValue(87);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockStatement.executeQuery(sql);
|
||||
ctrlStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockStatement.getWarnings();
|
||||
ctrlStatement.setReturnValue(null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
long l = template.queryForLong(sql);
|
||||
assertEquals("Return of a long", 87, l);
|
||||
}
|
||||
|
||||
public void testQueryForListWithArgs() throws Exception {
|
||||
doTestQueryForListWithArgs("SELECT AGE FROM CUSTMR WHERE ID < ?");
|
||||
}
|
||||
|
||||
public void testQueryForListIsNotConfusedByNamedParameterPrefix() throws Exception {
|
||||
doTestQueryForListWithArgs("SELECT AGE FROM PREFIX:CUSTMR WHERE ID < ?");
|
||||
}
|
||||
|
||||
private void doTestQueryForListWithArgs(String sql) throws Exception {
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1, 2);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 2);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData, 2);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(12));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql, new Object[] {new Integer(3)});
|
||||
assertEquals("All rows returned", 2, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
assertEquals("Second row is Integer", 12, ((Integer)((Map)li.get(1)).get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForListWithArgsAndEmptyResult() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql, new Object[] {new Integer(3)});
|
||||
assertEquals("All rows returned", 0, li.size());
|
||||
}
|
||||
|
||||
public void testQueryForListWithArgsAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql, new Object[] {new Integer(3)});
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForListWithArgsAndIntegerElementAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(11);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
List li = template.queryForList(sql, new Object[] {new Integer(3)}, Integer.class);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer) li.get(0)).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForMapWithArgsAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
Map map = template.queryForMap(sql, new Object[] {new Integer(3)});
|
||||
assertEquals("Row is Integer", 11, ((Integer) map.get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithArgsAndRowMapper() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
Object o = template.queryForObject(sql, new Object[] {new Integer(3)}, new RowMapper() {
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return new Integer(rs.getInt(1));
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithArgsAndInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
|
||||
Object o = template.queryForObject(sql, new Object[] {new Integer(3)}, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForIntWithArgs() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
int i = template.queryForInt(sql, new Object[] {new Integer(3)});
|
||||
assertEquals("Return of an int", 22, i);
|
||||
}
|
||||
|
||||
public void testQueryForLongWithArgs() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getLong(1);
|
||||
ctrlResultSet.setReturnValue(87);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource);
|
||||
long l = template.queryForLong(sql, new Object[] {new Integer(3)});
|
||||
assertEquals("Return of a long", 87, l);
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,248 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.util.List;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
|
||||
import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 02.08.2004
|
||||
*/
|
||||
public class RowMapperTests extends TestCase {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private MockControl conControl;
|
||||
private Connection con;
|
||||
private MockControl rsControl;
|
||||
private ResultSet rs;
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private List result;
|
||||
|
||||
protected void setUp() throws SQLException {
|
||||
conControl = MockControl.createControl(Connection.class);
|
||||
con = (Connection) conControl.getMock();
|
||||
con.isClosed();
|
||||
conControl.setDefaultReturnValue(false);
|
||||
|
||||
rsControl = MockControl.createControl(ResultSet.class);
|
||||
rs = (ResultSet) rsControl.getMock();
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 1);
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue("tb1", 1);
|
||||
rs.getInt(2);
|
||||
rsControl.setReturnValue(1, 1);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 1);
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue("tb2", 1);
|
||||
rs.getInt(2);
|
||||
rsControl.setReturnValue(2, 1);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(false, 1);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(1);
|
||||
rsControl.replay();
|
||||
|
||||
jdbcTemplate = new JdbcTemplate();
|
||||
jdbcTemplate.setDataSource(new SingleConnectionDataSource(con, false));
|
||||
jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
|
||||
jdbcTemplate.afterPropertiesSet();
|
||||
}
|
||||
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 1);
|
||||
stmt.executeQuery("some SQL");
|
||||
stmtControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
stmt.getWarnings();
|
||||
stmtControl.setReturnValue(null, 1);
|
||||
}
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
|
||||
result = jdbcTemplate.query("some SQL", new TestRowMapper());
|
||||
|
||||
stmtControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testPreparedStatementCreatorWithRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
new PreparedStatementCreator() {
|
||||
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
|
||||
return ps;
|
||||
}
|
||||
}, new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testPreparedStatementSetterWithRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
con.prepareStatement("some SQL");
|
||||
conControl.setReturnValue(ps, 1);
|
||||
ps.setString(1, "test");
|
||||
psControl.setVoidCallable(1);
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
"some SQL",
|
||||
new PreparedStatementSetter() {
|
||||
public void setValues(PreparedStatement ps) throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
}
|
||||
}, new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testQueryWithArgsAndRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
con.prepareStatement("some SQL");
|
||||
conControl.setReturnValue(ps, 1);
|
||||
ps.setString(1, "test1");
|
||||
ps.setString(2, "test2");
|
||||
psControl.setVoidCallable(1);
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
"some SQL",
|
||||
new Object[] {"test1", "test2"},
|
||||
new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
public void testQueryWithArgsAndTypesAndRowMapper() throws SQLException {
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
final PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
con.prepareStatement("some SQL");
|
||||
conControl.setReturnValue(ps, 1);
|
||||
ps.setString(1, "test1");
|
||||
ps.setString(2, "test2");
|
||||
psControl.setVoidCallable(1);
|
||||
ps.executeQuery();
|
||||
psControl.setReturnValue(rs, 1);
|
||||
if (debugEnabled) {
|
||||
ps.getWarnings();
|
||||
psControl.setReturnValue(null, 1);
|
||||
}
|
||||
ps.close();
|
||||
psControl.setVoidCallable(1);
|
||||
|
||||
conControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
result = jdbcTemplate.query(
|
||||
"some SQL",
|
||||
new Object[] {"test1", "test2"},
|
||||
new int[] {Types.VARCHAR, Types.VARCHAR},
|
||||
new TestRowMapper());
|
||||
|
||||
psControl.verify();
|
||||
verify();
|
||||
}
|
||||
|
||||
protected void verify() {
|
||||
conControl.verify();
|
||||
rsControl.verify();
|
||||
|
||||
assertTrue(result != null);
|
||||
assertEquals(2, result.size());
|
||||
TestBean tb1 = (TestBean) result.get(0);
|
||||
TestBean tb2 = (TestBean) result.get(1);
|
||||
assertEquals("tb1", tb1.getName());
|
||||
assertEquals(1, tb1.getAge());
|
||||
assertEquals("tb2", tb2.getName());
|
||||
assertEquals(2, tb2.getAge());
|
||||
}
|
||||
|
||||
|
||||
private static class TestRowMapper implements RowMapper {
|
||||
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return new TestBean(rs.getString(1), rs.getInt(2));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.jdbc.core;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Simple row count callback handler for testing purposes.
|
||||
* Does not call any JDBC methods on the given ResultSet.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.0
|
||||
*/
|
||||
public class SimpleRowCountCallbackHandler implements RowCallbackHandler {
|
||||
|
||||
private int count;
|
||||
|
||||
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
count++;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 31.08.2004
|
||||
*/
|
||||
public class StatementCreatorUtilsTests extends TestCase {
|
||||
|
||||
private MockControl psControl;
|
||||
private PreparedStatement ps;
|
||||
|
||||
protected void setUp() {
|
||||
psControl = MockControl.createControl(PreparedStatement.class);
|
||||
ps = (PreparedStatement) psControl.getMock();
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndType() throws SQLException {
|
||||
ps.setNull(1, Types.VARCHAR);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, null, null);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndTypeName() throws SQLException {
|
||||
ps.setNull(1, Types.VARCHAR, "mytype");
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, "mytype", null);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndUnknownType() throws SQLException {
|
||||
ps.setNull(1, Types.NULL);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndUnknownTypeOnInformix() throws SQLException {
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl metaDataControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData metaData = (DatabaseMetaData) metaDataControl.getMock();
|
||||
ps.getConnection();
|
||||
psControl.setReturnValue(con, 1);
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(metaData, 1);
|
||||
metaData.getDatabaseProductName();
|
||||
metaDataControl.setReturnValue("Informix Dynamic Server");
|
||||
metaData.getDriverName();
|
||||
metaDataControl.setReturnValue("Informix Driver");
|
||||
ps.setObject(1, null);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
conControl.replay();
|
||||
metaDataControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
conControl.verify();
|
||||
metaDataControl.verify();
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithNullAndUnknownTypeOnDerbyEmbedded() throws SQLException {
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl metaDataControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData metaData = (DatabaseMetaData) metaDataControl.getMock();
|
||||
ps.getConnection();
|
||||
psControl.setReturnValue(con, 1);
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(metaData, 1);
|
||||
metaData.getDatabaseProductName();
|
||||
metaDataControl.setReturnValue("Apache Derby");
|
||||
metaData.getDriverName();
|
||||
metaDataControl.setReturnValue("Apache Derby Embedded Driver");
|
||||
ps.setNull(1, Types.VARCHAR);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
conControl.replay();
|
||||
metaDataControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, null);
|
||||
conControl.verify();
|
||||
metaDataControl.verify();
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithString() throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.VARCHAR, null, "test");
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithStringAndSpecialType() throws SQLException {
|
||||
ps.setObject(1, "test", Types.CHAR);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.CHAR, null, "test");
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithStringAndUnknownType() throws SQLException {
|
||||
ps.setString(1, "test");
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, "test");
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithSqlDate() throws SQLException {
|
||||
java.sql.Date date = new java.sql.Date(1000);
|
||||
ps.setDate(1, date);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, date);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithDateAndUtilDate() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setDate(1, new java.sql.Date(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, date);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithDateAndCalendar() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.DATE, null, cal);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithSqlTime() throws SQLException {
|
||||
java.sql.Time time = new java.sql.Time(1000);
|
||||
ps.setTime(1, time);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, time);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithTimeAndUtilDate() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setTime(1, new java.sql.Time(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, date);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithTimeAndCalendar() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setTime(1, new java.sql.Time(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIME, null, cal);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithSqlTimestamp() throws SQLException {
|
||||
java.sql.Timestamp timestamp = new java.sql.Timestamp(1000);
|
||||
ps.setTimestamp(1, timestamp);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, timestamp);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithTimestampAndUtilDate() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, date);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithTimestampAndCalendar() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, Types.TIMESTAMP, null, cal);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithDateAndUnknownType() throws SQLException {
|
||||
java.util.Date date = new java.util.Date(1000);
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(1000));
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, date);
|
||||
}
|
||||
|
||||
public void testSetParameterValueWithCalendarAndUnknownType() throws SQLException {
|
||||
java.util.Calendar cal = new GregorianCalendar();
|
||||
ps.setTimestamp(1, new java.sql.Timestamp(cal.getTime().getTime()), cal);
|
||||
psControl.setVoidCallable(1);
|
||||
psControl.replay();
|
||||
StatementCreatorUtils.setParameterValue(ps, 1, SqlTypeValue.TYPE_UNKNOWN, null, cal);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.namedparam;
|
||||
|
||||
import java.sql.Types;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Juergen Hoeller
|
||||
* @author Arjen Poutsma
|
||||
*/
|
||||
public class BeanPropertySqlParameterSourceTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void withNullBeanPassedToCtor() throws Exception {
|
||||
new BeanPropertySqlParameterSource(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void getValueWhereTheUnderlyingBeanHasNoSuchProperty() throws Exception {
|
||||
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean());
|
||||
source.getValue("thisPropertyDoesNotExist");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulPropertyAccess() {
|
||||
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
|
||||
assertTrue(Arrays.asList(source.getReadablePropertyNames()).contains("name"));
|
||||
assertTrue(Arrays.asList(source.getReadablePropertyNames()).contains("age"));
|
||||
assertEquals("tb", source.getValue("name"));
|
||||
assertEquals(99, source.getValue("age"));
|
||||
assertEquals(Types.VARCHAR, source.getSqlType("name"));
|
||||
assertEquals(Types.INTEGER, source.getSqlType("age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulPropertyAccessWithOverriddenSqlType() {
|
||||
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean("tb", 99));
|
||||
source.registerSqlType("age", Types.NUMERIC);
|
||||
assertEquals("tb", source.getValue("name"));
|
||||
assertEquals(99, source.getValue("age"));
|
||||
assertEquals(Types.VARCHAR, source.getSqlType("name"));
|
||||
assertEquals(Types.NUMERIC, source.getSqlType("age"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasValueWhereTheUnderlyingBeanHasNoSuchProperty() throws Exception {
|
||||
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new TestBean());
|
||||
assertFalse(source.hasValue("thisPropertyDoesNotExist"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void getValueWhereTheUnderlyingBeanPropertyIsNotReadable() throws Exception {
|
||||
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties());
|
||||
source.getValue("noOp");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hasValueWhereTheUnderlyingBeanPropertyIsNotReadable() throws Exception {
|
||||
BeanPropertySqlParameterSource source = new BeanPropertySqlParameterSource(new NoReadableProperties());
|
||||
assertFalse(source.hasValue("noOp"));
|
||||
}
|
||||
|
||||
private static final class NoReadableProperties {
|
||||
|
||||
public void setNoOp(String noOp) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.jdbc.core.namedparam;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.jdbc.core.SqlParameterValue;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Arjen Poutsma
|
||||
*/
|
||||
public final class MapSqlParameterSourceTests {
|
||||
|
||||
@Test
|
||||
public void nullParameterValuesPassedToCtorIsOk() throws Exception {
|
||||
new MapSqlParameterSource(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void getValueChokesIfParameterIsNotPresent() throws Exception {
|
||||
MapSqlParameterSource source = new MapSqlParameterSource();
|
||||
source.getValue("pechorin was right!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sqlParameterValueRegistersSqlType() throws Exception {
|
||||
MapSqlParameterSource msps = new MapSqlParameterSource("FOO", new SqlParameterValue(2, "Foo"));
|
||||
assertEquals("Correct SQL Type not registered", 2, msps.getSqlType("FOO"));
|
||||
MapSqlParameterSource msps2 = new MapSqlParameterSource();
|
||||
msps2.addValues(msps.getValues());
|
||||
assertEquals("Correct SQL Type not registered", 2, msps2.getSqlType("FOO"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.namedparam;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.Customer;
|
||||
import org.springframework.jdbc.core.JdbcOperations;
|
||||
import org.springframework.jdbc.core.PreparedStatementCallback;
|
||||
import org.springframework.jdbc.core.ResultSetExtractor;
|
||||
import org.springframework.jdbc.core.RowCallbackHandler;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.jdbc.core.SqlParameterValue;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.BatchUpdateTestHelper;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public class NamedParameterJdbcTemplateTests extends AbstractJdbcTests {
|
||||
|
||||
private static final String SELECT_NAMED_PARAMETERS =
|
||||
"select id, forename from custmr where id = :id and country = :country";
|
||||
private static final String SELECT_NAMED_PARAMETERS_PARSED =
|
||||
"select id, forename from custmr where id = ? and country = ?";
|
||||
|
||||
private static final String UPDATE_NAMED_PARAMETERS =
|
||||
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
|
||||
private static final String UPDATE_NAMED_PARAMETERS_PARSED =
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
|
||||
|
||||
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlResultSet.replay();
|
||||
}
|
||||
|
||||
|
||||
public void testNullDataSourceProvidedToCtor() throws Exception {
|
||||
try {
|
||||
new NamedParameterJdbcTemplate((DataSource) null);
|
||||
fail("should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException ex) { /* expected */ }
|
||||
}
|
||||
|
||||
public void testNullJdbcTemplateProvidedToCtor() throws Exception {
|
||||
try {
|
||||
new NamedParameterJdbcTemplate((JdbcOperations) null);
|
||||
fail("should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException ex) { /* expected */ }
|
||||
}
|
||||
|
||||
public void testExecute() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new Integer(1));
|
||||
params.put("priceId", new Integer(1));
|
||||
assertEquals("result", jt.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback() {
|
||||
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
|
||||
assertEquals(mockPreparedStatement, ps);
|
||||
ps.executeUpdate();
|
||||
return "result";
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public void testExecuteWithTypedParameters() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1)));
|
||||
assertEquals("result", jt.execute(UPDATE_NAMED_PARAMETERS, params, new PreparedStatementCallback() {
|
||||
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
|
||||
assertEquals(mockPreparedStatement, ps);
|
||||
ps.executeUpdate();
|
||||
return "result";
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
public void testUpdate() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new Integer(1));
|
||||
params.put("priceId", new Integer(1));
|
||||
int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUpdateWithTypedParameters() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("priceId", new SqlParameterValue(Types.INTEGER, new Integer(1)));
|
||||
int rowsAffected = jt.update(UPDATE_NAMED_PARAMETERS, params);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testQueryWithResultSetExtractor() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("country", "UK");
|
||||
Customer cust = (Customer) jt.query(SELECT_NAMED_PARAMETERS, params, new ResultSetExtractor() {
|
||||
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
|
||||
rs.next();
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
}
|
||||
|
||||
public void testQueryWithRowCallbackHandler() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("country", "UK");
|
||||
final List customers = new LinkedList();
|
||||
jt.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
customers.add(cust);
|
||||
}
|
||||
});
|
||||
assertEquals(1, customers.size());
|
||||
Customer cust = (Customer) customers.get(0);
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
}
|
||||
|
||||
public void testQueryWithRowMapper() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("country", "UK");
|
||||
List customers = jt.query(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
|
||||
public Object mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
assertEquals(1, customers.size());
|
||||
Customer cust = (Customer) customers.get(0);
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithRowMapper() throws SQLException {
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt("id");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
mockResultSet.getString("forename");
|
||||
ctrlResultSet.setReturnValue("rod");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
Map params = new HashMap();
|
||||
params.put("id", new SqlParameterValue(Types.DECIMAL, new Integer(1)));
|
||||
params.put("country", "UK");
|
||||
Customer cust = (Customer) jt.queryForObject(SELECT_NAMED_PARAMETERS, params, new RowMapper() {
|
||||
public Object mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
});
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithPlainMap() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final Map[] ids = new Map[2];
|
||||
ids[0] = Collections.singletonMap("id", 100);
|
||||
ids[1] = Collections.singletonMap("id", 200);
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithSqlParameterSource() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final SqlParameterSource[] ids = new SqlParameterSource[2];
|
||||
ids[0] = new MapSqlParameterSource("id", 100);
|
||||
ids[1] = new MapSqlParameterSource("id", 200);
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithSqlParameterSourcePlusTypeInfo() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final SqlParameterSource[] ids = new SqlParameterSource[2];
|
||||
ids[0] = new MapSqlParameterSource().addValue("id", 100, Types.NUMERIC);
|
||||
ids[1] = new MapSqlParameterSource().addValue("id", 200, Types.NUMERIC);
|
||||
final int[] sqlTypes = new int[] {Types.NUMERIC};
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, sqlTypes, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = namedParameterJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.namedparam;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class NamedParameterQueryTests extends AbstractJdbcTests {
|
||||
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
private MockControl ctrlResultSetMetaData;
|
||||
private ResultSetMetaData mockResultSetMetaData;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
|
||||
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlResultSet.replay();
|
||||
ctrlResultSetMetaData.replay();
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (false && shouldVerify()) {
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlResultSet.verify();
|
||||
ctrlResultSetMetaData.verify();
|
||||
}
|
||||
}
|
||||
|
||||
public void testQueryForListWithParamMap() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1, 2);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 2);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData, 2);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(12));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
List li = template.queryForList(sql, parms);
|
||||
assertEquals("All rows returned", 2, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
assertEquals("Second row is Integer", 12, ((Integer)((Map)li.get(1)).get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForListWithParamMapAndEmptyResult() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
List li = template.queryForList(sql, parms);
|
||||
assertEquals("All rows returned", 0, li.size());
|
||||
}
|
||||
|
||||
public void testQueryForListWithParamMapAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
List li = template.queryForList(sql, parms);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer)((Map)li.get(0)).get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForListWithParamMapAndIntegerElementAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(11);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
List li = template.queryForList(sql, parms, Integer.class);
|
||||
assertEquals("All rows returned", 1, li.size());
|
||||
assertEquals("First row is Integer", 11, ((Integer) li.get(0)).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForMapWithParamMapAndSingleRowAndColumn() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID < :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID < ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("age", 1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
Map map = template.queryForMap(sql, parms);
|
||||
assertEquals("Row is Integer", 11, ((Integer) map.get("age")).intValue());
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithParamMapAndRowMapper() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
Object o = template.queryForObject(sql, parms, new RowMapper() {
|
||||
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
return new Integer(rs.getInt(1));
|
||||
}
|
||||
});
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithMapAndInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
Map parms = new HashMap();
|
||||
parms.put("id", new Integer(3));
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithParamMapAndInteger() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithParamMapAndList() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID IN (:ids)";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID IN (?, ?)";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(2, new Integer(4));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("ids", Arrays.asList(new Object[] {new Integer(3), new Integer(4)}));
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithParamMapAndListOfExpressionLists() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN (:multiExpressionList)";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE (ID, NAME) IN ((?, ?), (?, ?))";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(2, "Rod");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(3, new Integer(4));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setString(4, "Juergen");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
List l1 = new ArrayList();
|
||||
l1.add(new Object[] {new Integer(3), "Rod"});
|
||||
l1.add(new Object[] {new Integer(4), "Juergen"});
|
||||
parms.addValue("multiExpressionList", l1);
|
||||
|
||||
Object o = template.queryForObject(sql, parms, Integer.class);
|
||||
assertTrue("Correct result type", o instanceof Integer);
|
||||
}
|
||||
|
||||
public void testQueryForIntWithParamMap() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getInt(1);
|
||||
ctrlResultSet.setReturnValue(22.0d);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3));
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
|
||||
MapSqlParameterSource parms = new MapSqlParameterSource();
|
||||
parms.addValue("id", new Integer(3));
|
||||
|
||||
int i = template.queryForInt(sql, parms);
|
||||
assertEquals("Return of an int", 22, i);
|
||||
}
|
||||
|
||||
public void testQueryForLongWithParamBean() throws Exception {
|
||||
String sql = "SELECT AGE FROM CUSTMR WHERE ID = :id";
|
||||
String sqlToUse = "SELECT AGE FROM CUSTMR WHERE ID = ?";
|
||||
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getLong(1);
|
||||
ctrlResultSet.setReturnValue(87.0d);
|
||||
mockResultSet.wasNull();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(3), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeQuery();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(sqlToUse);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(mockDataSource);
|
||||
BeanPropertySqlParameterSource parms = new BeanPropertySqlParameterSource(new ParameterBean(3));
|
||||
|
||||
long l = template.queryForLong(sql, parms);
|
||||
assertEquals("Return of a long", 87, l);
|
||||
}
|
||||
|
||||
|
||||
private static class ParameterBean {
|
||||
|
||||
private int id;
|
||||
|
||||
public ParameterBean(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.jdbc.core.namedparam;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
*/
|
||||
public class NamedParameterUtilsTests {
|
||||
|
||||
@Test
|
||||
public void parseSql() {
|
||||
String sql = "xxx :a yyyy :b :c :a zzzzz";
|
||||
ParsedSql psql = NamedParameterUtils.parseSqlStatement(sql);
|
||||
assertEquals("xxx ? yyyy ? ? ? zzzzz", NamedParameterUtils.substituteNamedParameters(psql, null));
|
||||
assertEquals("a", psql.getParameterNames().get(0));
|
||||
assertEquals("c", psql.getParameterNames().get(2));
|
||||
assertEquals("a", psql.getParameterNames().get(3));
|
||||
assertEquals(4, psql.getTotalParameterCount());
|
||||
assertEquals(3, psql.getNamedParameterCount());
|
||||
|
||||
String sql2 = "xxx &a yyyy ? zzzzz";
|
||||
ParsedSql psql2 = NamedParameterUtils.parseSqlStatement(sql2);
|
||||
assertEquals("xxx ? yyyy ? zzzzz", NamedParameterUtils.substituteNamedParameters(psql2, null));
|
||||
assertEquals("a", psql2.getParameterNames().get(0));
|
||||
assertEquals(2, psql2.getTotalParameterCount());
|
||||
assertEquals(1, psql2.getNamedParameterCount());
|
||||
|
||||
String sql3 = "xxx &a+:b" + '\t' + ":c%10 yyyy ? zzzzz";
|
||||
ParsedSql psql3 = NamedParameterUtils.parseSqlStatement(sql3);
|
||||
assertEquals("a", psql3.getParameterNames().get(0));
|
||||
assertEquals("b", psql3.getParameterNames().get(1));
|
||||
assertEquals("c", psql3.getParameterNames().get(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void substituteNamedParameters() {
|
||||
MapSqlParameterSource namedParams = new MapSqlParameterSource();
|
||||
namedParams.addValue("a", "a").addValue("b", "b").addValue("c", "c");
|
||||
assertEquals("xxx ? ? ?", NamedParameterUtils.substituteNamedParameters("xxx :a :b :c", namedParams));
|
||||
assertEquals("xxx ? ? ? xx ? ?",
|
||||
NamedParameterUtils.substituteNamedParameters("xxx :a :b :c xx :a :a", namedParams));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertParamMapToArray() {
|
||||
Map<String, String> paramMap = new HashMap<String, String>();
|
||||
paramMap.put("a", "a");
|
||||
paramMap.put("b", "b");
|
||||
paramMap.put("c", "c");
|
||||
assertSame(3, NamedParameterUtils.buildValueArray("xxx :a :b :c", paramMap).length);
|
||||
assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap).length);
|
||||
assertSame(5, NamedParameterUtils.buildValueArray("xxx :a :a :a xx :a :a", paramMap).length);
|
||||
assertEquals("b", NamedParameterUtils.buildValueArray("xxx :a :b :c xx :a :b", paramMap)[4]);
|
||||
try {
|
||||
NamedParameterUtils.buildValueArray("xxx :a :b ?", paramMap);
|
||||
fail("mixed named parameters and ? placeholders not detected");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertTypeMapToArray() {
|
||||
MapSqlParameterSource namedParams = new MapSqlParameterSource();
|
||||
namedParams.addValue("a", "a", 1).addValue("b", "b", 2).addValue("c", "c", 3);
|
||||
assertSame(3, NamedParameterUtils
|
||||
.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).length);
|
||||
assertSame(5, NamedParameterUtils
|
||||
.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).length);
|
||||
assertSame(5, NamedParameterUtils
|
||||
.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).length);
|
||||
assertEquals(2, NamedParameterUtils
|
||||
.buildSqlTypeArray(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams)[4]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertTypeMapToSqlParameterList() {
|
||||
MapSqlParameterSource namedParams = new MapSqlParameterSource();
|
||||
namedParams.addValue("a", "a", 1).addValue("b", "b", 2).addValue("c", "c", 3, "SQL_TYPE");
|
||||
assertSame(3, NamedParameterUtils
|
||||
.buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).size());
|
||||
assertSame(5, NamedParameterUtils
|
||||
.buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).size());
|
||||
assertSame(5, NamedParameterUtils
|
||||
.buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :a :a xx :a :a"), namedParams).size());
|
||||
assertEquals(2, NamedParameterUtils
|
||||
.buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c xx :a :b"), namedParams).get(4).getSqlType());
|
||||
assertEquals("SQL_TYPE", NamedParameterUtils
|
||||
.buildSqlParameterList(NamedParameterUtils.parseSqlStatement("xxx :a :b :c"), namedParams).get(2).getTypeName());
|
||||
}
|
||||
|
||||
@Test(expected = InvalidDataAccessApiUsageException.class)
|
||||
public void buildValueArrayWithMissingParameterValue() throws Exception {
|
||||
String sql = "select count(0) from foo where id = :id";
|
||||
NamedParameterUtils.buildValueArray(sql, new HashMap());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void substituteNamedParametersWithStringContainingQuotes() throws Exception {
|
||||
String expectedSql = "select 'first name' from artists where id = ? and quote = 'exsqueeze me?'";
|
||||
String sql = "select 'first name' from artists where id = :id and quote = 'exsqueeze me?'";
|
||||
String newSql = NamedParameterUtils.substituteNamedParameters(sql, new MapSqlParameterSource());
|
||||
assertEquals(expectedSql, newSql);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseSqlStatementWithStringContainingQuotes() throws Exception {
|
||||
String expectedSql = "select 'first name' from artists where id = ? and quote = 'exsqueeze me?'";
|
||||
String sql = "select 'first name' from artists where id = :id and quote = 'exsqueeze me?'";
|
||||
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
|
||||
assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null));
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-4789
|
||||
*/
|
||||
@Test
|
||||
public void parseSqlContainingComments() {
|
||||
String sql1 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz -- :xx XX\n";
|
||||
ParsedSql psql1 = NamedParameterUtils.parseSqlStatement(sql1);
|
||||
assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX\n",
|
||||
NamedParameterUtils.substituteNamedParameters(psql1, null));
|
||||
MapSqlParameterSource paramMap = new MapSqlParameterSource();
|
||||
paramMap.addValue("a", "a");
|
||||
paramMap.addValue("b", "b");
|
||||
paramMap.addValue("c", "c");
|
||||
Object[] params = NamedParameterUtils.buildValueArray(psql1, paramMap, null);
|
||||
assertEquals(4, params.length);
|
||||
assertEquals("a", params[0]);
|
||||
assertEquals("b", params[1]);
|
||||
assertEquals("c", params[2]);
|
||||
assertEquals("a", params[3]);
|
||||
|
||||
String sql2 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz -- :xx XX";
|
||||
ParsedSql psql2 = NamedParameterUtils.parseSqlStatement(sql2);
|
||||
assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz -- :xx XX",
|
||||
NamedParameterUtils.substituteNamedParameters(psql2, null));
|
||||
|
||||
String sql3 = "/*+ HINT */ xxx /* comment ? */ :a yyyy :b :c :a zzzzz /* :xx XX*";
|
||||
ParsedSql psql3 = NamedParameterUtils.parseSqlStatement(sql3);
|
||||
assertEquals("/*+ HINT */ xxx /* comment ? */ ? yyyy ? ? ? zzzzz /* :xx XX*",
|
||||
NamedParameterUtils.substituteNamedParameters(psql3, null));
|
||||
|
||||
String sql4 = "/*+ HINT */ xxx /* comment :a ? */ :a yyyy :b :c :a zzzzz /* :xx XX*";
|
||||
ParsedSql psql4 = NamedParameterUtils.parseSqlStatement(sql4);
|
||||
Map parameters = Collections.singletonMap("a", "0");
|
||||
assertEquals("/*+ HINT */ xxx /* comment :a ? */ ? yyyy ? ? ? zzzzz /* :xx XX*",
|
||||
NamedParameterUtils.substituteNamedParameters(psql4, new MapSqlParameterSource(parameters)));
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-4612
|
||||
*/
|
||||
@Test
|
||||
public void parseSqlStatementWithPostgresCasting() throws Exception {
|
||||
String expectedSql = "select 'first name' from artists where id = ? and birth_date=?::timestamp";
|
||||
String sql = "select 'first name' from artists where id = :id and birth_date=:birthDate::timestamp";
|
||||
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
|
||||
assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null));
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-7476
|
||||
*/
|
||||
@Test
|
||||
public void parseSqlStatementWithEscapedColon() throws Exception {
|
||||
String expectedSql = "select '0\\:0' as a, foo from bar where baz < DATE(? 23:59:59) and baz = ?";
|
||||
String sql = "select '0\\:0' as a, foo from bar where baz < DATE(:p1 23\\:59\\:59) and baz = :p2";
|
||||
|
||||
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
|
||||
assertEquals(2, parsedSql.getParameterNames().size());
|
||||
assertEquals("p1", parsedSql.getParameterNames().get(0));
|
||||
assertEquals("p2", parsedSql.getParameterNames().get(1));
|
||||
String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null);
|
||||
assertEquals(expectedSql, finalSql);
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-7476
|
||||
*/
|
||||
@Test
|
||||
public void parseSqlStatementWithBracketDelimitedParameterNames() throws Exception {
|
||||
String expectedSql = "select foo from bar where baz = b??z";
|
||||
String sql = "select foo from bar where baz = b:{p1}:{p2}z";
|
||||
|
||||
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
|
||||
assertEquals(2, parsedSql.getParameterNames().size());
|
||||
assertEquals("p1", parsedSql.getParameterNames().get(0));
|
||||
assertEquals("p2", parsedSql.getParameterNames().get(1));
|
||||
String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null);
|
||||
assertEquals(expectedSql, finalSql);
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-7476
|
||||
*/
|
||||
@Test
|
||||
public void parseSqlStatementWithEmptyBracketsOrBracketsInQuotes() throws Exception {
|
||||
String expectedSql = "select foo from bar where baz = b:{}z";
|
||||
String sql = "select foo from bar where baz = b:{}z";
|
||||
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
|
||||
assertEquals(0, parsedSql.getParameterNames().size());
|
||||
String finalSql = NamedParameterUtils.substituteNamedParameters(parsedSql, null);
|
||||
assertEquals(expectedSql, finalSql);
|
||||
|
||||
String expectedSql2 = "select foo from bar where baz = 'b:{p1}z'";
|
||||
String sql2 = "select foo from bar where baz = 'b:{p1}z'";
|
||||
|
||||
ParsedSql parsedSql2 = NamedParameterUtils.parseSqlStatement(sql2);
|
||||
assertEquals(0, parsedSql2.getParameterNames().size());
|
||||
String finalSql2 = NamedParameterUtils.substituteNamedParameters(parsedSql2, null);
|
||||
assertEquals(expectedSql2, finalSql2);
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-2544
|
||||
*/
|
||||
@Test
|
||||
public void parseSqlStatementWithLogicalAnd() {
|
||||
String expectedSql = "xxx & yyyy";
|
||||
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(expectedSql);
|
||||
assertEquals(expectedSql, NamedParameterUtils.substituteNamedParameters(parsedSql, null));
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-2544
|
||||
*/
|
||||
@Test
|
||||
public void substituteNamedParametersWithLogicalAnd() throws Exception {
|
||||
String expectedSql = "xxx & yyyy";
|
||||
String newSql = NamedParameterUtils.substituteNamedParameters(expectedSql, new MapSqlParameterSource());
|
||||
assertEquals(expectedSql, newSql);
|
||||
}
|
||||
|
||||
/*
|
||||
* SPR-3173
|
||||
*/
|
||||
@Test
|
||||
public void variableAssignmentOperator() throws Exception {
|
||||
String expectedSql = "x := 1";
|
||||
String newSql = NamedParameterUtils.substituteNamedParameters(expectedSql, new MapSqlParameterSource());
|
||||
assertEquals(expectedSql, newSql);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.springframework.jdbc.core.metadata.CallMetaDataContext;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.SqlOutParameter;
|
||||
import org.springframework.jdbc.core.SqlInOutParameter;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Mock object based tests for CallMetaDataContext.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class CallMetaDataContextTests extends TestCase {
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
|
||||
private CallMetaDataContext context = new CallMetaDataContext();
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
ctrlConnection = MockControl.createControl(Connection.class);
|
||||
mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setDefaultVoidCallable();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
}
|
||||
|
||||
public void testMatchParameterValuesAndSqlInOutParameters() throws Exception {
|
||||
final String TABLE = "customers";
|
||||
final String USER = "me";
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
replay();
|
||||
|
||||
List<SqlParameter> parameters = new ArrayList<SqlParameter>();
|
||||
parameters.add(new SqlParameter("id", Types.NUMERIC));
|
||||
parameters.add(new SqlInOutParameter("name", Types.NUMERIC));
|
||||
parameters.add(new SqlOutParameter("customer_no", Types.NUMERIC));
|
||||
|
||||
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
|
||||
parameterSource.addValue("id", 1);
|
||||
parameterSource.addValue("name", "Sven");
|
||||
parameterSource.addValue("customer_no", "12345XYZ");
|
||||
|
||||
context.setProcedureName(TABLE);
|
||||
context.initializeMetaData(mockDataSource);
|
||||
context.processParameters(parameters);
|
||||
|
||||
Map<String, Object> inParameters = context.matchInParameterValuesWithCallParameters(parameterSource);
|
||||
assertEquals("Wrong number of matched in parameter values", 2, inParameters.size());
|
||||
assertTrue("in parameter value missing", inParameters.containsKey("id"));
|
||||
assertTrue("in out parameter value missing", inParameters.containsKey("name"));
|
||||
assertTrue("out parameter value matched", !inParameters.containsKey("customer_no"));
|
||||
|
||||
List<String> names = context.getOutParameterNames();
|
||||
assertEquals("Wrong number of out parameters", 2, names.size());
|
||||
|
||||
List<SqlParameter> callParameters = context.getCallParameters();
|
||||
assertEquals("Wrong number of call parameters", 3, callParameters.size());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.simple;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.jdbc.core.AbstractRowMapperTests;
|
||||
import org.springframework.jdbc.core.test.ConcretePerson;
|
||||
import org.springframework.jdbc.core.test.Person;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class ParameterizedBeanPropertyRowMapperTests extends AbstractRowMapperTests {
|
||||
|
||||
private SimpleJdbcTemplate simpleJdbcTemplate;
|
||||
|
||||
protected void setUp() throws SQLException {
|
||||
super.setUp();
|
||||
simpleJdbcTemplate = new SimpleJdbcTemplate(jdbcTemplate);
|
||||
}
|
||||
|
||||
public void testOverridingClassDefinedForMapping() {
|
||||
ParameterizedBeanPropertyRowMapper<Person> mapper =
|
||||
ParameterizedBeanPropertyRowMapper.newInstance(Person.class);
|
||||
try {
|
||||
((ParameterizedBeanPropertyRowMapper) mapper).setMappedClass(Long.class);
|
||||
fail("Setting new class should have thrown InvalidDataAccessApiUsageException");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
// expected
|
||||
}
|
||||
try {
|
||||
mapper.setMappedClass(Person.class);
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
fail("Setting same class should not have thrown InvalidDataAccessApiUsageException");
|
||||
}
|
||||
}
|
||||
|
||||
public void testStaticQueryWithRowMapper() throws SQLException {
|
||||
List<Person> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
ParameterizedBeanPropertyRowMapper.newInstance(Person.class));
|
||||
assertEquals(1, result.size());
|
||||
Person bean = result.get(0);
|
||||
verifyPerson(bean);
|
||||
}
|
||||
|
||||
public void testMappingWithInheritance() throws SQLException {
|
||||
List<ConcretePerson> result = simpleJdbcTemplate.query("select name, age, birth_date, balance from people",
|
||||
ParameterizedBeanPropertyRowMapper.newInstance(ConcretePerson.class));
|
||||
assertEquals(1, result.size());
|
||||
ConcretePerson bean = result.get(0);
|
||||
verifyConcretePerson(bean);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.core.SqlOutParameter;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.*;
|
||||
|
||||
/**
|
||||
* Mock object based tests for SimpleJdbcCall.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SimpleJdbcCallTests extends TestCase {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
private MockControl ctrlCallable;
|
||||
private CallableStatement mockCallable;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
ctrlConnection = MockControl.createControl(Connection.class);
|
||||
mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setDefaultVoidCallable();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
ctrlCallable = MockControl.createControl(CallableStatement.class);
|
||||
mockCallable = (CallableStatement) ctrlCallable.getMock();
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
ctrlCallable.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
ctrlCallable.replay();
|
||||
}
|
||||
|
||||
public void testNoSuchStoredProcedure() throws Exception {
|
||||
final String NO_SUCH_PROC = "x";
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue("me");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
SQLException sex =
|
||||
new SQLException(
|
||||
"Syntax error or access violation exception",
|
||||
"42000");
|
||||
mockCallable.execute();
|
||||
ctrlCallable.setThrowable(sex);
|
||||
mockCallable.close();
|
||||
ctrlCallable.setVoidCallable();
|
||||
|
||||
mockConnection.prepareCall(
|
||||
"{call " + NO_SUCH_PROC + "()}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall sproc = new SimpleJdbcCall(mockDataSource).withProcedureName(NO_SUCH_PROC);
|
||||
try {
|
||||
sproc.execute();
|
||||
fail("Shouldn't succeed in running stored procedure which doesn't exist");
|
||||
} catch (BadSqlGrammarException ex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testUnnamedParameterHandling() throws Exception {
|
||||
final String MY_PROC = "my_proc";
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall sproc = new SimpleJdbcCall(mockDataSource).withProcedureName(MY_PROC);
|
||||
try {
|
||||
sproc.addDeclaredParameter(new SqlParameter(1));
|
||||
fail("Shouldn't succeed in adding unnamed parameter");
|
||||
} catch (InvalidDataAccessApiUsageException ex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testAddInvoiceProcWithoutMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(false);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER),
|
||||
new SqlOutParameter("newid", Types.INTEGER));
|
||||
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
assertEquals(4, newId.intValue());
|
||||
}
|
||||
|
||||
public void testAddInvoiceProcWithoutMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(false);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
adder.declareParameters(new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER),
|
||||
new SqlOutParameter("newid", Types.INTEGER));
|
||||
Number newId = adder.executeObject(Number.class, amount, custid);
|
||||
assertEquals(4, newId.intValue());
|
||||
}
|
||||
|
||||
public void testAddInvoiceProcWithMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(false);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
Number newId = adder.executeObject(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
assertEquals(4, newId.intValue());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
|
||||
public void testAddInvoiceProcWithMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(false);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withProcedureName("add_invoice");
|
||||
Number newId = adder.executeObject(Number.class, amount, custid);
|
||||
assertEquals(4, newId.intValue());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
|
||||
public void testAddInvoiceFuncWithoutMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(true);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
|
||||
new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER));
|
||||
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
assertEquals(4, newId.intValue());
|
||||
}
|
||||
|
||||
public void testAddInvoiceFuncWithoutMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
initializeAddInvoiceWithoutMetaData(true);
|
||||
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
adder.declareParameters(new SqlOutParameter("return", Types.INTEGER),
|
||||
new SqlParameter("amount", Types.INTEGER),
|
||||
new SqlParameter("custid", Types.INTEGER));
|
||||
Number newId = adder.executeFunction(Number.class, amount, custid);
|
||||
assertEquals(4, newId.intValue());
|
||||
}
|
||||
|
||||
public void testAddInvoiceFuncWithMetaDataUsingMapParamSource() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(true);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
Number newId = adder.executeFunction(Number.class, new MapSqlParameterSource()
|
||||
.addValue("amount", amount)
|
||||
.addValue("custid", custid));
|
||||
assertEquals(4, newId.intValue());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
|
||||
public void testAddInvoiceFuncWithMetaDataUsingArrayParams() throws Exception {
|
||||
final int amount = 1103;
|
||||
final int custid = 3;
|
||||
|
||||
MockControl ctrlResultSet = initializeAddInvoiceWithMetaData(true);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcCall adder = new SimpleJdbcCall(mockDataSource).withFunctionName("add_invoice");
|
||||
Number newId = adder.executeFunction(Number.class, amount, custid);
|
||||
assertEquals(4, newId.intValue());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
}
|
||||
|
||||
private void initializeAddInvoiceWithoutMetaData(boolean isFunction) throws SQLException {
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue("me");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
if (isFunction) {
|
||||
mockCallable.registerOutParameter(1, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(3, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
else {
|
||||
mockCallable.setObject(1, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.registerOutParameter(3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
mockCallable.execute();
|
||||
ctrlCallable.setReturnValue(false);
|
||||
mockCallable.getUpdateCount();
|
||||
ctrlCallable.setReturnValue(-1);
|
||||
if (isFunction) {
|
||||
mockCallable.getObject(1);
|
||||
}
|
||||
else {
|
||||
mockCallable.getObject(3);
|
||||
}
|
||||
ctrlCallable.setReturnValue(new Long(4));
|
||||
if (debugEnabled) {
|
||||
mockCallable.getWarnings();
|
||||
ctrlCallable.setReturnValue(null);
|
||||
}
|
||||
mockCallable.close();
|
||||
ctrlCallable.setVoidCallable();
|
||||
|
||||
if (isFunction) {
|
||||
mockConnection.prepareCall(
|
||||
"{? = call add_invoice(?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
else {
|
||||
mockConnection.prepareCall(
|
||||
"{call add_invoice(?, ?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
}
|
||||
|
||||
private MockControl initializeAddInvoiceWithMetaData(boolean isFunction) throws SQLException {
|
||||
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getString("PROCEDURE_CAT");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getString("PROCEDURE_SCHEM");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getString("PROCEDURE_NAME");
|
||||
ctrlResultSet.setReturnValue("add_invoice");
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
if (isFunction) {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(5);
|
||||
}
|
||||
else {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("amount");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
mockResultSet.getInt("DATA_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
mockResultSet.getString("TYPE_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getBoolean("NULLABLE");
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
if (isFunction) {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("amount");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
else {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("custid");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
mockResultSet.getInt("DATA_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
mockResultSet.getString("TYPE_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getBoolean("NULLABLE");
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
if (isFunction) {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("custid");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(1);
|
||||
}
|
||||
else {
|
||||
mockResultSet.getString("COLUMN_NAME");
|
||||
ctrlResultSet.setReturnValue("newid");
|
||||
mockResultSet.getInt("COLUMN_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
}
|
||||
mockResultSet.getInt("DATA_TYPE");
|
||||
ctrlResultSet.setReturnValue(4);
|
||||
mockResultSet.getString("TYPE_NAME");
|
||||
ctrlResultSet.setReturnValue(null);
|
||||
mockResultSet.getBoolean("NULLABLE");
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("Oracle");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue("ME");
|
||||
mockDatabaseMetaData.supportsCatalogsInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.supportsSchemasInProcedureCalls();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getProcedures("", "ME", "ADD_INVOICE");
|
||||
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
|
||||
mockDatabaseMetaData.getProcedureColumns("", "ME", "ADD_INVOICE", null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
|
||||
|
||||
if (isFunction) {
|
||||
mockCallable.registerOutParameter(1, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(3, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
else {
|
||||
mockCallable.setObject(1, 1103, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.setObject(2, 3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
mockCallable.registerOutParameter(3, 4);
|
||||
ctrlCallable.setVoidCallable();
|
||||
}
|
||||
mockCallable.execute();
|
||||
ctrlCallable.setReturnValue(false);
|
||||
mockCallable.getUpdateCount();
|
||||
ctrlCallable.setReturnValue(-1);
|
||||
if (isFunction) {
|
||||
mockCallable.getObject(1);
|
||||
ctrlCallable.setReturnValue(new Long(4));
|
||||
}
|
||||
else {
|
||||
mockCallable.getObject(3);
|
||||
ctrlCallable.setReturnValue(new Long(4));
|
||||
}
|
||||
if (debugEnabled) {
|
||||
mockCallable.getWarnings();
|
||||
ctrlCallable.setReturnValue(null);
|
||||
}
|
||||
mockCallable.close();
|
||||
ctrlCallable.setVoidCallable();
|
||||
|
||||
if (isFunction) {
|
||||
mockConnection.prepareCall(
|
||||
"{? = call ADD_INVOICE(?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
else {
|
||||
mockConnection.prepareCall(
|
||||
"{call ADD_INVOICE(?, ?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
}
|
||||
return ctrlResultSet;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* Mock object based tests for SimpleJdbcInsert.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SimpleJdbcInsertTests extends TestCase {
|
||||
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
ctrlConnection = MockControl.createControl(Connection.class);
|
||||
mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setDefaultVoidCallable();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
}
|
||||
|
||||
public void testNoSuchTable() throws Exception {
|
||||
final String NO_SUCH_TABLE = "x";
|
||||
final String USER = "me";
|
||||
|
||||
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsGetGeneratedKeys();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductVersion();
|
||||
ctrlDatabaseMetaData.setReturnValue("1.0");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.getTables(null, null, NO_SUCH_TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockResultSet);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
replay();
|
||||
|
||||
SimpleJdbcInsert insert = new SimpleJdbcInsert(mockDataSource).withTableName(NO_SUCH_TABLE);
|
||||
try {
|
||||
insert.execute(new HashMap());
|
||||
fail("Shouldn't succeed in inserting into table which doesn't exist");
|
||||
} catch (InvalidDataAccessApiUsageException ex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testInsert() throws Exception {
|
||||
replay();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.jdbc.core.simple;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.easymock.MockControl;
|
||||
import org.easymock.internal.ArrayMatcher;
|
||||
|
||||
import org.springframework.jdbc.core.BatchUpdateTestHelper;
|
||||
import org.springframework.jdbc.core.JdbcOperations;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Rob Harrop
|
||||
* @author Juergen Hoeller
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SimpleJdbcTemplateTests extends TestCase {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
|
||||
public void testQueryForIntWithoutArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR";
|
||||
int expectedResult = 666;
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForInt(sql);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
|
||||
assertSame(jo, jth.getJdbcOperations());
|
||||
|
||||
int result = jth.queryForInt(sql);
|
||||
assertEquals(expectedResult, result);
|
||||
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForIntWithArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
|
||||
int expectedResult = 666;
|
||||
int arg1 = 24;
|
||||
String arg2 = "foo";
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForInt(sql, new Object[]{arg1, arg2});
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
int result = jth.queryForInt(sql, arg1, arg2);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForIntWithMap() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=:id AND XY=:xy";
|
||||
int expectedResult = 666;
|
||||
int arg1 = 24;
|
||||
String arg2 = "foo";
|
||||
|
||||
MockControl mc = MockControl.createControl(NamedParameterJdbcOperations.class);
|
||||
NamedParameterJdbcOperations npjo = (NamedParameterJdbcOperations) mc.getMock();
|
||||
Map<String, Object> args = new HashMap<String, Object>(2);
|
||||
args.put("id", arg1);
|
||||
args.put("xy", arg2);
|
||||
npjo.queryForInt(sql, args);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(npjo);
|
||||
int result = jth.queryForInt(sql, args);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForIntWitSqlParameterSource() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=:id AND XY=:xy";
|
||||
int expectedResult = 666;
|
||||
int arg1 = 24;
|
||||
String arg2 = "foo";
|
||||
|
||||
MockControl mc = MockControl.createControl(NamedParameterJdbcOperations.class);
|
||||
NamedParameterJdbcOperations npjo = (NamedParameterJdbcOperations) mc.getMock();
|
||||
SqlParameterSource args = new MapSqlParameterSource().addValue("id", arg1).addValue("xy", arg2);
|
||||
npjo.queryForInt(sql, args);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(npjo);
|
||||
int result = jth.queryForInt(sql, args);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForLongWithoutArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR";
|
||||
long expectedResult = 666;
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForLong(sql);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
long result = jth.queryForLong(sql);
|
||||
assertEquals(expectedResult, result);
|
||||
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForLongWithArgs() {
|
||||
String sql = "SELECT COUNT(0) FROM BAR WHERE ID=? AND XY=?";
|
||||
long expectedResult = 666;
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForLong(sql, new Object[]{arg1, arg2, arg3});
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
long result = jth.queryForLong(sql, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithoutArgs() throws Exception {
|
||||
String sql = "SELECT SYSDATE FROM DUAL";
|
||||
Date expectedResult = new Date();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, Date.class);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, Date.class);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithArgs() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, Date.class, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithArgArray() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Object args = new Object[] {arg1, arg2, arg3};
|
||||
Date result = jth.queryForObject(sql, Date.class, args);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithMap() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, Date.class);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, Date.class, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithRowMapperAndWithoutArgs() throws Exception {
|
||||
String sql = "SELECT SYSDATE FROM DUAL";
|
||||
Date expectedResult = new Date();
|
||||
|
||||
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
|
||||
public Date mapRow(ResultSet rs, int rowNum) {
|
||||
return new Date();
|
||||
}
|
||||
};
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, rm);
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, rm);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithRowMapperAndArgs() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
|
||||
public Date mapRow(ResultSet rs, int rowNum) {
|
||||
return new Date();
|
||||
}
|
||||
};
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, rm);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, rm, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForObjectWithRowMapperAndMap() throws Exception {
|
||||
String sql = "SELECT SOMEDATE FROM BAR WHERE ID=? AND XY=?";
|
||||
Date expectedResult = new Date();
|
||||
double arg1 = 24.7;
|
||||
String arg2 = "foo";
|
||||
Object arg3 = new Object();
|
||||
|
||||
ParameterizedRowMapper<Date> rm = new ParameterizedRowMapper<Date>() {
|
||||
public Date mapRow(ResultSet rs, int rowNum) {
|
||||
return new Date();
|
||||
}
|
||||
};
|
||||
|
||||
MockControl mc = MockControl.createControl(JdbcOperations.class);
|
||||
JdbcOperations jo = (JdbcOperations) mc.getMock();
|
||||
jo.queryForObject(sql, new Object[]{arg1, arg2, arg3}, rm);
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
mc.setReturnValue(expectedResult);
|
||||
mc.replay();
|
||||
|
||||
SimpleJdbcTemplate jth = new SimpleJdbcTemplate(jo);
|
||||
Date result = jth.queryForObject(sql, rm, arg1, arg2, arg3);
|
||||
assertEquals(expectedResult, result);
|
||||
mc.verify();
|
||||
}
|
||||
|
||||
public void testQueryForListWithoutArgs() throws Exception {
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{}, Collections.singletonList(new Object()));
|
||||
}
|
||||
|
||||
public void testQueryForListWithArgs() throws Exception {
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{1, 2, 3}, new LinkedList());
|
||||
}
|
||||
|
||||
public void testQueryForListWithMap() throws Exception {
|
||||
HashMap args = new HashMap(3);
|
||||
args.put("1", 1);
|
||||
args.put("2", 2);
|
||||
args.put("3", 3);
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{args}, new LinkedList());
|
||||
}
|
||||
|
||||
public void testQueryForListWithSqlParameterSource() throws Exception {
|
||||
MapSqlParameterSource args = new MapSqlParameterSource();
|
||||
args.addValue("1", 1);
|
||||
args.addValue("2", 2);
|
||||
args.addValue("3", 3);
|
||||
testDelegation("queryForList", new Object[]{"sql"}, new Object[]{args}, new LinkedList());
|
||||
}
|
||||
|
||||
public void testQueryForMapWithoutArgs() throws Exception {
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{}, new HashMap());
|
||||
}
|
||||
|
||||
public void testQueryForMapWithArgs() throws Exception {
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{1, 2, 3}, new HashMap());
|
||||
// TODO test generic type
|
||||
}
|
||||
|
||||
public void testQueryForMapWithMap() throws Exception {
|
||||
HashMap args = new HashMap(3);
|
||||
args.put("1", 1);
|
||||
args.put("2", 2);
|
||||
args.put("3", 3);
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{args}, new HashMap());
|
||||
}
|
||||
|
||||
public void testQueryForMapWithSqlParameterSource() throws Exception {
|
||||
MapSqlParameterSource args = new MapSqlParameterSource();
|
||||
args.addValue("1", 1);
|
||||
args.addValue("2", 2);
|
||||
args.addValue("3", 3);
|
||||
testDelegation("queryForMap", new Object[]{"sql"}, new Object[]{args}, new HashMap());
|
||||
}
|
||||
|
||||
public void testUpdateWithoutArgs() throws Exception {
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{}, 666);
|
||||
}
|
||||
|
||||
public void testUpdateWithArgs() throws Exception {
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{1, 2, 3}, 666);
|
||||
}
|
||||
|
||||
public void testUpdateWithMap() throws Exception {
|
||||
HashMap args = new HashMap(3);
|
||||
args.put("1", 1);
|
||||
args.put("2", 2);
|
||||
args.put("3", 3);
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{args}, 666);
|
||||
}
|
||||
|
||||
public void testUpdateWithSqlParameterSource() throws Exception {
|
||||
MapSqlParameterSource args = new MapSqlParameterSource();
|
||||
args.addValue("1", 1);
|
||||
args.addValue("2", 2);
|
||||
args.addValue("3", 3);
|
||||
testDelegation("update", new Object[]{"sql"}, new Object[]{args}, 666);
|
||||
}
|
||||
|
||||
private Object testDelegation(String methodName, Object[] typedArgs, Object[] varargs, Object expectedResult) throws Exception {
|
||||
Class[] unifiedTypes;
|
||||
Object[] unifiedArgs;
|
||||
Class[] unifiedTypes2;
|
||||
Object[] unifiedArgs2;
|
||||
boolean namedParameters = false;
|
||||
|
||||
if (varargs != null && varargs.length > 0) {
|
||||
// Allow for Map
|
||||
if (varargs[0].getClass().equals(HashMap.class)) {
|
||||
unifiedTypes = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < typedArgs.length; i++) {
|
||||
unifiedTypes[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes[unifiedTypes.length - 1] = Map.class;
|
||||
unifiedArgs[unifiedArgs.length - 1] = varargs[0];
|
||||
unifiedTypes2 = unifiedTypes;
|
||||
unifiedArgs2 = unifiedArgs;
|
||||
namedParameters = true;
|
||||
}
|
||||
else if (varargs[0].getClass().equals(MapSqlParameterSource.class)) {
|
||||
unifiedTypes = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < typedArgs.length; i++) {
|
||||
unifiedTypes[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes[unifiedTypes.length - 1] = SqlParameterSource.class;
|
||||
unifiedArgs[unifiedArgs.length - 1] = varargs[0];
|
||||
unifiedTypes2 = unifiedTypes;
|
||||
unifiedArgs2 = unifiedArgs;
|
||||
namedParameters = true;
|
||||
}
|
||||
else {
|
||||
// Allow for varargs.length
|
||||
unifiedTypes = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < unifiedTypes.length - 1; i++) {
|
||||
unifiedTypes[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes[unifiedTypes.length - 1] = Object[].class;
|
||||
unifiedArgs[unifiedTypes.length - 1] = varargs;
|
||||
}
|
||||
|
||||
unifiedTypes2 = unifiedTypes;
|
||||
unifiedArgs2 = unifiedArgs;
|
||||
}
|
||||
else {
|
||||
unifiedTypes = new Class[typedArgs.length];
|
||||
unifiedTypes2 = new Class[typedArgs.length + 1];
|
||||
unifiedArgs = new Object[typedArgs.length];
|
||||
unifiedArgs2 = new Object[typedArgs.length + 1];
|
||||
for (int i = 0; i < typedArgs.length; i++) {
|
||||
unifiedTypes[i] = unifiedTypes2[i] = typedArgs[i].getClass();
|
||||
unifiedArgs[i] = unifiedArgs2[i] = typedArgs[i];
|
||||
}
|
||||
unifiedTypes2[unifiedTypes2.length - 1] = Object[].class;
|
||||
unifiedArgs2[unifiedArgs2.length - 1] = new Object[]{};
|
||||
}
|
||||
|
||||
MockControl mc;
|
||||
JdbcOperations jo = null;
|
||||
NamedParameterJdbcOperations npjo = null;
|
||||
Method joMethod = null;
|
||||
SimpleJdbcTemplate jth = null;
|
||||
|
||||
if (namedParameters) {
|
||||
mc = MockControl.createControl(NamedParameterJdbcOperations.class);
|
||||
npjo = (NamedParameterJdbcOperations) mc.getMock();
|
||||
joMethod = NamedParameterJdbcOperations.class.getMethod(methodName, unifiedTypes);
|
||||
joMethod.invoke(npjo, unifiedArgs);
|
||||
jth = new SimpleJdbcTemplate(npjo);
|
||||
}
|
||||
else {
|
||||
mc = MockControl.createControl(JdbcOperations.class);
|
||||
jo = (JdbcOperations) mc.getMock();
|
||||
joMethod = JdbcOperations.class.getMethod(methodName, unifiedTypes);
|
||||
joMethod.invoke(jo, unifiedArgs);
|
||||
jth = new SimpleJdbcTemplate(jo);
|
||||
}
|
||||
|
||||
mc.setDefaultMatcher(new ArrayMatcher());
|
||||
|
||||
if (joMethod.getReturnType().isPrimitive()) {
|
||||
// TODO bit of a hack with autoboxing passing up Integer when the return
|
||||
// type is an int
|
||||
mc.setReturnValue(((Integer) expectedResult).intValue());
|
||||
}
|
||||
else {
|
||||
mc.setReturnValue(expectedResult);
|
||||
}
|
||||
mc.replay();
|
||||
|
||||
Method jthMethod = SimpleJdbcTemplate.class.getMethod(methodName, unifiedTypes2);
|
||||
Object result = jthMethod.invoke(jth, unifiedArgs2);
|
||||
|
||||
assertEquals(expectedResult, result);
|
||||
|
||||
mc.verify();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithSqlParameterSource() throws Exception {
|
||||
|
||||
final String sqlToUse = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id";
|
||||
final SqlParameterSource[] ids = new SqlParameterSource[2];
|
||||
ids[0] = new MapSqlParameterSource("id", 100);
|
||||
ids[1] = new MapSqlParameterSource("id", 200);
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sqlToUse, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithListOfObjectArrays() throws Exception {
|
||||
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final List<Object[]> ids = new ArrayList<Object[]>();
|
||||
ids.add(new Object[] {100});
|
||||
ids.add(new Object[] {200});
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, null, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithListOfObjectArraysPlusTypeInfo() throws Exception {
|
||||
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final List<Object[]> ids = new ArrayList<Object[]>();
|
||||
ids.add(new Object[] {100});
|
||||
ids.add(new Object[] {200});
|
||||
final int[] sqlTypes = new int[] {Types.NUMERIC};
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, sqlTypes, rowsAffected, ctrlDataSource, mockDataSource, ctrlConnection,
|
||||
mockConnection, ctrlPreparedStatement, mockPreparedStatement, ctrlDatabaseMetaData,
|
||||
mockDatabaseMetaData);
|
||||
|
||||
BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
|
||||
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);
|
||||
|
||||
int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids, sqlTypes);
|
||||
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package org.springframework.jdbc.core.simple;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.springframework.jdbc.core.metadata.TableMetaDataContext;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.SqlParameterValue;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.sql.Types;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
/**
|
||||
* Mock object based tests for TableMetaDataContext.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class TableMetaDataContextTests extends TestCase {
|
||||
private MockControl ctrlDataSource;
|
||||
private DataSource mockDataSource;
|
||||
private MockControl ctrlConnection;
|
||||
private Connection mockConnection;
|
||||
private MockControl ctrlDatabaseMetaData;
|
||||
private DatabaseMetaData mockDatabaseMetaData;
|
||||
|
||||
private TableMetaDataContext context = new TableMetaDataContext();
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
|
||||
ctrlConnection = MockControl.createControl(Connection.class);
|
||||
mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setDefaultReturnValue(mockDatabaseMetaData);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setDefaultVoidCallable();
|
||||
|
||||
ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
ctrlDatabaseMetaData.replay();
|
||||
ctrlConnection.replay();
|
||||
ctrlDataSource.replay();
|
||||
}
|
||||
|
||||
public void testMatchInParametersAndSqlTypeInfoWrapping() throws Exception {
|
||||
final String TABLE = "customers";
|
||||
final String USER = "me";
|
||||
|
||||
MockControl ctrlMetaDataResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockMetaDataResultSet = (ResultSet) ctrlMetaDataResultSet.getMock();
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(true);
|
||||
mockMetaDataResultSet.getString("TABLE_CAT");
|
||||
ctrlMetaDataResultSet.setReturnValue(null);
|
||||
mockMetaDataResultSet.getString("TABLE_SCHEM");
|
||||
ctrlMetaDataResultSet.setReturnValue(USER);
|
||||
mockMetaDataResultSet.getString("TABLE_NAME");
|
||||
ctrlMetaDataResultSet.setReturnValue(TABLE);
|
||||
mockMetaDataResultSet.getString("TABLE_TYPE");
|
||||
ctrlMetaDataResultSet.setReturnValue("TABLE");
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(false);
|
||||
mockMetaDataResultSet.close();
|
||||
ctrlMetaDataResultSet.setVoidCallable();
|
||||
|
||||
MockControl ctrlColumnsResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockColumnsResultSet = (ResultSet) ctrlColumnsResultSet.getMock();
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("id");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.INTEGER);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("name");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.VARCHAR);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("customersince");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.DATE);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("version");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.NUMERIC);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.close();
|
||||
ctrlColumnsResultSet.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsGetGeneratedKeys();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductVersion();
|
||||
ctrlDatabaseMetaData.setReturnValue("1.0");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.getTables(null, null, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockMetaDataResultSet);
|
||||
mockDatabaseMetaData.getColumns(null, USER, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockColumnsResultSet);
|
||||
|
||||
ctrlMetaDataResultSet.replay();
|
||||
ctrlColumnsResultSet.replay();
|
||||
replay();
|
||||
|
||||
MapSqlParameterSource map = new MapSqlParameterSource();
|
||||
map.addValue("id", 1);
|
||||
map.addValue("name", "Sven");
|
||||
map.addValue("customersince", new Date());
|
||||
map.addValue("version", 0);
|
||||
map.registerSqlType("customersince", Types.DATE);
|
||||
map.registerSqlType("version", Types.NUMERIC);
|
||||
|
||||
context.setTableName(TABLE);
|
||||
context.processMetaData(mockDataSource, new ArrayList<String>(), new String[] {});
|
||||
|
||||
List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
|
||||
|
||||
assertEquals("wrong number of parameters: ", 4, values.size());
|
||||
assertTrue("id not wrapped with type info", values.get(0) instanceof Number);
|
||||
assertTrue("name not wrapped with type info", values.get(1) instanceof String);
|
||||
assertTrue("date wrapped with type info", values.get(2) instanceof SqlParameterValue);
|
||||
assertTrue("version wrapped with type info", values.get(3) instanceof SqlParameterValue);
|
||||
}
|
||||
|
||||
public void testTableWithSingleColumnGeneratedKey() throws Exception {
|
||||
final String TABLE = "customers";
|
||||
final String USER = "me";
|
||||
|
||||
MockControl ctrlMetaDataResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockMetaDataResultSet = (ResultSet) ctrlMetaDataResultSet.getMock();
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(true);
|
||||
mockMetaDataResultSet.getString("TABLE_CAT");
|
||||
ctrlMetaDataResultSet.setReturnValue(null);
|
||||
mockMetaDataResultSet.getString("TABLE_SCHEM");
|
||||
ctrlMetaDataResultSet.setReturnValue(USER);
|
||||
mockMetaDataResultSet.getString("TABLE_NAME");
|
||||
ctrlMetaDataResultSet.setReturnValue(TABLE);
|
||||
mockMetaDataResultSet.getString("TABLE_TYPE");
|
||||
ctrlMetaDataResultSet.setReturnValue("TABLE");
|
||||
mockMetaDataResultSet.next();
|
||||
ctrlMetaDataResultSet.setReturnValue(false);
|
||||
mockMetaDataResultSet.close();
|
||||
ctrlMetaDataResultSet.setVoidCallable();
|
||||
|
||||
MockControl ctrlColumnsResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockColumnsResultSet = (ResultSet) ctrlColumnsResultSet.getMock();
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(true);
|
||||
mockColumnsResultSet.getString("COLUMN_NAME");
|
||||
ctrlColumnsResultSet.setReturnValue("id");
|
||||
mockColumnsResultSet.getInt("DATA_TYPE");
|
||||
ctrlColumnsResultSet.setReturnValue(Types.INTEGER);
|
||||
mockColumnsResultSet.getBoolean("NULLABLE");
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.next();
|
||||
ctrlColumnsResultSet.setReturnValue(false);
|
||||
mockColumnsResultSet.close();
|
||||
ctrlColumnsResultSet.setVoidCallable();
|
||||
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.supportsGetGeneratedKeys();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.getDatabaseProductName();
|
||||
ctrlDatabaseMetaData.setReturnValue("MyDB");
|
||||
mockDatabaseMetaData.getDatabaseProductVersion();
|
||||
ctrlDatabaseMetaData.setReturnValue("1.0");
|
||||
mockDatabaseMetaData.getUserName();
|
||||
ctrlDatabaseMetaData.setReturnValue(USER);
|
||||
mockDatabaseMetaData.storesUpperCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(false);
|
||||
mockDatabaseMetaData.storesLowerCaseIdentifiers();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
mockDatabaseMetaData.getTables(null, null, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockMetaDataResultSet);
|
||||
mockDatabaseMetaData.getColumns(null, USER, TABLE, null);
|
||||
ctrlDatabaseMetaData.setReturnValue(mockColumnsResultSet);
|
||||
|
||||
ctrlMetaDataResultSet.replay();
|
||||
ctrlColumnsResultSet.replay();
|
||||
replay();
|
||||
|
||||
MapSqlParameterSource map = new MapSqlParameterSource();
|
||||
|
||||
String[] keyCols = new String[] {"id"};
|
||||
|
||||
context.setTableName(TABLE);
|
||||
context.processMetaData(mockDataSource, new ArrayList<String>(), keyCols);
|
||||
|
||||
List<Object> values = context.matchInParameterValuesWithInsertColumns(map);
|
||||
|
||||
String insertString = context.createInsertString(keyCols);
|
||||
|
||||
assertEquals("wrong number of parameters: ", 0, values.size());
|
||||
assertEquals("empty insert not generated correctly", "INSERT INTO customers () VALUES()", insertString);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.support;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class JdbcBeanDefinitionReaderTests extends AbstractJdbcTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
|
||||
public void testValid() throws Exception {
|
||||
String sql = "SELECT NAME AS NAME, PROPERTY AS PROPERTY, VALUE AS VALUE FROM T";
|
||||
|
||||
MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.next(), true, 2);
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.next(), false);
|
||||
|
||||
// first row
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(1), "one");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(2), "(class)");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(3), "org.springframework.beans.TestBean");
|
||||
|
||||
// second row
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(1), "one");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(2), "age");
|
||||
ctrlResultSet.expectAndReturn(mockResultSet.getString(3), "53");
|
||||
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
MockControl ctrlStatement = MockControl.createControl(Statement.class);
|
||||
Statement mockStatement = (Statement) ctrlStatement.getMock();
|
||||
ctrlStatement.expectAndReturn(mockStatement.executeQuery(sql), mockResultSet);
|
||||
if (debugEnabled) {
|
||||
ctrlStatement.expectAndReturn(mockStatement.getWarnings(), null);
|
||||
}
|
||||
mockStatement.close();
|
||||
ctrlStatement.setVoidCallable();
|
||||
|
||||
mockConnection.createStatement();
|
||||
ctrlConnection.setReturnValue(mockStatement);
|
||||
|
||||
ctrlResultSet.replay();
|
||||
ctrlStatement.replay();
|
||||
replay();
|
||||
|
||||
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
|
||||
JdbcBeanDefinitionReader reader = new JdbcBeanDefinitionReader(bf);
|
||||
reader.setDataSource(mockDataSource);
|
||||
reader.loadBeanDefinitions(sql);
|
||||
assertEquals("Incorrect number of bean definitions", 1, bf.getBeanDefinitionCount());
|
||||
TestBean tb = (TestBean) bf.getBean("one");
|
||||
assertEquals("Age in TestBean was wrong.", 53, tb.getAge());
|
||||
|
||||
ctrlResultSet.verify();
|
||||
ctrlStatement.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.core.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 30.07.2003
|
||||
*/
|
||||
public class JdbcDaoSupportTests extends TestCase {
|
||||
|
||||
public void testJdbcDaoSupportWithDataSource() throws Exception {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
final List test = new ArrayList();
|
||||
JdbcDaoSupport dao = new JdbcDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setDataSource(ds);
|
||||
dao.afterPropertiesSet();
|
||||
assertEquals("Correct DataSource", ds, dao.getDataSource());
|
||||
assertEquals("Correct JdbcTemplate", ds, dao.getJdbcTemplate().getDataSource());
|
||||
assertEquals("initDao called", test.size(), 1);
|
||||
}
|
||||
|
||||
public void testJdbcDaoSupportWithJdbcTemplate() throws Exception {
|
||||
JdbcTemplate template = new JdbcTemplate();
|
||||
final List test = new ArrayList();
|
||||
JdbcDaoSupport dao = new JdbcDaoSupport() {
|
||||
protected void initDao() {
|
||||
test.add("test");
|
||||
}
|
||||
};
|
||||
dao.setJdbcTemplate(template);
|
||||
dao.afterPropertiesSet();
|
||||
assertEquals("Correct JdbcTemplate", dao.getJdbcTemplate(), template);
|
||||
assertEquals("initDao called", test.size(), 1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.core.support;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.IncorrectResultSizeDataAccessException;
|
||||
import org.springframework.jdbc.LobRetrievalFailureException;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
|
||||
/**
|
||||
* @author Alef Arendsen
|
||||
*/
|
||||
public class LobSupportTests extends TestCase {
|
||||
|
||||
public void testCreatingPreparedStatementCallback() throws SQLException {
|
||||
// - return value should match
|
||||
// - lob creator should be closed
|
||||
// - set return value should be called
|
||||
// - execute update should be called
|
||||
|
||||
MockControl lobHandlerControl = MockControl.createControl(LobHandler.class);
|
||||
LobHandler handler = (LobHandler)lobHandlerControl.getMock();
|
||||
|
||||
MockControl lobCreatorControl = MockControl.createControl(LobCreator.class);
|
||||
LobCreator creator = (LobCreator)lobCreatorControl.getMock();
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement)psControl.getMock();
|
||||
|
||||
handler.getLobCreator();
|
||||
lobHandlerControl.setReturnValue(creator);
|
||||
ps.executeUpdate();
|
||||
psControl.setReturnValue(3);
|
||||
creator.close();
|
||||
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
psControl.replay();
|
||||
|
||||
class SetValuesCalled {
|
||||
boolean b = false;
|
||||
}
|
||||
|
||||
final SetValuesCalled svc = new SetValuesCalled();
|
||||
|
||||
AbstractLobCreatingPreparedStatementCallback psc =
|
||||
new AbstractLobCreatingPreparedStatementCallback(handler) {
|
||||
|
||||
protected void setValues(PreparedStatement ps, LobCreator lobCreator)
|
||||
throws SQLException, DataAccessException {
|
||||
svc.b = true;
|
||||
}
|
||||
};
|
||||
|
||||
assertEquals(new Integer(3), psc.doInPreparedStatement(ps));
|
||||
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
psControl.verify();
|
||||
assertTrue(svc.b);
|
||||
}
|
||||
|
||||
public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(false);
|
||||
rsetControl.replay();
|
||||
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
|
||||
try {
|
||||
lobRse.extractData(rset);
|
||||
fail("IncorrectResultSizeDataAccessException should have been thrown");
|
||||
} catch (IncorrectResultSizeDataAccessException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testAbstractLobStreamingResultSetExtractorOneRow() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
// see if it's called
|
||||
rset.clearWarnings();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(false);
|
||||
rsetControl.replay();
|
||||
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
|
||||
lobRse.extractData(rset);
|
||||
rsetControl.verify();
|
||||
}
|
||||
|
||||
public void testAbstractLobStreamingResultSetExtractorMultipleRows() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
// see if it's called
|
||||
rset.clearWarnings();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
rsetControl.replay();
|
||||
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(false);
|
||||
try {
|
||||
lobRse.extractData(rset);
|
||||
fail("IncorrectResultSizeDataAccessException should have been thrown");
|
||||
} catch (IncorrectResultSizeDataAccessException e) {
|
||||
// expected
|
||||
}
|
||||
rsetControl.verify();
|
||||
}
|
||||
|
||||
public void testAbstractLobStreamingResultSetExtractorCorrectException() throws SQLException {
|
||||
MockControl rsetControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rset = (ResultSet)rsetControl.getMock();
|
||||
rset.next();
|
||||
rsetControl.setReturnValue(true);
|
||||
rsetControl.replay();
|
||||
|
||||
AbstractLobStreamingResultSetExtractor lobRse = getResultSetExtractor(true);
|
||||
try {
|
||||
lobRse.extractData(rset);
|
||||
fail("LobRetrievalFailureException should have been thrown");
|
||||
} catch (LobRetrievalFailureException e) {
|
||||
// expected
|
||||
}
|
||||
rsetControl.verify();
|
||||
}
|
||||
|
||||
private AbstractLobStreamingResultSetExtractor getResultSetExtractor(final boolean ex) {
|
||||
AbstractLobStreamingResultSetExtractor lobRse = new AbstractLobStreamingResultSetExtractor() {
|
||||
protected void streamData(ResultSet rs) throws SQLException, IOException {
|
||||
if (ex) {
|
||||
throw new IOException();
|
||||
}
|
||||
else {
|
||||
rs.clearWarnings();
|
||||
}
|
||||
}
|
||||
};
|
||||
return lobRse;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.core.support;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.ArgumentsMatcher;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
|
||||
/**
|
||||
* Test cases for the sql lob value:
|
||||
*
|
||||
* BLOB:
|
||||
* 1. Types.BLOB: setBlobAsBytes (byte[])
|
||||
* 2. String: setBlobAsBytes (byte[])
|
||||
* 3. else: IllegalArgumentException
|
||||
*
|
||||
* CLOB:
|
||||
* 4. String or NULL: setClobAsString (String)
|
||||
* 5. InputStream: setClobAsAsciiStream (InputStream)
|
||||
* 6. Reader: setClobAsCharacterStream (Reader)
|
||||
* 7. else: IllegalArgumentException
|
||||
*
|
||||
* @author Alef Arendsen
|
||||
*/
|
||||
public class SqlLobValueTests extends TestCase {
|
||||
|
||||
private MockControl psControl;
|
||||
private PreparedStatement ps;
|
||||
|
||||
private MockControl lobHandlerControl;
|
||||
private LobHandler handler;
|
||||
|
||||
private MockControl lobCreatorControl;
|
||||
private LobCreator creator;
|
||||
|
||||
public void setUp() {
|
||||
// create preparedstatement
|
||||
psControl = MockControl.createControl(PreparedStatement.class);
|
||||
ps = (PreparedStatement) psControl.getMock();
|
||||
|
||||
// create handler controler
|
||||
lobHandlerControl = MockControl.createControl(LobHandler.class);
|
||||
handler = (LobHandler) lobHandlerControl.getMock();
|
||||
|
||||
// create creator control
|
||||
lobCreatorControl = MockControl.createControl(LobCreator.class);
|
||||
creator = (LobCreator) lobCreatorControl.getMock();
|
||||
|
||||
// set initial state
|
||||
handler.getLobCreator();
|
||||
lobHandlerControl.setReturnValue(creator);
|
||||
}
|
||||
|
||||
private void replay() {
|
||||
psControl.replay();
|
||||
lobHandlerControl.replay();
|
||||
lobCreatorControl.replay();
|
||||
}
|
||||
|
||||
public void test1() throws SQLException {
|
||||
byte[] testBytes = "Bla".getBytes();
|
||||
creator.setBlobAsBytes(ps, 1, testBytes);
|
||||
replay();
|
||||
SqlLobValue lob = new SqlLobValue(testBytes, handler);
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
}
|
||||
|
||||
public void test2() throws SQLException {
|
||||
String testString = "Bla";
|
||||
|
||||
creator.setBlobAsBytes(ps, 1, testString.getBytes());
|
||||
// set a matcher to match the byte array!
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
public boolean matches(Object[] arg0, Object[] arg1) {
|
||||
byte[] one = (byte[]) arg0[2];
|
||||
byte[] two = (byte[]) arg1[2];
|
||||
return Arrays.equals(one, two);
|
||||
}
|
||||
public String toString(Object[] arg0) {
|
||||
return "bla";
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(testString, handler);
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
|
||||
}
|
||||
|
||||
public void test3()
|
||||
throws SQLException {
|
||||
|
||||
Date testContent = new Date();
|
||||
|
||||
SqlLobValue lob =
|
||||
new SqlLobValue(new InputStreamReader(new ByteArrayInputStream("Bla".getBytes())), 12);
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void test4() throws SQLException {
|
||||
String testContent = "Bla";
|
||||
creator.setClobAsString(ps, 1, testContent);
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(testContent, handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
}
|
||||
|
||||
public void test5() throws SQLException {
|
||||
byte[] testContent = "Bla".getBytes();
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(testContent);
|
||||
creator.setClobAsAsciiStream(ps, 1, bais, 3);
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
public boolean matches(Object[] arg0, Object[] arg1) {
|
||||
// for now, match always
|
||||
return true;
|
||||
}
|
||||
public String toString(Object[] arg0) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(new ByteArrayInputStream(testContent), 3, handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
}
|
||||
|
||||
public void test6()throws SQLException {
|
||||
byte[] testContent = "Bla".getBytes();
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(testContent);
|
||||
InputStreamReader reader = new InputStreamReader(bais);
|
||||
creator.setClobAsCharacterStream(ps, 1, reader, 3);
|
||||
lobCreatorControl.setMatcher(new ArgumentsMatcher() {
|
||||
public boolean matches(Object[] arg0, Object[] arg1) {
|
||||
// for now, match always
|
||||
return true;
|
||||
}
|
||||
public String toString(Object[] arg0) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
replay();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue(reader, 3, handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lobHandlerControl.verify();
|
||||
lobCreatorControl.verify();
|
||||
|
||||
}
|
||||
|
||||
public void test7() throws SQLException {
|
||||
Date testContent = new Date();
|
||||
|
||||
SqlLobValue lob = new SqlLobValue("bla".getBytes());
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testOtherConstructors() throws SQLException {
|
||||
// a bit BS, but we need to test them, as long as they don't throw exceptions
|
||||
|
||||
SqlLobValue lob = new SqlLobValue("bla");
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
|
||||
try {
|
||||
lob = new SqlLobValue("bla".getBytes());
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
|
||||
lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
|
||||
lob = new SqlLobValue(new InputStreamReader(
|
||||
new ByteArrayInputStream("bla".getBytes())), 3);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
|
||||
// same for BLOB
|
||||
lob = new SqlLobValue("bla");
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
|
||||
lob = new SqlLobValue("bla".getBytes());
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
|
||||
lob = new SqlLobValue(new ByteArrayInputStream("bla".getBytes()), 3);
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
|
||||
lob = new SqlLobValue(new InputStreamReader(
|
||||
new ByteArrayInputStream("bla".getBytes())), 3);
|
||||
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.BLOB, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
public void testCorrectCleanup() throws SQLException {
|
||||
creator.setClobAsString(ps, 1, "Bla");
|
||||
creator.close();
|
||||
|
||||
replay();
|
||||
SqlLobValue lob = new SqlLobValue("Bla", handler);
|
||||
lob.setTypeValue(ps, 1, Types.CLOB, "test");
|
||||
lob.cleanup();
|
||||
|
||||
lobCreatorControl.verify();
|
||||
}
|
||||
|
||||
public void testOtherSqlType() throws SQLException {
|
||||
replay();
|
||||
SqlLobValue lob = new SqlLobValue("Bla", handler);
|
||||
try {
|
||||
lob.setTypeValue(ps, 1, Types.SMALLINT, "test");
|
||||
fail("IllegalArgumentException should have been thrown");
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.test;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public abstract class AbstractPerson {
|
||||
|
||||
private String name;
|
||||
|
||||
private long age;
|
||||
|
||||
private Date birth_date;
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(long age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public Date getBirth_date() {
|
||||
return birth_date;
|
||||
}
|
||||
|
||||
public void setBirth_date(Date birth_date) {
|
||||
this.birth_date = birth_date;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class ConcretePerson extends AbstractPerson {
|
||||
|
||||
private BigDecimal balance;
|
||||
|
||||
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(BigDecimal balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.test;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class ExtendedPerson extends ConcretePerson {
|
||||
|
||||
private Object someField;
|
||||
|
||||
|
||||
public Object getSomeField() {
|
||||
return someField;
|
||||
}
|
||||
|
||||
public void setSomeField(Object someField) {
|
||||
this.someField = someField;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class Person {
|
||||
|
||||
private String name;
|
||||
|
||||
private long age;
|
||||
|
||||
private java.util.Date birth_date;
|
||||
|
||||
private BigDecimal balance;
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(long age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public java.util.Date getBirth_date() {
|
||||
return birth_date;
|
||||
}
|
||||
|
||||
public void setBirth_date(java.util.Date birth_date) {
|
||||
this.birth_date = birth_date;
|
||||
}
|
||||
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(BigDecimal balanace) {
|
||||
this.balance = balanace;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.core.test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SpacePerson {
|
||||
|
||||
private String lastName;
|
||||
|
||||
private long age;
|
||||
|
||||
private java.util.Date birthDate;
|
||||
|
||||
private BigDecimal balance;
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public long getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(long age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public java.util.Date getBirthDate() {
|
||||
return birthDate;
|
||||
}
|
||||
|
||||
public void setBirth_date(java.util.Date birthDate) {
|
||||
this.birthDate = birthDate;
|
||||
}
|
||||
|
||||
public BigDecimal getBalance() {
|
||||
return balance;
|
||||
}
|
||||
|
||||
public void setBalance(BigDecimal balanace) {
|
||||
this.balance = balanace;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,901 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc.datasource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import javax.transaction.Status;
|
||||
import javax.transaction.SystemException;
|
||||
import javax.transaction.Transaction;
|
||||
import javax.transaction.TransactionManager;
|
||||
import javax.transaction.UserTransaction;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.beans.factory.support.StaticListableBeanFactory;
|
||||
import org.springframework.jdbc.datasource.lookup.BeanFactoryDataSourceLookup;
|
||||
import org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.TransactionException;
|
||||
import org.springframework.transaction.TransactionStatus;
|
||||
import org.springframework.transaction.jta.JtaTransactionManager;
|
||||
import org.springframework.transaction.jta.JtaTransactionObject;
|
||||
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 17.10.2005
|
||||
*/
|
||||
public class DataSourceJtaTransactionTests extends TestCase {
|
||||
|
||||
public void testJtaTransactionCommit() throws Exception {
|
||||
doTestJtaTransaction(false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionRollback() throws Exception {
|
||||
doTestJtaTransaction(true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransaction(final boolean rollback) throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
if (rollback) {
|
||||
ut.rollback();
|
||||
}
|
||||
else {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
ut.commit();
|
||||
}
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
conControl.replay();
|
||||
dsControl.replay();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut);
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
|
||||
c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
|
||||
if (rollback) {
|
||||
status.setRollbackOnly();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
utControl.verify();
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNew() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, false, false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, true, false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, true, true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(false, false, true, true);
|
||||
}
|
||||
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNew() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, false, false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithAccessAfterResume() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnection() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, true, false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithOpenOuterConnectionAccessed() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, true, true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionRollbackWithPropagationRequiresNewWithTransactionAwareDataSource() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNew(true, false, true, true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransactionWithPropagationRequiresNew(
|
||||
final boolean rollback, final boolean openOuterConnection, final boolean accessAfterResume,
|
||||
final boolean useTransactionAwareDataSource) throws Exception {
|
||||
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 16);
|
||||
tm.suspend();
|
||||
tmControl.setReturnValue(tx, 5);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(5);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(5);
|
||||
tm.resume(tx);
|
||||
tmControl.setVoidCallable(5);
|
||||
if (rollback) {
|
||||
ut.rollback();
|
||||
}
|
||||
else {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
ut.commit();
|
||||
}
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
tmControl.replay();
|
||||
|
||||
final MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
final MockControl conControl = MockControl.createControl(Connection.class);
|
||||
final Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
if (!openOuterConnection) {
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
}
|
||||
conControl.replay();
|
||||
dsControl.replay();
|
||||
|
||||
final DataSource dsToUse = useTransactionAwareDataSource ?
|
||||
new TransactionAwareDataSourceProxy(ds) : ds;
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
|
||||
final TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
try {
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
c.isReadOnly();
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
if (!openOuterConnection) {
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
try {
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
dsControl.reset();
|
||||
conControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
c.isReadOnly();
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (rollback) {
|
||||
status.setRollbackOnly();
|
||||
}
|
||||
|
||||
if (accessAfterResume) {
|
||||
try {
|
||||
if (!openOuterConnection) {
|
||||
dsControl.verify();
|
||||
dsControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
dsControl.replay();
|
||||
}
|
||||
conControl.verify();
|
||||
conControl.reset();
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
conControl.replay();
|
||||
|
||||
if (!openOuterConnection) {
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
}
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
c.isReadOnly();
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
}
|
||||
|
||||
else {
|
||||
if (openOuterConnection) {
|
||||
try {
|
||||
conControl.verify();
|
||||
conControl.reset();
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
conControl.replay();
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
utControl.verify();
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiredWithinSupports() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiredWithinNotSupported() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(false, true);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithinSupports() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithinNotSupported() throws Exception {
|
||||
doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(true, true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(
|
||||
final boolean requiresNew, boolean notSupported) throws Exception {
|
||||
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
if (notSupported) {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
tm.suspend();
|
||||
tmControl.setReturnValue(tx, 1);
|
||||
}
|
||||
else {
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
}
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(1);
|
||||
if (notSupported) {
|
||||
tm.resume(tx);
|
||||
tmControl.setVoidCallable(1);
|
||||
}
|
||||
utControl.replay();
|
||||
tmControl.replay();
|
||||
txControl.replay();
|
||||
|
||||
final MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
final MockControl con1Control = MockControl.createControl(Connection.class);
|
||||
final Connection con1 = (Connection) con1Control.getMock();
|
||||
final MockControl con2Control = MockControl.createControl(Connection.class);
|
||||
final Connection con2 = (Connection) con2Control.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con1, 1);
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con2, 1);
|
||||
con2.close();
|
||||
con2Control.setVoidCallable(1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
con1Control.replay();
|
||||
con2Control.replay();
|
||||
|
||||
final JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.setPropagationBehavior(notSupported ?
|
||||
TransactionDefinition.PROPAGATION_NOT_SUPPORTED : TransactionDefinition.PROPAGATION_SUPPORTS);
|
||||
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) {
|
||||
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
assertSame(con1, DataSourceUtils.getConnection(ds));
|
||||
assertSame(con1, DataSourceUtils.getConnection(ds));
|
||||
|
||||
TransactionTemplate tt2 = new TransactionTemplate(ptm);
|
||||
tt2.setPropagationBehavior(requiresNew ?
|
||||
TransactionDefinition.PROPAGATION_REQUIRES_NEW : TransactionDefinition.PROPAGATION_REQUIRED);
|
||||
tt2.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) {
|
||||
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
assertSame(con2, DataSourceUtils.getConnection(ds));
|
||||
assertSame(con2, DataSourceUtils.getConnection(ds));
|
||||
}
|
||||
});
|
||||
|
||||
assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
assertSame(con1, DataSourceUtils.getConnection(ds));
|
||||
}
|
||||
});
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
utControl.verify();
|
||||
tmControl.verify();
|
||||
txControl.verify();
|
||||
dsControl.verify();
|
||||
con1Control.verify();
|
||||
con2Control.verify();
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, false, true);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndSuspendException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(true, true, true);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithOpenOuterConnectionAndTransactionAwareDataSourceAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, true, true);
|
||||
}
|
||||
|
||||
public void testJtaTransactionCommitWithPropagationRequiresNewWithTransactionAwareDataSourceAndBeginException() throws Exception {
|
||||
doTestJtaTransactionWithPropagationRequiresNewAndBeginException(false, false, true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException,
|
||||
final boolean openOuterConnection, final boolean useTransactionAwareDataSource) throws Exception {
|
||||
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
MockControl tmControl = MockControl.createControl(TransactionManager.class);
|
||||
TransactionManager tm = (TransactionManager) tmControl.getMock();
|
||||
MockControl txControl = MockControl.createControl(Transaction.class);
|
||||
Transaction tx = (Transaction) txControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
if (suspendException) {
|
||||
tm.suspend();
|
||||
tmControl.setThrowable(new SystemException(), 1);
|
||||
}
|
||||
else {
|
||||
tm.suspend();
|
||||
tmControl.setReturnValue(tx, 1);
|
||||
ut.begin();
|
||||
utControl.setThrowable(new SystemException(), 1);
|
||||
tm.resume(tx);
|
||||
tmControl.setVoidCallable(1);
|
||||
}
|
||||
ut.rollback();
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
tmControl.replay();
|
||||
|
||||
final MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
final MockControl conControl = MockControl.createControl(Connection.class);
|
||||
final Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
if (!openOuterConnection || useTransactionAwareDataSource) {
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
}
|
||||
conControl.replay();
|
||||
dsControl.replay();
|
||||
|
||||
final DataSource dsToUse = useTransactionAwareDataSource ?
|
||||
new TransactionAwareDataSourceProxy(ds) : ds;
|
||||
if (dsToUse instanceof TransactionAwareDataSourceProxy) {
|
||||
((TransactionAwareDataSourceProxy) dsToUse).setReobtainTransactionalConnections(true);
|
||||
}
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut, tm);
|
||||
final TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
try {
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
try {
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
c.isReadOnly();
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
if (!openOuterConnection) {
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
|
||||
try {
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is new transaction", status.isNewTransaction());
|
||||
|
||||
try {
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
dsControl.reset();
|
||||
conControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
|
||||
c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
finally {
|
||||
if (openOuterConnection) {
|
||||
try {
|
||||
dsControl.verify();
|
||||
dsControl.reset();
|
||||
conControl.verify();
|
||||
conControl.reset();
|
||||
|
||||
if (useTransactionAwareDataSource) {
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
}
|
||||
con.isReadOnly();
|
||||
conControl.setReturnValue(true, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
c.isReadOnly();
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
catch (SQLException ex) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
fail("Should have thrown TransactionException");
|
||||
}
|
||||
catch (TransactionException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
utControl.verify();
|
||||
tmControl.verify();
|
||||
}
|
||||
|
||||
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut) {
|
||||
protected void doRegisterAfterCompletionWithJtaTransaction(
|
||||
JtaTransactionObject txObject, final List synchronizations) {
|
||||
Thread async = new Thread() {
|
||||
public void run() {
|
||||
invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_COMMITTED);
|
||||
}
|
||||
};
|
||||
async.start();
|
||||
try {
|
||||
async.join();
|
||||
}
|
||||
catch (InterruptedException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
utControl.reset();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 1);
|
||||
utControl.replay();
|
||||
|
||||
dsControl.reset();
|
||||
conControl.reset();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 1);
|
||||
con.close();
|
||||
conControl.setVoidCallable(1);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
final boolean releaseCon = (i != 1);
|
||||
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
assertTrue("JTA synchronizations active", TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertTrue("Is existing transaction", !status.isNewTransaction());
|
||||
|
||||
Connection c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
|
||||
c = DataSourceUtils.getConnection(ds);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
|
||||
if (releaseCon) {
|
||||
DataSourceUtils.releaseConnection(c, ds);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!releaseCon) {
|
||||
assertTrue("Still has connection holder", TransactionSynchronizationManager.hasResource(ds));
|
||||
}
|
||||
else {
|
||||
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
|
||||
}
|
||||
assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());
|
||||
|
||||
conControl.verify();
|
||||
dsControl.verify();
|
||||
utControl.verify();
|
||||
}
|
||||
}
|
||||
|
||||
public void testJtaTransactionWithIsolationLevelDataSourceAdapter() throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
|
||||
MockControl ds1Control = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds1 = (DataSource) ds1Control.getMock();
|
||||
MockControl con1Control = MockControl.createControl(Connection.class);
|
||||
final Connection con1 = (Connection) con1Control.getMock();
|
||||
ds1.getConnection();
|
||||
ds1Control.setReturnValue(con1, 1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
ds1.getConnection();
|
||||
ds1Control.setReturnValue(con1, 1);
|
||||
con1.setReadOnly(true);
|
||||
con1Control.setVoidCallable(1);
|
||||
con1.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
|
||||
con1Control.setVoidCallable(1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
con1Control.replay();
|
||||
ds1Control.replay();
|
||||
|
||||
final IsolationLevelDataSourceAdapter dsToUse = new IsolationLevelDataSourceAdapter();
|
||||
dsToUse.setTargetDataSource(ds1);
|
||||
dsToUse.afterPropertiesSet();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut);
|
||||
ptm.setAllowCustomIsolationLevels(true);
|
||||
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con1, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
|
||||
tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
tt.setReadOnly(true);
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con1, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
|
||||
ds1Control.verify();
|
||||
con1Control.verify();
|
||||
utControl.verify();
|
||||
}
|
||||
|
||||
public void testJtaTransactionWithIsolationLevelDataSourceRouter() throws Exception {
|
||||
doTestJtaTransactionWithIsolationLevelDataSourceRouter(false);
|
||||
}
|
||||
|
||||
public void testJtaTransactionWithIsolationLevelDataSourceRouterWithDataSourceLookup() throws Exception {
|
||||
doTestJtaTransactionWithIsolationLevelDataSourceRouter(true);
|
||||
}
|
||||
|
||||
private void doTestJtaTransactionWithIsolationLevelDataSourceRouter(boolean dataSourceLookup) throws Exception {
|
||||
MockControl utControl = MockControl.createControl(UserTransaction.class);
|
||||
UserTransaction ut = (UserTransaction) utControl.getMock();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1);
|
||||
ut.getStatus();
|
||||
utControl.setReturnValue(Status.STATUS_ACTIVE, 2);
|
||||
ut.begin();
|
||||
utControl.setVoidCallable(1);
|
||||
ut.commit();
|
||||
utControl.setVoidCallable(1);
|
||||
utControl.replay();
|
||||
|
||||
MockControl ds1Control = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds1 = (DataSource) ds1Control.getMock();
|
||||
MockControl con1Control = MockControl.createControl(Connection.class);
|
||||
final Connection con1 = (Connection) con1Control.getMock();
|
||||
ds1.getConnection();
|
||||
ds1Control.setReturnValue(con1, 1);
|
||||
con1.close();
|
||||
con1Control.setVoidCallable(1);
|
||||
con1Control.replay();
|
||||
ds1Control.replay();
|
||||
|
||||
MockControl ds2Control = MockControl.createControl(DataSource.class);
|
||||
final DataSource ds2 = (DataSource) ds2Control.getMock();
|
||||
MockControl con2Control = MockControl.createControl(Connection.class);
|
||||
final Connection con2 = (Connection) con2Control.getMock();
|
||||
ds2.getConnection();
|
||||
ds2Control.setReturnValue(con2, 1);
|
||||
con2.close();
|
||||
con2Control.setVoidCallable(1);
|
||||
con2Control.replay();
|
||||
ds2Control.replay();
|
||||
|
||||
final IsolationLevelDataSourceRouter dsToUse = new IsolationLevelDataSourceRouter();
|
||||
Map targetDataSources = new HashMap();
|
||||
if (dataSourceLookup) {
|
||||
targetDataSources.put("ISOLATION_REPEATABLE_READ", "ds2");
|
||||
dsToUse.setDefaultTargetDataSource("ds1");
|
||||
StaticListableBeanFactory beanFactory = new StaticListableBeanFactory();
|
||||
beanFactory.addBean("ds1", ds1);
|
||||
beanFactory.addBean("ds2", ds2);
|
||||
dsToUse.setDataSourceLookup(new BeanFactoryDataSourceLookup(beanFactory));
|
||||
}
|
||||
else {
|
||||
targetDataSources.put("ISOLATION_REPEATABLE_READ", ds2);
|
||||
dsToUse.setDefaultTargetDataSource(ds1);
|
||||
}
|
||||
dsToUse.setTargetDataSources(targetDataSources);
|
||||
dsToUse.afterPropertiesSet();
|
||||
|
||||
JtaTransactionManager ptm = new JtaTransactionManager(ut);
|
||||
ptm.setAllowCustomIsolationLevels(true);
|
||||
|
||||
TransactionTemplate tt = new TransactionTemplate(ptm);
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con1, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
|
||||
tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
tt.execute(new TransactionCallbackWithoutResult() {
|
||||
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
|
||||
Connection c = DataSourceUtils.getConnection(dsToUse);
|
||||
assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(dsToUse));
|
||||
assertSame(con2, c);
|
||||
DataSourceUtils.releaseConnection(c, dsToUse);
|
||||
}
|
||||
});
|
||||
|
||||
ds1Control.verify();
|
||||
con1Control.verify();
|
||||
ds2Control.verify();
|
||||
con2Control.verify();
|
||||
utControl.verify();
|
||||
}
|
||||
|
||||
protected void tearDown() {
|
||||
assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty());
|
||||
assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
|
||||
assertNull(TransactionSynchronizationManager.getCurrentTransactionName());
|
||||
assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
|
||||
assertNull(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel());
|
||||
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.datasource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.Properties;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class DriverManagerDataSourceTests extends TestCase {
|
||||
|
||||
public void testStandardUsage() throws Exception {
|
||||
final String jdbcUrl = "url";
|
||||
final String uname = "uname";
|
||||
final String pwd = "pwd";
|
||||
|
||||
MockControl ctrlConnection =
|
||||
MockControl.createControl(Connection.class);
|
||||
final Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
ctrlConnection.replay();
|
||||
|
||||
class TestDriverManagerDataSource extends DriverManagerDataSource {
|
||||
protected Connection getConnectionFromDriverManager(String url, Properties props) {
|
||||
assertEquals(jdbcUrl, url);
|
||||
assertEquals(uname, props.getProperty("user"));
|
||||
assertEquals(pwd, props.getProperty("password"));
|
||||
return mockConnection;
|
||||
}
|
||||
}
|
||||
|
||||
DriverManagerDataSource ds = new TestDriverManagerDataSource();
|
||||
//ds.setDriverClassName("foobar");
|
||||
ds.setUrl(jdbcUrl);
|
||||
ds.setUsername(uname);
|
||||
ds.setPassword(pwd);
|
||||
|
||||
Connection actualCon = ds.getConnection();
|
||||
assertTrue(actualCon == mockConnection);
|
||||
|
||||
assertTrue(ds.getUrl().equals(jdbcUrl));
|
||||
assertTrue(ds.getPassword().equals(pwd));
|
||||
assertTrue(ds.getUsername().equals(uname));
|
||||
|
||||
ctrlConnection.verify();
|
||||
}
|
||||
|
||||
public void testUsageWithConnectionProperties() throws Exception {
|
||||
final String jdbcUrl = "url";
|
||||
|
||||
final Properties connProps = new Properties();
|
||||
connProps.setProperty("myProp", "myValue");
|
||||
connProps.setProperty("yourProp", "yourValue");
|
||||
connProps.setProperty("user", "uname");
|
||||
connProps.setProperty("password", "pwd");
|
||||
|
||||
MockControl ctrlConnection =
|
||||
MockControl.createControl(Connection.class);
|
||||
final Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
ctrlConnection.replay();
|
||||
|
||||
class TestDriverManagerDataSource extends DriverManagerDataSource {
|
||||
protected Connection getConnectionFromDriverManager(String url, Properties props) {
|
||||
assertEquals(jdbcUrl, url);
|
||||
assertEquals("uname", props.getProperty("user"));
|
||||
assertEquals("pwd", props.getProperty("password"));
|
||||
assertEquals("myValue", props.getProperty("myProp"));
|
||||
assertEquals("yourValue", props.getProperty("yourProp"));
|
||||
return mockConnection;
|
||||
}
|
||||
}
|
||||
|
||||
DriverManagerDataSource ds = new TestDriverManagerDataSource();
|
||||
//ds.setDriverClassName("foobar");
|
||||
ds.setUrl(jdbcUrl);
|
||||
ds.setConnectionProperties(connProps);
|
||||
|
||||
Connection actualCon = ds.getConnection();
|
||||
assertTrue(actualCon == mockConnection);
|
||||
|
||||
assertTrue(ds.getUrl().equals(jdbcUrl));
|
||||
|
||||
ctrlConnection.verify();
|
||||
}
|
||||
|
||||
public void testUsageWithConnectionPropertiesAndUserCredentials() throws Exception {
|
||||
final String jdbcUrl = "url";
|
||||
final String uname = "uname";
|
||||
final String pwd = "pwd";
|
||||
|
||||
final Properties connProps = new Properties();
|
||||
connProps.setProperty("myProp", "myValue");
|
||||
connProps.setProperty("yourProp", "yourValue");
|
||||
connProps.setProperty("user", "uname2");
|
||||
connProps.setProperty("password", "pwd2");
|
||||
|
||||
MockControl ctrlConnection =
|
||||
MockControl.createControl(Connection.class);
|
||||
final Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
ctrlConnection.replay();
|
||||
|
||||
class TestDriverManagerDataSource extends DriverManagerDataSource {
|
||||
protected Connection getConnectionFromDriverManager(String url, Properties props) {
|
||||
assertEquals(jdbcUrl, url);
|
||||
assertEquals(uname, props.getProperty("user"));
|
||||
assertEquals(pwd, props.getProperty("password"));
|
||||
assertEquals("myValue", props.getProperty("myProp"));
|
||||
assertEquals("yourValue", props.getProperty("yourProp"));
|
||||
return mockConnection;
|
||||
}
|
||||
}
|
||||
|
||||
DriverManagerDataSource ds = new TestDriverManagerDataSource();
|
||||
//ds.setDriverClassName("foobar");
|
||||
ds.setUrl(jdbcUrl);
|
||||
ds.setUsername(uname);
|
||||
ds.setPassword(pwd);
|
||||
ds.setConnectionProperties(connProps);
|
||||
|
||||
Connection actualCon = ds.getConnection();
|
||||
assertTrue(actualCon == mockConnection);
|
||||
|
||||
assertTrue(ds.getUrl().equals(jdbcUrl));
|
||||
assertTrue(ds.getPassword().equals(pwd));
|
||||
assertTrue(ds.getUsername().equals(uname));
|
||||
|
||||
ctrlConnection.verify();
|
||||
}
|
||||
|
||||
public void testInvalidClassName() throws Exception {
|
||||
String bogusClassName = "foobar";
|
||||
DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
try {
|
||||
ds.setDriverClassName(bogusClassName);
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// OK
|
||||
assertTrue(ex.getCause() instanceof ClassNotFoundException);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.springframework.jdbc.datasource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
public class TestDataSourceWrapper extends AbstractDataSource {
|
||||
|
||||
private DataSource target;
|
||||
|
||||
public void setTarget(DataSource target) {
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
public Connection getConnection() throws SQLException {
|
||||
return target.getConnection();
|
||||
}
|
||||
|
||||
public Connection getConnection(String username, String password) throws SQLException {
|
||||
return target.getConnection(username, password);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.datasource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 28.05.2004
|
||||
*/
|
||||
public class UserCredentialsDataSourceAdapterTests extends TestCase {
|
||||
|
||||
public void testStaticCredentials() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection("user", "pw");
|
||||
dsControl.setReturnValue(con);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
|
||||
adapter.setTargetDataSource(ds);
|
||||
adapter.setUsername("user");
|
||||
adapter.setPassword("pw");
|
||||
assertEquals(con, adapter.getConnection());
|
||||
}
|
||||
|
||||
public void testNoCredentials() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
|
||||
adapter.setTargetDataSource(ds);
|
||||
assertEquals(con, adapter.getConnection());
|
||||
}
|
||||
|
||||
public void testThreadBoundCredentials() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
ds.getConnection("user", "pw");
|
||||
dsControl.setReturnValue(con);
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
|
||||
UserCredentialsDataSourceAdapter adapter = new UserCredentialsDataSourceAdapter();
|
||||
adapter.setTargetDataSource(ds);
|
||||
|
||||
adapter.setCredentialsForCurrentThread("user", "pw");
|
||||
try {
|
||||
assertEquals(con, adapter.getConnection());
|
||||
}
|
||||
finally {
|
||||
adapter.removeCredentialsFromCurrentThread();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.jdbc.datasource.embedded;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.core.io.ClassRelativeResourceLoader;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.init.CannotReadScriptException;
|
||||
|
||||
/**
|
||||
* @author Keith Donald
|
||||
*/
|
||||
public class EmbeddedDatabaseBuilderTests {
|
||||
|
||||
@Test
|
||||
public void testBuildDefaultScripts() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
|
||||
EmbeddedDatabase db = builder.addDefaultScripts().build();
|
||||
assertDatabaseCreatedAndShutdown(db);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuild() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()));
|
||||
EmbeddedDatabase db = builder.addScript("db-schema.sql").addScript("db-test-data.sql").build();
|
||||
assertDatabaseCreatedAndShutdown(db);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithComments() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()));
|
||||
EmbeddedDatabase db = builder.addScript("db-schema-comments.sql").addScript("db-test-data.sql").build();
|
||||
assertDatabaseCreatedAndShutdown(db);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildH2() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()));
|
||||
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("db-schema.sql").addScript("db-test-data.sql").build();
|
||||
assertDatabaseCreatedAndShutdown(db);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildDerby() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(new ClassRelativeResourceLoader(getClass()));
|
||||
EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.DERBY).addScript("db-schema-derby.sql").addScript("db-test-data.sql").build();
|
||||
assertDatabaseCreatedAndShutdown(db);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildNoSuchScript() {
|
||||
try {
|
||||
new EmbeddedDatabaseBuilder().addScript("bogus.sql").build();
|
||||
fail("Should have failed");
|
||||
}
|
||||
catch (DataAccessResourceFailureException ex) {
|
||||
assertTrue(ex.getCause() instanceof CannotReadScriptException);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertDatabaseCreatedAndShutdown(EmbeddedDatabase db) {
|
||||
JdbcTemplate template = new JdbcTemplate(db);
|
||||
assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class));
|
||||
db.shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package org.springframework.jdbc.datasource.embedded;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
|
||||
|
||||
public class EmbeddedDatabaseFactoryBeanTests {
|
||||
|
||||
@Test
|
||||
public void testFactoryBeanLifecycle() throws Exception {
|
||||
EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean();
|
||||
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
|
||||
populator.setScripts(new Resource[] {
|
||||
new ClassPathResource("db-schema.sql", getClass()),
|
||||
new ClassPathResource("db-test-data.sql", getClass())
|
||||
});
|
||||
bean.setDatabasePopulator(populator);
|
||||
bean.afterPropertiesSet();
|
||||
DataSource ds = bean.getObject();
|
||||
JdbcTemplate template = new JdbcTemplate(ds);
|
||||
assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class));
|
||||
bean.destroy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.springframework.jdbc.datasource.embedded;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.jdbc.datasource.init.DatabasePopulator;
|
||||
|
||||
public class EmbeddedDatabaseFactoryTests {
|
||||
|
||||
private EmbeddedDatabaseFactory factory = new EmbeddedDatabaseFactory();
|
||||
|
||||
@Test
|
||||
public void testGetDataSource() {
|
||||
StubDatabasePopulator populator = new StubDatabasePopulator();
|
||||
factory.setDatabasePopulator(populator);
|
||||
EmbeddedDatabase db = factory.getDatabase();
|
||||
assertTrue(populator.populateCalled);
|
||||
db.shutdown();
|
||||
}
|
||||
|
||||
private static class StubDatabasePopulator implements DatabasePopulator {
|
||||
|
||||
private boolean populateCalled;
|
||||
|
||||
public void populate(Connection connection) {
|
||||
this.populateCalled = true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.jdbc.datasource.init;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.sql.Connection;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.io.ClassRelativeResourceLoader;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
* @author Sam Brannen
|
||||
*/
|
||||
public class DatabasePopulatorTests {
|
||||
|
||||
private final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
|
||||
private final EmbeddedDatabase db = builder.build();
|
||||
private final ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
|
||||
private final ClassRelativeResourceLoader resourceLoader = new ClassRelativeResourceLoader(getClass());
|
||||
private final JdbcTemplate jdbcTemplate = new JdbcTemplate(db);
|
||||
|
||||
private void assertTestDatabaseCreated() {
|
||||
assertTestDatabaseCreated("Keith");
|
||||
}
|
||||
|
||||
private void assertTestDatabaseCreated(String name) {
|
||||
assertEquals(name, jdbcTemplate.queryForObject("select NAME from T_TEST", String.class));
|
||||
}
|
||||
|
||||
private void assertUsersDatabaseCreated(DataSource db) {
|
||||
assertEquals("Sam", jdbcTemplate.queryForObject("select first_name from users where last_name = 'Brannen'",
|
||||
String.class));
|
||||
}
|
||||
|
||||
@After
|
||||
public void shutDown() {
|
||||
db.shutdown();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithCommentsAndFailedDrop() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema-failed-drop-comments.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data.sql"));
|
||||
databasePopulator.setIgnoreFailedDrops(true);
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertTestDatabaseCreated();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithNormalEscapedLiteral() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-escaped-literal.sql"));
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertTestDatabaseCreated("'Keith'");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithMySQLEscapedLiteral() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-mysql-escaped-literal.sql"));
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertTestDatabaseCreated("\\$Keith\\$");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithMultipleStatements() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-multiple.sql"));
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'"));
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithMultipleStatementsLongSeparator() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-endings.sql"));
|
||||
databasePopulator.setSeparator("@@");
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'"));
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithMultipleStatementsWhitespaceSeparator() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-whitespace.sql"));
|
||||
databasePopulator.setSeparator("/\n");
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'"));
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithMultipleStatementsNewlineSeparator() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-newline.sql"));
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'"));
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBuildWithMultipleStatementsMultipleNewlineSeparator() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("db-test-data-multi-newline.sql"));
|
||||
databasePopulator.setSeparator("\n\n");
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Keith'"));
|
||||
assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void scriptWithEolBetweenTokens() throws Exception {
|
||||
databasePopulator.addScript(resourceLoader.getResource("users-schema.sql"));
|
||||
databasePopulator.addScript(resourceLoader.getResource("users-data.sql"));
|
||||
Connection connection = db.getConnection();
|
||||
try {
|
||||
databasePopulator.populate(connection);
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
|
||||
assertUsersDatabaseCreated(db);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc.datasource.lookup;
|
||||
|
||||
import static org.easymock.EasyMock.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public class BeanFactoryDataSourceLookupTests {
|
||||
|
||||
private static final String DATASOURCE_BEAN_NAME = "dataSource";
|
||||
|
||||
|
||||
@Test
|
||||
public void testLookupSunnyDay() {
|
||||
BeanFactory beanFactory = createMock(BeanFactory.class);
|
||||
|
||||
StubDataSource expectedDataSource = new StubDataSource();
|
||||
expect(beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)).andReturn(expectedDataSource);
|
||||
|
||||
replay(beanFactory);
|
||||
|
||||
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
|
||||
lookup.setBeanFactory(beanFactory);
|
||||
DataSource dataSource = lookup.getDataSource(DATASOURCE_BEAN_NAME);
|
||||
assertNotNull("A DataSourceLookup implementation must *never* return null from " +
|
||||
"getDataSource(): this one obviously (and incorrectly) is", dataSource);
|
||||
assertSame(expectedDataSource, dataSource);
|
||||
|
||||
verify(beanFactory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLookupWhereBeanFactoryYieldsNonDataSourceType() throws Exception {
|
||||
final BeanFactory beanFactory = createMock(BeanFactory.class);
|
||||
|
||||
expect(
|
||||
beanFactory.getBean(DATASOURCE_BEAN_NAME, DataSource.class)
|
||||
).andThrow(new BeanNotOfRequiredTypeException(DATASOURCE_BEAN_NAME, DataSource.class, String.class));
|
||||
|
||||
replay(beanFactory);
|
||||
|
||||
try {
|
||||
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup(beanFactory);
|
||||
lookup.getDataSource(DATASOURCE_BEAN_NAME);
|
||||
fail("should have thrown DataSourceLookupFailureException");
|
||||
} catch (DataSourceLookupFailureException ex) { /* expected */ }
|
||||
|
||||
verify(beanFactory);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalStateException.class)
|
||||
public void testLookupWhereBeanFactoryHasNotBeenSupplied() throws Exception {
|
||||
BeanFactoryDataSourceLookup lookup = new BeanFactoryDataSourceLookup();
|
||||
lookup.getDataSource(DATASOURCE_BEAN_NAME);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.jdbc.datasource.lookup;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public final class JndiDataSourceLookupTests {
|
||||
|
||||
private static final String DATA_SOURCE_NAME = "Love is like a stove, burns you when it's hot";
|
||||
|
||||
@Test
|
||||
public void testSunnyDay() throws Exception {
|
||||
final DataSource expectedDataSource = new StubDataSource();
|
||||
JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
|
||||
@SuppressWarnings("unchecked")
|
||||
protected Object lookup(String jndiName, Class requiredType) {
|
||||
assertEquals(DATA_SOURCE_NAME, jndiName);
|
||||
return expectedDataSource;
|
||||
}
|
||||
};
|
||||
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
|
||||
assertSame(expectedDataSource, dataSource);
|
||||
}
|
||||
|
||||
@Test(expected=DataSourceLookupFailureException.class)
|
||||
public void testNoDataSourceAtJndiLocation() throws Exception {
|
||||
JndiDataSourceLookup lookup = new JndiDataSourceLookup() {
|
||||
@SuppressWarnings("unchecked")
|
||||
protected Object lookup(String jndiName, Class requiredType) throws NamingException {
|
||||
assertEquals(DATA_SOURCE_NAME, jndiName);
|
||||
throw new NamingException();
|
||||
}
|
||||
};
|
||||
lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.jdbc.datasource.lookup;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public final class MapDataSourceLookupTests {
|
||||
|
||||
private static final String DATA_SOURCE_NAME = "dataSource";
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test(expected=UnsupportedOperationException.class)
|
||||
public void testGetDataSourcesReturnsUnmodifiableMap() throws Exception {
|
||||
MapDataSourceLookup lookup = new MapDataSourceLookup(new HashMap());
|
||||
Map dataSources = lookup.getDataSources();
|
||||
dataSources.put("", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLookupSunnyDay() throws Exception {
|
||||
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
|
||||
StubDataSource expectedDataSource = new StubDataSource();
|
||||
dataSources.put(DATA_SOURCE_NAME, expectedDataSource);
|
||||
MapDataSourceLookup lookup = new MapDataSourceLookup();
|
||||
lookup.setDataSources(dataSources);
|
||||
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
|
||||
assertSame(expectedDataSource, dataSource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSettingDataSourceMapToNullIsAnIdempotentOperation() throws Exception {
|
||||
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
|
||||
StubDataSource expectedDataSource = new StubDataSource();
|
||||
dataSources.put(DATA_SOURCE_NAME, expectedDataSource);
|
||||
MapDataSourceLookup lookup = new MapDataSourceLookup();
|
||||
lookup.setDataSources(dataSources);
|
||||
lookup.setDataSources(null); // must be idempotent (i.e. the following lookup must still work);
|
||||
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
|
||||
assertSame(expectedDataSource, dataSource);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddingDataSourcePermitsOverride() throws Exception {
|
||||
Map<String, DataSource> dataSources = new HashMap<String, DataSource>();
|
||||
StubDataSource overridenDataSource = new StubDataSource();
|
||||
StubDataSource expectedDataSource = new StubDataSource();
|
||||
dataSources.put(DATA_SOURCE_NAME, overridenDataSource);
|
||||
MapDataSourceLookup lookup = new MapDataSourceLookup();
|
||||
lookup.setDataSources(dataSources);
|
||||
lookup.addDataSource(DATA_SOURCE_NAME, expectedDataSource); // must override existing entry
|
||||
DataSource dataSource = lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
assertNotNull("A DataSourceLookup implementation must *never* return null from getDataSource(): this one obviously (and incorrectly) is", dataSource);
|
||||
assertSame(expectedDataSource, dataSource);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test(expected=ClassCastException.class)
|
||||
public void testGetDataSourceWhereSuppliedMapHasNonDataSourceTypeUnderSpecifiedKey() throws Exception {
|
||||
Map dataSources = new HashMap();
|
||||
dataSources.put(DATA_SOURCE_NAME, new Object());
|
||||
MapDataSourceLookup lookup = new MapDataSourceLookup();
|
||||
lookup.setDataSources(dataSources);
|
||||
lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
}
|
||||
|
||||
@Test(expected=DataSourceLookupFailureException.class)
|
||||
public void testGetDataSourceWhereSuppliedMapHasNoEntryForSpecifiedKey() throws Exception {
|
||||
MapDataSourceLookup lookup = new MapDataSourceLookup();
|
||||
lookup.getDataSource(DATA_SOURCE_NAME);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc.datasource.lookup;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.springframework.jdbc.datasource.AbstractDataSource;
|
||||
|
||||
/**
|
||||
* Stub, do-nothing DataSource implementation.
|
||||
*
|
||||
* <p>All methods throw {@link UnsupportedOperationException}.
|
||||
*
|
||||
* @author Rick Evans
|
||||
*/
|
||||
class StubDataSource extends AbstractDataSource {
|
||||
|
||||
public Connection getConnection() throws SQLException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Connection getConnection(String username, String password) throws SQLException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.object;
|
||||
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Types;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 22.02.2005
|
||||
*/
|
||||
public class BatchSqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
|
||||
public void testBatchUpdateWithExplicitFlush() throws Exception {
|
||||
doTestBatchUpdate(false);
|
||||
}
|
||||
|
||||
public void testBatchUpdateWithFlushThroughBatchSize() throws Exception {
|
||||
doTestBatchUpdate(true);
|
||||
}
|
||||
|
||||
private void doTestBatchUpdate(boolean flushThroughBatchSize) throws Exception {
|
||||
final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
|
||||
final int[] ids = new int[] { 100, 200 };
|
||||
final int[] rowsAffected = new int[] { 1, 2 };
|
||||
|
||||
MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
mockPreparedStatement.getConnection();
|
||||
ctrlPreparedStatement.setReturnValue(mockConnection);
|
||||
mockPreparedStatement.setObject(1, new Integer(ids[0]), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.addBatch();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.setObject(1, new Integer(ids[1]), Types.INTEGER);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.addBatch();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeBatch();
|
||||
ctrlPreparedStatement.setReturnValue(rowsAffected);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();
|
||||
mockDatabaseMetaData.supportsBatchUpdates();
|
||||
ctrlDatabaseMetaData.setReturnValue(true);
|
||||
|
||||
mockConnection.prepareStatement(sql);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(mockDatabaseMetaData, 1);
|
||||
|
||||
ctrlPreparedStatement.replay();
|
||||
ctrlDatabaseMetaData.replay();
|
||||
replay();
|
||||
|
||||
BatchSqlUpdate update = new BatchSqlUpdate(mockDataSource, sql);
|
||||
update.declareParameter(new SqlParameter(Types.INTEGER));
|
||||
if (flushThroughBatchSize) {
|
||||
update.setBatchSize(2);
|
||||
}
|
||||
|
||||
update.update(ids[0]);
|
||||
update.update(ids[1]);
|
||||
|
||||
if (flushThroughBatchSize) {
|
||||
assertEquals(0, update.getQueueCount());
|
||||
assertEquals(2, update.getRowsAffected().length);
|
||||
}
|
||||
else {
|
||||
assertEquals(2, update.getQueueCount());
|
||||
assertEquals(0, update.getRowsAffected().length);
|
||||
}
|
||||
|
||||
int[] actualRowsAffected = update.flush();
|
||||
assertEquals(0, update.getQueueCount());
|
||||
|
||||
if (flushThroughBatchSize) {
|
||||
assertTrue("flush did not execute updates", actualRowsAffected.length == 0);
|
||||
}
|
||||
else {
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
}
|
||||
|
||||
actualRowsAffected = update.getRowsAffected();
|
||||
assertTrue("executed 2 updates", actualRowsAffected.length == 2);
|
||||
assertEquals(rowsAffected[0], actualRowsAffected[0]);
|
||||
assertEquals(rowsAffected[1], actualRowsAffected[1]);
|
||||
|
||||
update.reset();
|
||||
assertEquals(0, update.getRowsAffected().length);
|
||||
|
||||
ctrlPreparedStatement.verify();
|
||||
ctrlDatabaseMetaData.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.springframework.jdbc.object;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.jdbc.Customer;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class CustomerMapper implements RowMapper<Customer> {
|
||||
|
||||
private static final String[] COLUMN_NAMES = new String[] {"id", "forename"};
|
||||
|
||||
public Customer mapRow(ResultSet rs, int rownum) throws SQLException {
|
||||
Customer cust = new Customer();
|
||||
cust.setId(rs.getInt(COLUMN_NAMES[0]));
|
||||
cust.setForename(rs.getString(COLUMN_NAMES[1]));
|
||||
return cust;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.object;
|
||||
|
||||
import static org.easymock.EasyMock.createMock;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.expectLastCall;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.EasyMock;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.Customer;
|
||||
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
@RunWith(JUnit4.class)
|
||||
public class GenericSqlQueryTests extends AbstractJdbcTests {
|
||||
|
||||
private static final String SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED =
|
||||
"select id, forename from custmr where id = ? and country = ?";
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private ResultSet mockResultSet;
|
||||
|
||||
private BeanFactory bf;
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
mockPreparedStatement = createMock(PreparedStatement.class);
|
||||
mockResultSet = createMock(ResultSet.class);
|
||||
this.bf = new XmlBeanFactory(
|
||||
new ClassPathResource("org/springframework/jdbc/object/GenericSqlQueryTests-context.xml"));
|
||||
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
|
||||
testDataSource.setTarget(mockDataSource);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
EasyMock.verify(mockPreparedStatement);
|
||||
EasyMock.verify(mockResultSet);
|
||||
}
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
EasyMock.replay(mockPreparedStatement);
|
||||
EasyMock.replay(mockResultSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPlaceHoldersCustomerQuery() throws SQLException {
|
||||
SqlQuery query = (SqlQuery) bf.getBean("queryWithPlaceHolders");
|
||||
testCustomerQuery(query, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNamedParameterCustomerQuery() throws SQLException {
|
||||
SqlQuery query = (SqlQuery) bf.getBean("queryWithNamedParameters");
|
||||
testCustomerQuery(query, true);
|
||||
}
|
||||
|
||||
private void testCustomerQuery(SqlQuery query, boolean namedParameters) throws SQLException {
|
||||
expect(mockResultSet.next()).andReturn(true);
|
||||
expect(mockResultSet.getInt("id")).andReturn(1);
|
||||
expect(mockResultSet.getString("forename")).andReturn("rod");
|
||||
expect(mockResultSet.next()).andReturn(false);
|
||||
mockResultSet.close();
|
||||
expectLastCall();
|
||||
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.INTEGER);
|
||||
expectLastCall();
|
||||
mockPreparedStatement.setString(2, "UK");
|
||||
expectLastCall();
|
||||
expect(mockPreparedStatement.executeQuery()).andReturn(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
expect(mockPreparedStatement.getWarnings()).andReturn(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
expectLastCall();
|
||||
|
||||
mockConnection.prepareStatement(SELECT_ID_FORENAME_NAMED_PARAMETERS_PARSED);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
List l;
|
||||
if (namedParameters) {
|
||||
Map<String, Object> params = new HashMap<String, Object>(2);
|
||||
params.put("id", new Integer(1));
|
||||
params.put("country", "UK");
|
||||
l = query.executeByNamedParam(params);
|
||||
}
|
||||
else {
|
||||
Object[] params = new Object[] {new Integer(1), "UK"};
|
||||
l = query.execute(params);
|
||||
}
|
||||
assertTrue("Customer was returned correctly", l.size() == 1);
|
||||
Customer cust = (Customer) l.get(0);
|
||||
assertTrue("Customer id was assigned correctly", cust.getId() == 1);
|
||||
assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.jdbc.object;
|
||||
|
||||
import static org.easymock.EasyMock.createMock;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.expectLastCall;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.EasyMock;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.Test;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.datasource.TestDataSourceWrapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.xml.XmlBeanFactory;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
@RunWith(JUnit4.class)
|
||||
public class GenericStoredProcedureTests extends AbstractJdbcTests {
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private CallableStatement mockCallable;
|
||||
|
||||
private BeanFactory bf;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
mockCallable = createMock(CallableStatement.class);
|
||||
bf = new XmlBeanFactory(
|
||||
new ClassPathResource("org/springframework/jdbc/object/GenericStoredProcedureTests-context.xml"));
|
||||
TestDataSourceWrapper testDataSource = (TestDataSourceWrapper) bf.getBean("dataSource");
|
||||
testDataSource.setTarget(mockDataSource);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
EasyMock.verify(mockCallable);
|
||||
}
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
EasyMock.replay(mockCallable);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddInvoices() throws Exception {
|
||||
|
||||
mockCallable.setObject(1, new Integer(1106), Types.INTEGER);
|
||||
expectLastCall();
|
||||
mockCallable.setObject(2, new Integer(3), Types.INTEGER);
|
||||
expectLastCall();
|
||||
mockCallable.registerOutParameter(3, Types.INTEGER);
|
||||
expectLastCall();
|
||||
expect(mockCallable.execute()).andReturn(false);
|
||||
expect(mockCallable.getUpdateCount()).andReturn(-1);
|
||||
expect(mockCallable.getObject(3)).andReturn(new Integer(4));
|
||||
if (debugEnabled) {
|
||||
expect(mockCallable.getWarnings()).andReturn(null);
|
||||
}
|
||||
mockCallable.close();
|
||||
expectLastCall();
|
||||
|
||||
mockConnection.prepareCall("{call " + "add_invoice" + "(?, ?, ?)}");
|
||||
ctrlConnection.setReturnValue(mockCallable);
|
||||
|
||||
replay();
|
||||
|
||||
testAddInvoice(1106, 3);
|
||||
}
|
||||
|
||||
private void testAddInvoice(final int amount, final int custid)
|
||||
throws Exception {
|
||||
|
||||
StoredProcedure adder = (StoredProcedure) bf.getBean("genericProcedure");
|
||||
Map<String, Object> in = new HashMap<String, Object>(2);
|
||||
in.put("amount", amount);
|
||||
in.put("custid", custid);
|
||||
Map out = adder.execute(in);
|
||||
Integer id = (Integer) out.get("newid");
|
||||
assertEquals(4, id.intValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc.object;
|
||||
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.SqlInOutParameter;
|
||||
import org.springframework.jdbc.core.SqlOutParameter;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
|
||||
/**
|
||||
* @author Trevor Cook
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class RdbmsOperationTests extends TestCase {
|
||||
|
||||
public void testEmptySql() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
try {
|
||||
operation.compile();
|
||||
fail("Shouldn't allow compiling without sql statement");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testSetTypeAfterCompile() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setDataSource(new DriverManagerDataSource());
|
||||
operation.setSql("select * from mytable");
|
||||
operation.compile();
|
||||
try {
|
||||
operation.setTypes(new int[] {Types.INTEGER });
|
||||
fail("Shouldn't allow setting parameters after compile");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testDeclareParameterAfterCompile() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setDataSource(new DriverManagerDataSource());
|
||||
operation.setSql("select * from mytable");
|
||||
operation.compile();
|
||||
try {
|
||||
operation.declareParameter(new SqlParameter(Types.INTEGER));
|
||||
fail("Shouldn't allow setting parameters after compile");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testTooFewParameters() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setSql("select * from mytable");
|
||||
operation.setTypes(new int[] { Types.INTEGER });
|
||||
try {
|
||||
operation.validateParameters((Object[]) null);
|
||||
fail("Shouldn't validate without enough parameters");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testTooFewMapParameters() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setSql("select * from mytable");
|
||||
operation.setTypes(new int[] { Types.INTEGER });
|
||||
try {
|
||||
operation.validateNamedParameters((Map) null);
|
||||
fail("Shouldn't validate without enough parameters");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testOperationConfiguredViaJdbcTemplateMustGetDataSource() throws Exception {
|
||||
try {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setSql("foo");
|
||||
operation.compile();
|
||||
fail("Can't compile without providing a DataSource for the JdbcTemplate");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException ex) {
|
||||
// Check for helpful error message. Omit leading character
|
||||
// so as not to be fussy about case
|
||||
assertTrue(ex.getMessage().indexOf("ataSource") != -1);
|
||||
}
|
||||
}
|
||||
|
||||
public void testTooManyParameters() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setSql("select * from mytable");
|
||||
try {
|
||||
operation.validateParameters(new Object[] {new Integer(1), new Integer(2)});
|
||||
fail("Shouldn't validate with too many parameters");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testUnspecifiedMapParameters() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setSql("select * from mytable");
|
||||
try {
|
||||
Map params = new HashMap();
|
||||
params.put("col1", "value");
|
||||
operation.validateNamedParameters(params);
|
||||
fail("Shouldn't validate with unspecified parameters");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testCompileTwice() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setDataSource(new DriverManagerDataSource());
|
||||
operation.setSql("select * from mytable");
|
||||
operation.setTypes(null);
|
||||
operation.compile();
|
||||
operation.compile();
|
||||
}
|
||||
|
||||
public void testEmptyDataSource() {
|
||||
SqlOperation operation = new SqlOperation() {
|
||||
};
|
||||
operation.setSql("select * from mytable");
|
||||
try {
|
||||
operation.compile();
|
||||
fail("Shouldn't allow compiling without data source");
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testParameterPropagation() {
|
||||
SqlOperation operation = new SqlOperation() {
|
||||
};
|
||||
DataSource ds = new DriverManagerDataSource();
|
||||
operation.setDataSource(ds);
|
||||
operation.setFetchSize(10);
|
||||
operation.setMaxRows(20);
|
||||
JdbcTemplate jt = operation.getJdbcTemplate();
|
||||
assertEquals(ds, jt.getDataSource());
|
||||
assertEquals(10, jt.getFetchSize());
|
||||
assertEquals(20, jt.getMaxRows());
|
||||
}
|
||||
|
||||
public void testValidateInOutParameter() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
operation.setDataSource(new DriverManagerDataSource());
|
||||
operation.setSql("DUMMY_PROC");
|
||||
operation.declareParameter(new SqlOutParameter("DUMMY_OUT_PARAM", Types.VARCHAR));
|
||||
operation.declareParameter(new SqlInOutParameter("DUMMY_IN_OUT_PARAM", Types.VARCHAR));
|
||||
operation.validateParameters(new Object[] {"DUMMY_VALUE1", "DUMMY_VALUE2"});
|
||||
}
|
||||
|
||||
public void testParametersSetWithList() {
|
||||
TestRdbmsOperation operation = new TestRdbmsOperation();
|
||||
DataSource ds = new DriverManagerDataSource();
|
||||
operation.setDataSource(ds);
|
||||
operation.setSql("select * from mytable where one = ? and two = ?");
|
||||
List l = new ArrayList();
|
||||
l.add(new SqlParameter("one", Types.NUMERIC));
|
||||
l.add(new SqlParameter("two", Types.VARCHAR));
|
||||
operation.setParameters(new SqlParameter[] {
|
||||
new SqlParameter("one", Types.NUMERIC),
|
||||
new SqlParameter("two", Types.NUMERIC)});
|
||||
operation.afterPropertiesSet();
|
||||
try {
|
||||
operation.validateParameters(new Object[] {new Integer(1), new String("2")});
|
||||
assertEquals(2, operation.getDeclaredParameters().size());
|
||||
// OK
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException idaauex) {
|
||||
fail("Should have validated with parameters set using List: " + idaauex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class TestRdbmsOperation extends RdbmsOperation {
|
||||
|
||||
protected void compileInternal() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,584 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.object;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.easymock.MockControl;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.jdbc.AbstractJdbcTests;
|
||||
import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
|
||||
/**
|
||||
* @author Trevor Cook
|
||||
* @author Thomas Risberg
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class SqlUpdateTests extends AbstractJdbcTests {
|
||||
|
||||
private static final String UPDATE =
|
||||
"update seat_status set booking_id = null";
|
||||
private static final String UPDATE_INT =
|
||||
"update seat_status set booking_id = null where performance_id = ?";
|
||||
private static final String UPDATE_INT_INT =
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ?";
|
||||
private static final String UPDATE_NAMED_PARAMETERS =
|
||||
"update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId";
|
||||
private static final String UPDATE_STRING =
|
||||
"update seat_status set booking_id = null where name = ?";
|
||||
private static final String UPDATE_OBJECTS =
|
||||
"update seat_status set booking_id = null where performance_id = ? and price_band_id = ? and name = ? and confirmed = ?";
|
||||
private static final String INSERT_GENERATE_KEYS =
|
||||
"insert into show (name) values(?)";
|
||||
|
||||
private final boolean debugEnabled = LogFactory.getLog(JdbcTemplate.class).isDebugEnabled();
|
||||
|
||||
private MockControl ctrlPreparedStatement;
|
||||
private PreparedStatement mockPreparedStatement;
|
||||
private MockControl ctrlResultSet;
|
||||
private ResultSet mockResultSet;
|
||||
private MockControl ctrlResultSetMetaData;
|
||||
private ResultSetMetaData mockResultSetMetaData;
|
||||
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
|
||||
mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
if (shouldVerify()) {
|
||||
ctrlPreparedStatement.verify();
|
||||
}
|
||||
}
|
||||
|
||||
protected void replay() {
|
||||
super.replay();
|
||||
ctrlPreparedStatement.replay();
|
||||
}
|
||||
|
||||
|
||||
public void testUpdate() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
Updater pc = new Updater();
|
||||
int rowsAffected = pc.run();
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUpdateInt() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_INT);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
IntUpdater pc = new IntUpdater();
|
||||
int rowsAffected = pc.run(1);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUpdateIntInt() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_INT_INT);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
IntIntUpdater pc = new IntIntUpdater();
|
||||
int rowsAffected = pc.run(1, 1);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testNamedParameterUpdateWithUnnamedDeclarations() throws SQLException {
|
||||
doTestNamedParameterUpdate(false);
|
||||
}
|
||||
|
||||
public void testNamedParameterUpdateWithNamedDeclarations() throws SQLException {
|
||||
doTestNamedParameterUpdate(true);
|
||||
}
|
||||
|
||||
private void doTestNamedParameterUpdate(final boolean namedDeclarations) throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.DECIMAL);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_INT_INT);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
class NamedParameterUpdater extends SqlUpdate {
|
||||
|
||||
public NamedParameterUpdater() {
|
||||
setSql(UPDATE_NAMED_PARAMETERS);
|
||||
setDataSource(mockDataSource);
|
||||
if (namedDeclarations) {
|
||||
declareParameter(new SqlParameter("priceId", Types.DECIMAL));
|
||||
declareParameter(new SqlParameter("perfId", Types.NUMERIC));
|
||||
}
|
||||
else {
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
declareParameter(new SqlParameter(Types.DECIMAL));
|
||||
}
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(int performanceId, int type) {
|
||||
Map params = new HashMap();
|
||||
params.put("perfId", new Integer(performanceId));
|
||||
params.put("priceId", new Integer(type));
|
||||
return updateByNamedParam(params);
|
||||
}
|
||||
}
|
||||
|
||||
NamedParameterUpdater pc = new NamedParameterUpdater();
|
||||
int rowsAffected = pc.run(1, 1);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUpdateString() throws SQLException {
|
||||
mockPreparedStatement.setString(1, "rod");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_STRING);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
StringUpdater pc = new StringUpdater();
|
||||
int rowsAffected = pc.run("rod");
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUpdateMixed() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC, 2);
|
||||
mockPreparedStatement.setString(3, "rod");
|
||||
mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_OBJECTS);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
MixedUpdater pc = new MixedUpdater();
|
||||
int rowsAffected = pc.run(1, 1, "rod", true);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUpdateAndGeneratedKeys() throws SQLException {
|
||||
ctrlResultSetMetaData = MockControl.createControl(ResultSetMetaData.class);
|
||||
mockResultSetMetaData = (ResultSetMetaData) ctrlResultSetMetaData.getMock();
|
||||
mockResultSetMetaData.getColumnCount();
|
||||
ctrlResultSetMetaData.setReturnValue(1);
|
||||
mockResultSetMetaData.getColumnLabel(1);
|
||||
ctrlResultSetMetaData.setReturnValue("1", 2);
|
||||
|
||||
ctrlResultSet = MockControl.createControl(ResultSet.class);
|
||||
mockResultSet = (ResultSet) ctrlResultSet.getMock();
|
||||
mockResultSet.getMetaData();
|
||||
ctrlResultSet.setReturnValue(mockResultSetMetaData);
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(true);
|
||||
mockResultSet.getObject(1);
|
||||
ctrlResultSet.setReturnValue(new Integer(11));
|
||||
mockResultSet.next();
|
||||
ctrlResultSet.setReturnValue(false);
|
||||
mockResultSet.close();
|
||||
ctrlResultSet.setVoidCallable();
|
||||
|
||||
mockPreparedStatement.setString(1, "rod");
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
mockPreparedStatement.getGeneratedKeys();
|
||||
ctrlPreparedStatement.setReturnValue(mockResultSet);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(INSERT_GENERATE_KEYS, PreparedStatement.RETURN_GENERATED_KEYS);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
ctrlResultSet.replay();
|
||||
ctrlResultSetMetaData.replay();
|
||||
|
||||
GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
|
||||
KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
|
||||
int rowsAffected = pc.run("rod", generatedKeyHolder);
|
||||
assertEquals(1, rowsAffected);
|
||||
assertEquals(1, generatedKeyHolder.getKeyList().size());
|
||||
assertEquals(11, generatedKeyHolder.getKey().intValue());
|
||||
}
|
||||
|
||||
public void testUpdateConstructor() throws SQLException {
|
||||
mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
|
||||
mockPreparedStatement.setString(3, "rod");
|
||||
mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(1);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE_OBJECTS);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
ConstructorUpdater pc = new ConstructorUpdater();
|
||||
int rowsAffected = pc.run(1, 1, "rod", true);
|
||||
assertEquals(1, rowsAffected);
|
||||
}
|
||||
|
||||
public void testUnderMaxRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(3);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
MaxRowsUpdater pc = new MaxRowsUpdater();
|
||||
int rowsAffected = pc.run();
|
||||
assertEquals(3, rowsAffected);
|
||||
}
|
||||
|
||||
public void testMaxRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(5);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
MaxRowsUpdater pc = new MaxRowsUpdater();
|
||||
int rowsAffected = pc.run();
|
||||
assertEquals(5, rowsAffected);
|
||||
}
|
||||
|
||||
public void testOverMaxRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(8);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
MaxRowsUpdater pc = new MaxRowsUpdater();
|
||||
try {
|
||||
int rowsAffected = pc.run();
|
||||
fail("Shouldn't continue when too many rows affected");
|
||||
}
|
||||
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException juaicrex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
public void testRequiredRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(3);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
RequiredRowsUpdater pc = new RequiredRowsUpdater();
|
||||
int rowsAffected = pc.run();
|
||||
assertEquals(3, rowsAffected);
|
||||
}
|
||||
|
||||
public void testNotRequiredRows() throws SQLException {
|
||||
mockPreparedStatement.executeUpdate();
|
||||
ctrlPreparedStatement.setReturnValue(2);
|
||||
if (debugEnabled) {
|
||||
mockPreparedStatement.getWarnings();
|
||||
ctrlPreparedStatement.setReturnValue(null);
|
||||
}
|
||||
mockPreparedStatement.close();
|
||||
ctrlPreparedStatement.setVoidCallable();
|
||||
|
||||
mockConnection.prepareStatement(UPDATE);
|
||||
ctrlConnection.setReturnValue(mockPreparedStatement);
|
||||
|
||||
replay();
|
||||
|
||||
RequiredRowsUpdater pc = new RequiredRowsUpdater();
|
||||
try {
|
||||
int rowsAffected = pc.run();
|
||||
fail("Shouldn't continue when too many rows affected");
|
||||
}
|
||||
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException juaicrex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class Updater extends SqlUpdate {
|
||||
|
||||
public Updater() {
|
||||
setSql(UPDATE);
|
||||
setDataSource(mockDataSource);
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run() {
|
||||
return update();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class IntUpdater extends SqlUpdate {
|
||||
|
||||
public IntUpdater() {
|
||||
setSql(UPDATE_INT);
|
||||
setDataSource(mockDataSource);
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(int performanceId) {
|
||||
return update(performanceId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class IntIntUpdater extends SqlUpdate {
|
||||
|
||||
public IntIntUpdater() {
|
||||
setSql(UPDATE_INT_INT);
|
||||
setDataSource(mockDataSource);
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(int performanceId, int type) {
|
||||
return update(performanceId, type);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class StringUpdater extends SqlUpdate {
|
||||
|
||||
public StringUpdater() {
|
||||
setSql(UPDATE_STRING);
|
||||
setDataSource(mockDataSource);
|
||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(String name) {
|
||||
return update(name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class MixedUpdater extends SqlUpdate {
|
||||
|
||||
public MixedUpdater() {
|
||||
setSql(UPDATE_OBJECTS);
|
||||
setDataSource(mockDataSource);
|
||||
declareParameter(new SqlParameter(Types.NUMERIC));
|
||||
declareParameter(new SqlParameter(Types.NUMERIC, 2));
|
||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||
declareParameter(new SqlParameter(Types.BOOLEAN));
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(int performanceId, int type, String name, boolean confirmed) {
|
||||
Object[] params =
|
||||
new Object[] {new Integer(performanceId), new Integer(type), name,
|
||||
new Boolean(confirmed)};
|
||||
return update(params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class GeneratedKeysUpdater extends SqlUpdate {
|
||||
|
||||
public GeneratedKeysUpdater() {
|
||||
setSql(INSERT_GENERATE_KEYS);
|
||||
setDataSource(mockDataSource);
|
||||
declareParameter(new SqlParameter(Types.VARCHAR));
|
||||
setReturnGeneratedKeys(true);
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(String name, KeyHolder generatedKeyHolder) {
|
||||
Object[] params = new Object[] {name};
|
||||
return update(params, generatedKeyHolder);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class ConstructorUpdater extends SqlUpdate {
|
||||
|
||||
public ConstructorUpdater() {
|
||||
super(mockDataSource, UPDATE_OBJECTS,
|
||||
new int[] {Types.NUMERIC, Types.NUMERIC, Types.VARCHAR, Types.BOOLEAN });
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run(int performanceId, int type, String name, boolean confirmed) {
|
||||
Object[] params =
|
||||
new Object[] {
|
||||
new Integer(performanceId), new Integer(type), name, new Boolean(confirmed)};
|
||||
return update(params);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class MaxRowsUpdater extends SqlUpdate {
|
||||
|
||||
public MaxRowsUpdater() {
|
||||
setSql(UPDATE);
|
||||
setDataSource(mockDataSource);
|
||||
setMaxRowsAffected(5);
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run() {
|
||||
return update();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private class RequiredRowsUpdater extends SqlUpdate {
|
||||
|
||||
public RequiredRowsUpdater() {
|
||||
setSql(UPDATE);
|
||||
setDataSource(mockDataSource);
|
||||
setRequiredRowsAffected(3);
|
||||
compile();
|
||||
}
|
||||
|
||||
public int run() {
|
||||
return update();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.support;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
@SuppressWarnings("serial")
|
||||
public class CustomErrorCodeException extends DataAccessException {
|
||||
|
||||
public CustomErrorCodeException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public CustomErrorCodeException(String msg, Throwable ex) {
|
||||
super(msg, ex);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.jdbc.support;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.TransientDataAccessResourceException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Custom SQLException translation for testing.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class CustomSqlExceptionTranslator implements SQLExceptionTranslator {
|
||||
public DataAccessException translate(String task, String sql, SQLException ex) {
|
||||
if (ex.getErrorCode() == 2) {
|
||||
return new TransientDataAccessResourceException("Custom", ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.support;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementer;
|
||||
import org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementer;
|
||||
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
|
||||
import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 27.02.2004
|
||||
*/
|
||||
public class DataFieldMaxValueIncrementerTests extends TestCase {
|
||||
|
||||
public void testHsqlMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeUpdate("insert into myseq values(null)");
|
||||
stmtControl.setReturnValue(1, 6);
|
||||
stmt.executeQuery("select max(identity()) from myseq");
|
||||
stmtControl.setReturnValue(rs, 6);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 6);
|
||||
for (long i = 0; i < 6; i++) {
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(i);
|
||||
}
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(6);
|
||||
stmt.executeUpdate("delete from myseq where seq < 2");
|
||||
stmtControl.setReturnValue(1);
|
||||
stmt.executeUpdate("delete from myseq where seq < 5");
|
||||
stmtControl.setReturnValue(1);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
|
||||
HsqlMaxValueIncrementer incrementer = new HsqlMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setColumnName("seq");
|
||||
incrementer.setCacheSize(3);
|
||||
incrementer.setPaddingLength(3);
|
||||
incrementer.afterPropertiesSet();
|
||||
|
||||
assertEquals(0, incrementer.nextIntValue());
|
||||
assertEquals(1, incrementer.nextLongValue());
|
||||
assertEquals("002", incrementer.nextStringValue());
|
||||
assertEquals(3, incrementer.nextIntValue());
|
||||
assertEquals(4, incrementer.nextLongValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testMySQLMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeUpdate("update myseq set seq = last_insert_id(seq + 2)");
|
||||
stmtControl.setReturnValue(1, 2);
|
||||
stmt.executeQuery("select last_insert_id()");
|
||||
stmtControl.setReturnValue(rs, 2);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(4);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(2);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
|
||||
MySQLMaxValueIncrementer incrementer = new MySQLMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setColumnName("seq");
|
||||
incrementer.setCacheSize(2);
|
||||
incrementer.setPaddingLength(1);
|
||||
incrementer.afterPropertiesSet();
|
||||
|
||||
assertEquals(1, incrementer.nextIntValue());
|
||||
assertEquals(2, incrementer.nextLongValue());
|
||||
assertEquals("3", incrementer.nextStringValue());
|
||||
assertEquals(4, incrementer.nextLongValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testPostgreSQLSequenceMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeQuery("select nextval('myseq')");
|
||||
stmtControl.setReturnValue(rs, 2);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(10);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(12);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(2);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
|
||||
PostgreSQLSequenceMaxValueIncrementer incrementer = new PostgreSQLSequenceMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setPaddingLength(5);
|
||||
incrementer.afterPropertiesSet();
|
||||
|
||||
assertEquals("00010", incrementer.nextStringValue());
|
||||
assertEquals(12, incrementer.nextIntValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testOracleSequenceMaxValueIncrementer() throws SQLException {
|
||||
MockControl dsControl = MockControl.createControl(DataSource.class);
|
||||
DataSource ds = (DataSource) dsControl.getMock();
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
|
||||
ds.getConnection();
|
||||
dsControl.setReturnValue(con, 2);
|
||||
con.createStatement();
|
||||
conControl.setReturnValue(stmt, 2);
|
||||
stmt.executeQuery("select myseq.nextval from dual");
|
||||
stmtControl.setReturnValue(rs, 2);
|
||||
rs.next();
|
||||
rsControl.setReturnValue(true, 2);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(10);
|
||||
rs.getLong(1);
|
||||
rsControl.setReturnValue(12);
|
||||
rs.close();
|
||||
rsControl.setVoidCallable(2);
|
||||
stmt.close();
|
||||
stmtControl.setVoidCallable(2);
|
||||
con.close();
|
||||
conControl.setVoidCallable(2);
|
||||
|
||||
dsControl.replay();
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
rsControl.replay();
|
||||
|
||||
OracleSequenceMaxValueIncrementer incrementer = new OracleSequenceMaxValueIncrementer();
|
||||
incrementer.setDataSource(ds);
|
||||
incrementer.setIncrementerName("myseq");
|
||||
incrementer.setPaddingLength(2);
|
||||
incrementer.afterPropertiesSet();
|
||||
|
||||
assertEquals(10, incrementer.nextLongValue());
|
||||
assertEquals("12", incrementer.nextStringValue());
|
||||
|
||||
dsControl.verify();
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.support;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.support.lob.DefaultLobHandler;
|
||||
import org.springframework.jdbc.support.lob.LobCreator;
|
||||
import org.springframework.jdbc.support.lob.LobHandler;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 17.12.2003
|
||||
*/
|
||||
public class DefaultLobHandlerTests extends TestCase {
|
||||
|
||||
public void testGetBlobAsBytes() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getBytes(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getBlobAsBytes(rs, 1);
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testGetBlobAsBinaryStream() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getBinaryStream(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getBlobAsBinaryStream(rs, 1);
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testGetClobAsString() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getString(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getClobAsString(rs, 1);
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testGetClobAsAsciiStream() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getAsciiStream(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getClobAsAsciiStream(rs, 1);
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testGetClobAsCharacterStream() throws SQLException {
|
||||
LobHandler lobHandler = new DefaultLobHandler();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rs.getCharacterStream(1);
|
||||
rsControl.setReturnValue(null);
|
||||
rsControl.replay();
|
||||
lobHandler.getClobAsCharacterStream(rs, 1);
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testSetBlobAsBytes() throws SQLException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
byte[] content = "testContent".getBytes();
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setBytes(1, content);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setBlobAsBytes(ps, 1, content);
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
public void testSetBlobAsBinaryStream() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setBinaryStream(1, bis, 11);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setBlobAsBinaryStream(ps, 1, bis, 11);
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
public void testSetClobAsString() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
String content = "testContent";
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setString(1, content);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setClobAsString(ps, 1, content);
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
public void testSetClobAsAsciiStream() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
InputStream bis = new ByteArrayInputStream("testContent".getBytes());
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setAsciiStream(1, bis, 11);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setClobAsAsciiStream(ps, 1, bis, 11);
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
public void testSetClobAsCharacterStream() throws SQLException, IOException {
|
||||
LobCreator lobCreator = (new DefaultLobHandler()).getLobCreator();
|
||||
Reader str = new StringReader("testContent");
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
ps.setCharacterStream(1, str, 11);
|
||||
psControl.replay();
|
||||
|
||||
lobCreator.setClobAsCharacterStream(ps, 1, str, 11);
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.jdbc.support;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Unit tests for JdbcUtils.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class JdbcUtilsTests extends TestCase {
|
||||
|
||||
public void testCommonDatabaseName() {
|
||||
assertEquals("Wrong db name", "Oracle", JdbcUtils.commonDatabaseName("Oracle"));
|
||||
assertEquals("Wrong db name", "DB2", JdbcUtils.commonDatabaseName("DB2-for-Spring"));
|
||||
assertEquals("Wrong db name", "Sybase", JdbcUtils.commonDatabaseName("Sybase SQL Server"));
|
||||
assertEquals("Wrong db name", "Sybase", JdbcUtils.commonDatabaseName("Adaptive Server Enterprise"));
|
||||
assertEquals("Wrong db name", "MySQL", JdbcUtils.commonDatabaseName("MySQL"));
|
||||
}
|
||||
|
||||
public void testConvertUnderscoreNameToPropertyName() {
|
||||
assertEquals("Wrong property name", "myName", JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME"));
|
||||
assertEquals("Wrong property name", "yourName", JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME"));
|
||||
assertEquals("Wrong property name", "AName", JdbcUtils.convertUnderscoreNameToPropertyName("a_name"));
|
||||
assertEquals("Wrong property name", "someoneElsesName", JdbcUtils.convertUnderscoreNameToPropertyName("someone_elses_name"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.support;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.dao.DataRetrievalFailureException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests for the KeyHolder and GeneratedKeyHolder
|
||||
* and it appears that JdbcUtils doesn't work exactly as documented.
|
||||
*
|
||||
* @author trisberg
|
||||
* @since Jul 18, 2004
|
||||
*/
|
||||
public class KeyHolderTests extends TestCase {
|
||||
private KeyHolder kh;
|
||||
|
||||
public void setUp() {
|
||||
kh = new GeneratedKeyHolder();
|
||||
}
|
||||
|
||||
public void testSingleKey(){
|
||||
LinkedList l = new LinkedList();
|
||||
HashMap m = new HashMap(1);
|
||||
m.put("key", new Integer(1));
|
||||
l.add(m);
|
||||
kh.getKeyList().addAll(l);
|
||||
assertEquals("single key should be returned", 1, kh.getKey().intValue());
|
||||
}
|
||||
|
||||
public void testSingleKeyNonNumeric(){
|
||||
LinkedList l = new LinkedList();
|
||||
HashMap m = new HashMap(1);
|
||||
m.put("key", "1");
|
||||
l.add(m);
|
||||
kh.getKeyList().addAll(l);
|
||||
try {
|
||||
kh.getKey().intValue();
|
||||
}
|
||||
catch (DataRetrievalFailureException e) {
|
||||
assertTrue(e.getMessage().startsWith("The generated key is not of a supported numeric type."));
|
||||
}
|
||||
}
|
||||
|
||||
public void testNoKeyReturnedInMap(){
|
||||
LinkedList l = new LinkedList();
|
||||
HashMap m = new HashMap();
|
||||
l.add(m);
|
||||
kh.getKeyList().addAll(l);
|
||||
try {
|
||||
kh.getKey();
|
||||
}
|
||||
catch (DataRetrievalFailureException e) {
|
||||
assertTrue(e.getMessage().startsWith("Unable to retrieve the generated key."));
|
||||
}
|
||||
}
|
||||
|
||||
public void testMultipleKeys(){
|
||||
LinkedList l = new LinkedList();
|
||||
HashMap m = new HashMap(1);
|
||||
m.put("key", new Integer(1));
|
||||
m.put("seq", new Integer(2));
|
||||
l.add(m);
|
||||
kh.getKeyList().addAll(l);
|
||||
Map keyMap = kh.getKeys();
|
||||
assertEquals("two keys should be in the map", 2, keyMap.size());
|
||||
try {
|
||||
kh.getKey();
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException e) {
|
||||
assertTrue(e.getMessage().startsWith("The getKey method should only be used when a single key is returned."));
|
||||
}
|
||||
}
|
||||
|
||||
public void testMultipleKeyRows(){
|
||||
LinkedList l = new LinkedList();
|
||||
HashMap m = new HashMap(1);
|
||||
m.put("key", new Integer(1));
|
||||
m.put("seq", new Integer(2));
|
||||
l.add(m);
|
||||
l.add(m);
|
||||
kh.getKeyList().addAll(l);
|
||||
|
||||
assertEquals("two rows should be in the list", 2, kh.getKeyList().size());
|
||||
try {
|
||||
kh.getKeys();
|
||||
}
|
||||
catch (InvalidDataAccessApiUsageException e) {
|
||||
assertTrue(e.getMessage().startsWith("The getKeys method should only be used when keys for a single row are returned."));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.jdbc.support;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor;
|
||||
import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor;
|
||||
|
||||
/**
|
||||
* @author Andre Biryukov
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class NativeJdbcExtractorTests extends TestCase {
|
||||
|
||||
public void testSimpleNativeJdbcExtractor() throws SQLException {
|
||||
SimpleNativeJdbcExtractor extractor = new SimpleNativeJdbcExtractor();
|
||||
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl dbmdControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData dbmd = (DatabaseMetaData) dbmdControl.getMock();
|
||||
MockControl con2Control = MockControl.createControl(Connection.class);
|
||||
Connection con2 = (Connection) con2Control.getMock();
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(dbmd, 2);
|
||||
dbmd.getConnection();
|
||||
dbmdControl.setReturnValue(con2, 2);
|
||||
conControl.replay();
|
||||
dbmdControl.replay();
|
||||
con2Control.replay();
|
||||
|
||||
Connection nativeCon = extractor.getNativeConnection(con);
|
||||
assertEquals(con2, nativeCon);
|
||||
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
stmt.getConnection();
|
||||
stmtControl.setReturnValue(con);
|
||||
stmtControl.replay();
|
||||
|
||||
nativeCon = extractor.getNativeConnectionFromStatement(stmt);
|
||||
assertEquals(con2, nativeCon);
|
||||
|
||||
Statement nativeStmt = extractor.getNativeStatement(stmt);
|
||||
assertEquals(nativeStmt, stmt);
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
psControl.replay();
|
||||
|
||||
PreparedStatement nativePs = extractor.getNativePreparedStatement(ps);
|
||||
assertEquals(ps, nativePs);
|
||||
|
||||
MockControl csControl = MockControl.createControl(CallableStatement.class);
|
||||
CallableStatement cs = (CallableStatement) csControl.getMock();
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
cs.getResultSet();
|
||||
csControl.setReturnValue(rs);
|
||||
csControl.replay();
|
||||
rsControl.replay();
|
||||
|
||||
CallableStatement nativeCs = extractor.getNativeCallableStatement(cs);
|
||||
assertEquals(cs, nativeCs);
|
||||
|
||||
ResultSet nativeRs = extractor.getNativeResultSet(cs.getResultSet());
|
||||
assertEquals(nativeRs, rs);
|
||||
|
||||
conControl.verify();
|
||||
dbmdControl.verify();
|
||||
con2Control.verify();
|
||||
stmtControl.verify();
|
||||
psControl.verify();
|
||||
csControl.verify();
|
||||
rsControl.verify();
|
||||
}
|
||||
|
||||
public void testCommonsDbcpNativeJdbcExtractor() throws SQLException {
|
||||
CommonsDbcpNativeJdbcExtractor extractor = new CommonsDbcpNativeJdbcExtractor();
|
||||
assertFalse(extractor.isNativeConnectionNecessaryForNativeStatements());
|
||||
|
||||
MockControl conControl = MockControl.createControl(Connection.class);
|
||||
Connection con = (Connection) conControl.getMock();
|
||||
MockControl stmtControl = MockControl.createControl(Statement.class);
|
||||
Statement stmt = (Statement) stmtControl.getMock();
|
||||
con.getMetaData();
|
||||
conControl.setReturnValue(null, 2);
|
||||
stmt.getConnection();
|
||||
stmtControl.setReturnValue(con, 1);
|
||||
conControl.replay();
|
||||
stmtControl.replay();
|
||||
|
||||
Connection nativeConnection = extractor.getNativeConnection(con);
|
||||
assertEquals(con, nativeConnection);
|
||||
|
||||
nativeConnection = extractor.getNativeConnectionFromStatement(stmt);
|
||||
assertEquals(con, nativeConnection);
|
||||
assertEquals(stmt, extractor.getNativeStatement(stmt));
|
||||
|
||||
MockControl psControl = MockControl.createControl(PreparedStatement.class);
|
||||
PreparedStatement ps = (PreparedStatement) psControl.getMock();
|
||||
psControl.replay();
|
||||
assertEquals(ps, extractor.getNativePreparedStatement(ps));
|
||||
|
||||
MockControl csControl = MockControl.createControl(CallableStatement.class);
|
||||
CallableStatement cs = (CallableStatement) csControl.getMock();
|
||||
csControl.replay();
|
||||
assertEquals(cs, extractor.getNativePreparedStatement(cs));
|
||||
|
||||
MockControl rsControl = MockControl.createControl(ResultSet.class);
|
||||
ResultSet rs = (ResultSet) rsControl.getMock();
|
||||
rsControl.replay();
|
||||
assertEquals(rs, extractor.getNativeResultSet(rs));
|
||||
|
||||
conControl.verify();
|
||||
stmtControl.verify();
|
||||
psControl.verify();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.support;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.BatchUpdateException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.dao.CannotAcquireLockException;
|
||||
import org.springframework.dao.CannotSerializeTransactionException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.DeadlockLoserDataAccessException;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.InvalidResultSetAccessException;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase {
|
||||
|
||||
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
|
||||
static {
|
||||
ERROR_CODES.setBadSqlGrammarCodes(new String[] { "1", "2" });
|
||||
ERROR_CODES.setInvalidResultSetAccessCodes(new String[] { "3", "4" });
|
||||
ERROR_CODES.setDuplicateKeyCodes(new String[] {"10"});
|
||||
ERROR_CODES.setDataAccessResourceFailureCodes(new String[] { "5" });
|
||||
ERROR_CODES.setDataIntegrityViolationCodes(new String[] { "6" });
|
||||
ERROR_CODES.setCannotAcquireLockCodes(new String[] { "7" });
|
||||
ERROR_CODES.setDeadlockLoserCodes(new String[] { "8" });
|
||||
ERROR_CODES.setCannotSerializeTransactionCodes(new String[] { "9" });
|
||||
}
|
||||
|
||||
public void testErrorCodeTranslation() {
|
||||
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
|
||||
|
||||
SQLException badSqlEx = new SQLException("", "", 1);
|
||||
BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
|
||||
assertEquals("SQL", bsgex.getSql());
|
||||
assertEquals(badSqlEx, bsgex.getSQLException());
|
||||
|
||||
SQLException invResEx = new SQLException("", "", 4);
|
||||
InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
|
||||
assertEquals("SQL", irsex.getSql());
|
||||
assertEquals(invResEx, irsex.getSQLException());
|
||||
|
||||
checkTranslation(sext, 5, DataAccessResourceFailureException.class);
|
||||
checkTranslation(sext, 6, DataIntegrityViolationException.class);
|
||||
checkTranslation(sext, 7, CannotAcquireLockException.class);
|
||||
checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
|
||||
checkTranslation(sext, 9, CannotSerializeTransactionException.class);
|
||||
checkTranslation(sext, 10, DuplicateKeyException.class);
|
||||
|
||||
SQLException dupKeyEx = new SQLException("", "", 10);
|
||||
DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
|
||||
assertTrue("Not instance of DataIntegrityViolationException",
|
||||
DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));
|
||||
|
||||
// Test fallback. We assume that no database will ever return this error code,
|
||||
// but 07xxx will be bad grammar picked up by the fallback SQLState translator
|
||||
SQLException sex = new SQLException("", "07xxx", 666666666);
|
||||
BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
|
||||
assertEquals("SQL2", bsgex2.getSql());
|
||||
assertEquals(sex, bsgex2.getSQLException());
|
||||
}
|
||||
|
||||
private void checkTranslation(SQLExceptionTranslator sext, int errorCode, Class exClass) {
|
||||
SQLException sex = new SQLException("", "", errorCode);
|
||||
DataAccessException ex = sext.translate("", "", sex);
|
||||
assertTrue(exClass.isInstance(ex));
|
||||
assertTrue(ex.getCause() == sex);
|
||||
}
|
||||
|
||||
public void testBatchExceptionTranslation() {
|
||||
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
|
||||
|
||||
SQLException badSqlEx = new SQLException("", "", 1);
|
||||
BatchUpdateException batchUdateEx = new BatchUpdateException();
|
||||
batchUdateEx.setNextException(badSqlEx);
|
||||
BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUdateEx);
|
||||
assertEquals("SQL", bsgex.getSql());
|
||||
assertEquals(badSqlEx, bsgex.getSQLException());
|
||||
}
|
||||
|
||||
|
||||
public void testCustomTranslateMethodTranslation() {
|
||||
final String TASK = "TASK";
|
||||
final String SQL = "SQL SELECT *";
|
||||
final DataAccessException customDex = new DataAccessException("") {};
|
||||
|
||||
final SQLException badSqlEx = new SQLException("", "", 1);
|
||||
SQLException intVioEx = new SQLException("", "", 6);
|
||||
|
||||
SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator() {
|
||||
protected DataAccessException customTranslate(String task, String sql, SQLException sqlex) {
|
||||
assertEquals(TASK, task);
|
||||
assertEquals(SQL, sql);
|
||||
return (sqlex == badSqlEx) ? customDex : null;
|
||||
}
|
||||
};
|
||||
sext.setSqlErrorCodes(ERROR_CODES);
|
||||
|
||||
// Shouldn't custom translate this
|
||||
assertEquals(customDex, sext.translate(TASK, SQL, badSqlEx));
|
||||
DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, intVioEx);
|
||||
assertEquals(intVioEx, diex.getCause());
|
||||
}
|
||||
|
||||
public void testCustomExceptionTranslation() {
|
||||
final String TASK = "TASK";
|
||||
final String SQL = "SQL SELECT *";
|
||||
final SQLErrorCodes customErrorCodes = new SQLErrorCodes();
|
||||
final CustomSQLErrorCodesTranslation customTranslation = new CustomSQLErrorCodesTranslation();
|
||||
|
||||
customErrorCodes.setBadSqlGrammarCodes(new String[] {"1", "2"});
|
||||
customErrorCodes.setDataIntegrityViolationCodes(new String[] {"3", "4"});
|
||||
customTranslation.setErrorCodes(new String[] {"1"});
|
||||
customTranslation.setExceptionClass(CustomErrorCodeException.class);
|
||||
customErrorCodes.setCustomTranslations(new CustomSQLErrorCodesTranslation[] {customTranslation});
|
||||
|
||||
SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
|
||||
sext.setSqlErrorCodes(customErrorCodes);
|
||||
|
||||
// Should custom translate this
|
||||
SQLException badSqlEx = new SQLException("", "", 1);
|
||||
assertEquals(CustomErrorCodeException.class, sext.translate(TASK, SQL, badSqlEx).getClass());
|
||||
assertEquals(badSqlEx, sext.translate(TASK, SQL, badSqlEx).getCause());
|
||||
|
||||
// Shouldn't custom translate this
|
||||
SQLException invResEx = new SQLException("", "", 3);
|
||||
DataIntegrityViolationException diex = (DataIntegrityViolationException) sext.translate(TASK, SQL, invResEx);
|
||||
assertEquals(invResEx, diex.getCause());
|
||||
|
||||
// Shouldn't custom translate this - invalid class
|
||||
try {
|
||||
customTranslation.setExceptionClass(String.class);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.jdbc.support;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
/**
|
||||
* Tests for SQLErrorCodes loading.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SQLErrorCodesFactoryTests extends TestCase {
|
||||
|
||||
/**
|
||||
* Check that a default instance returns empty error codes for an unknown database.
|
||||
*/
|
||||
public void testDefaultInstanceWithNoSuchDatabase() {
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("xx");
|
||||
assertTrue(sec.getBadSqlGrammarCodes().length == 0);
|
||||
assertTrue(sec.getDataIntegrityViolationCodes().length == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that a known database produces recognizable codes.
|
||||
*/
|
||||
public void testDefaultInstanceWithOracle() {
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes("Oracle");
|
||||
assertIsOracle(sec);
|
||||
}
|
||||
|
||||
private void assertIsOracle(SQLErrorCodes sec) {
|
||||
assertTrue(sec.getBadSqlGrammarCodes().length > 0);
|
||||
assertTrue(sec.getDataIntegrityViolationCodes().length > 0);
|
||||
// This had better be a Bad SQL Grammar code
|
||||
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0);
|
||||
// This had better NOT be
|
||||
assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "9xx42") >= 0);
|
||||
}
|
||||
|
||||
private void assertIsHsql(SQLErrorCodes sec) {
|
||||
assertTrue(sec.getBadSqlGrammarCodes().length > 0);
|
||||
assertTrue(sec.getDataIntegrityViolationCodes().length > 0);
|
||||
// This had better be a Bad SQL Grammar code
|
||||
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-22") >= 0);
|
||||
// This had better NOT be
|
||||
assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-9") >= 0);
|
||||
}
|
||||
|
||||
private void assertIsDB2(SQLErrorCodes sec) {
|
||||
assertTrue(sec.getBadSqlGrammarCodes().length > 0);
|
||||
assertTrue(sec.getDataIntegrityViolationCodes().length > 0);
|
||||
|
||||
assertFalse(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "942") >= 0);
|
||||
// This had better NOT be
|
||||
assertTrue(Arrays.binarySearch(sec.getBadSqlGrammarCodes(), "-204") >= 0);
|
||||
}
|
||||
|
||||
public void testLookupOrder() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
private int lookups = 0;
|
||||
protected Resource loadResource(String path) {
|
||||
++lookups;
|
||||
if (lookups == 1) {
|
||||
assertEquals(SQLErrorCodesFactory.SQL_ERROR_CODE_DEFAULT_PATH, path);
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
// Should have only one more lookup
|
||||
assertEquals(2, lookups);
|
||||
assertEquals(SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH, path);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Should have failed to load without error
|
||||
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
|
||||
assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
|
||||
assertTrue(sf.getErrorCodes("Oracle").getDataIntegrityViolationCodes().length == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that user defined error codes take precedence.
|
||||
*/
|
||||
public void testFindUserDefinedCodes() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
protected Resource loadResource(String path) {
|
||||
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
|
||||
return new ClassPathResource("test-error-codes.xml", SQLErrorCodesFactoryTests.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Should have loaded without error
|
||||
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
|
||||
assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
|
||||
assertEquals(2, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length);
|
||||
assertEquals("1", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[0]);
|
||||
assertEquals("2", sf.getErrorCodes("Oracle").getBadSqlGrammarCodes()[1]);
|
||||
}
|
||||
|
||||
public void testInvalidUserDefinedCodeFormat() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
protected Resource loadResource(String path) {
|
||||
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
|
||||
// Guaranteed to be on the classpath, but most certainly NOT XML
|
||||
return new ClassPathResource("SQLExceptionTranslator.class", SQLErrorCodesFactoryTests.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Should have failed to load without error
|
||||
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
|
||||
assertTrue(sf.getErrorCodes("XX").getBadSqlGrammarCodes().length == 0);
|
||||
assertEquals(0, sf.getErrorCodes("Oracle").getBadSqlGrammarCodes().length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that custom error codes take precedence.
|
||||
*/
|
||||
public void testFindCustomCodes() {
|
||||
class TestSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
protected Resource loadResource(String path) {
|
||||
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
|
||||
return new ClassPathResource("custom-error-codes.xml", SQLErrorCodesFactoryTests.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Should have loaded without error
|
||||
TestSQLErrorCodesFactory sf = new TestSQLErrorCodesFactory();
|
||||
assertEquals(1, sf.getErrorCodes("Oracle").getCustomTranslations().length);
|
||||
CustomSQLErrorCodesTranslation translation =
|
||||
(CustomSQLErrorCodesTranslation) sf.getErrorCodes("Oracle").getCustomTranslations()[0];
|
||||
assertEquals(CustomErrorCodeException.class, translation.getExceptionClass());
|
||||
assertEquals(1, translation.getErrorCodes().length);
|
||||
}
|
||||
|
||||
public void testDataSourceWithNullMetadata() throws Exception {
|
||||
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(null);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setVoidCallable();
|
||||
ctrlConnection.replay();
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
ctrlDataSource.replay();
|
||||
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
|
||||
assertIsEmpty(sec);
|
||||
|
||||
ctrlConnection.verify();
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
public void testGetFromDataSourceWithSQLException() throws Exception {
|
||||
|
||||
SQLException expectedSQLException = new SQLException();
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setThrowable(expectedSQLException);
|
||||
ctrlDataSource.replay();
|
||||
|
||||
SQLErrorCodes sec = SQLErrorCodesFactory.getInstance().getErrorCodes(mockDataSource);
|
||||
assertIsEmpty(sec);
|
||||
|
||||
ctrlDataSource.verify();
|
||||
}
|
||||
|
||||
private void assertIsEmpty(SQLErrorCodes sec) {
|
||||
// Codes should be empty
|
||||
assertEquals(0, sec.getBadSqlGrammarCodes().length);
|
||||
assertEquals(0, sec.getDataIntegrityViolationCodes().length);
|
||||
}
|
||||
|
||||
private SQLErrorCodes getErrorCodesFromDataSource(String productName, SQLErrorCodesFactory factory) throws Exception {
|
||||
MockControl mdControl = MockControl.createControl(DatabaseMetaData.class);
|
||||
DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock();
|
||||
md.getDatabaseProductName();
|
||||
mdControl.setReturnValue(productName);
|
||||
mdControl.replay();
|
||||
|
||||
MockControl ctrlConnection = MockControl.createControl(Connection.class);
|
||||
Connection mockConnection = (Connection) ctrlConnection.getMock();
|
||||
mockConnection.getMetaData();
|
||||
ctrlConnection.setReturnValue(md);
|
||||
mockConnection.close();
|
||||
ctrlConnection.setVoidCallable();
|
||||
ctrlConnection.replay();
|
||||
|
||||
MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
|
||||
DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
|
||||
mockDataSource.getConnection();
|
||||
ctrlDataSource.setDefaultReturnValue(mockConnection);
|
||||
ctrlDataSource.replay();
|
||||
|
||||
SQLErrorCodesFactory secf = null;
|
||||
if (factory != null) {
|
||||
secf = factory;
|
||||
}
|
||||
else {
|
||||
secf = SQLErrorCodesFactory.getInstance();
|
||||
}
|
||||
|
||||
SQLErrorCodes sec = secf.getErrorCodes(mockDataSource);
|
||||
|
||||
mdControl.verify();
|
||||
ctrlConnection.verify();
|
||||
ctrlDataSource.verify();
|
||||
|
||||
SQLErrorCodes sec2 = secf.getErrorCodes(mockDataSource);
|
||||
assertSame("Cached per DataSource", sec2, sec);
|
||||
|
||||
return sec;
|
||||
}
|
||||
|
||||
public void testOracleRecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("Oracle", null);
|
||||
assertIsOracle(sec);
|
||||
}
|
||||
|
||||
public void testHsqlRecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("HSQL Database Engine", null);
|
||||
assertIsHsql(sec);
|
||||
}
|
||||
|
||||
public void testDB2RecognizedFromMetadata() throws Exception {
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("DB2", null);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB2/", null);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB-2", null);
|
||||
assertIsEmpty(sec);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that wild card database name works.
|
||||
*/
|
||||
public void testWildCardNameRecognized() throws Exception {
|
||||
class WildcardSQLErrorCodesFactory extends SQLErrorCodesFactory {
|
||||
protected Resource loadResource(String path) {
|
||||
if (SQLErrorCodesFactory.SQL_ERROR_CODE_OVERRIDE_PATH.equals(path)) {
|
||||
return new ClassPathResource("wildcard-error-codes.xml", SQLErrorCodesFactoryTests.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
WildcardSQLErrorCodesFactory factory = new WildcardSQLErrorCodesFactory();
|
||||
SQLErrorCodes sec = getErrorCodesFromDataSource("DB2", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB2 UDB for Xxxxx", factory);
|
||||
assertIsDB2(sec);
|
||||
|
||||
sec = getErrorCodesFromDataSource("DB3", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB3/", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB3", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB3", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB3/", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB-3", factory);
|
||||
assertIsEmpty(sec);
|
||||
|
||||
sec = getErrorCodesFromDataSource("DB1", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB1/", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB1", factory);
|
||||
assertIsEmpty(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB1/", factory);
|
||||
assertIsEmpty(sec);
|
||||
|
||||
sec = getErrorCodesFromDataSource("DB0", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB0", factory);
|
||||
assertIsDB2(sec);
|
||||
sec = getErrorCodesFromDataSource("DB0/", factory);
|
||||
assertIsEmpty(sec);
|
||||
sec = getErrorCodesFromDataSource("/DB0/", factory);
|
||||
assertIsEmpty(sec);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.support;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.TransientDataAccessResourceException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.JUnit4;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Class to test custom SQLException translation.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
@RunWith(JUnit4.class)
|
||||
public class SQLExceptionCustomTranslatorTests extends TestCase {
|
||||
|
||||
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
|
||||
|
||||
static {
|
||||
ERROR_CODES.setBadSqlGrammarCodes(new String[] { "1" });
|
||||
ERROR_CODES.setDataAccessResourceFailureCodes(new String[] { "2" });
|
||||
ERROR_CODES.setCustomSqlExceptionTranslatorClass(CustomSqlExceptionTranslator.class);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCustomErrorCodeTranslation() {
|
||||
|
||||
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
|
||||
|
||||
SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1);
|
||||
DataAccessException daeex = sext.translate("task", "SQL", dataIntegrityViolationEx);
|
||||
assertEquals(dataIntegrityViolationEx, daeex.getCause());
|
||||
assertTrue(daeex instanceof BadSqlGrammarException);
|
||||
|
||||
SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2);
|
||||
DataAccessException darex = sext.translate("task", "SQL", dataAccessResourceEx);
|
||||
assertEquals(dataIntegrityViolationEx, daeex.getCause());
|
||||
assertTrue(darex instanceof TransientDataAccessResourceException);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.support;
|
||||
|
||||
import java.sql.SQLDataException;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLFeatureNotSupportedException;
|
||||
import java.sql.SQLIntegrityConstraintViolationException;
|
||||
import java.sql.SQLInvalidAuthorizationSpecException;
|
||||
import java.sql.SQLNonTransientConnectionException;
|
||||
import java.sql.SQLRecoverableException;
|
||||
import java.sql.SQLSyntaxErrorException;
|
||||
import java.sql.SQLTimeoutException;
|
||||
import java.sql.SQLTransactionRollbackException;
|
||||
import java.sql.SQLTransientConnectionException;
|
||||
|
||||
/**
|
||||
* Class to generate Java 6 SQLException subclasses for testing purposes.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SQLExceptionSubclassFactory {
|
||||
|
||||
public static SQLException newSQLDataException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLDataException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLFeatureNotSupportedException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLFeatureNotSupportedException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLIntegrityConstraintViolationException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLIntegrityConstraintViolationException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLInvalidAuthorizationSpecException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLInvalidAuthorizationSpecException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLNonTransientConnectionException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLNonTransientConnectionException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLSyntaxErrorException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLSyntaxErrorException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLTransactionRollbackException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLTransactionRollbackException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLTransientConnectionException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLTransientConnectionException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLTimeoutException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLTimeoutException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
public static SQLException newSQLRecoverableException(String reason, String SQLState, int vendorCode) {
|
||||
return new SQLRecoverableException(reason, SQLState, vendorCode);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.support;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.core.JdkVersion;
|
||||
import org.springframework.dao.ConcurrencyFailureException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.dao.PermissionDeniedDataAccessException;
|
||||
import org.springframework.dao.RecoverableDataAccessException;
|
||||
import org.springframework.dao.TransientDataAccessResourceException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class SQLExceptionSubclassTranslatorTests extends TestCase {
|
||||
|
||||
private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes();
|
||||
|
||||
static {
|
||||
ERROR_CODES.setBadSqlGrammarCodes(new String[] { "1" });
|
||||
}
|
||||
|
||||
|
||||
public void testErrorCodeTranslation() {
|
||||
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16) {
|
||||
return;
|
||||
}
|
||||
|
||||
SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);
|
||||
|
||||
SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0);
|
||||
DataIntegrityViolationException divex = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx);
|
||||
assertEquals(dataIntegrityViolationEx, divex.getCause());
|
||||
|
||||
SQLException featureNotSupEx = SQLExceptionSubclassFactory.newSQLFeatureNotSupportedException("", "", 0);
|
||||
InvalidDataAccessApiUsageException idaex = (InvalidDataAccessApiUsageException) sext.translate("task", "SQL", featureNotSupEx);
|
||||
assertEquals(featureNotSupEx, idaex.getCause());
|
||||
|
||||
SQLException dataIntegrityViolationEx2 = SQLExceptionSubclassFactory.newSQLIntegrityConstraintViolationException("", "", 0);
|
||||
DataIntegrityViolationException divex2 = (DataIntegrityViolationException) sext.translate("task", "SQL", dataIntegrityViolationEx2);
|
||||
assertEquals(dataIntegrityViolationEx2, divex2.getCause());
|
||||
|
||||
SQLException permissionDeniedEx = SQLExceptionSubclassFactory.newSQLInvalidAuthorizationSpecException("", "", 0);
|
||||
PermissionDeniedDataAccessException pdaex = (PermissionDeniedDataAccessException) sext.translate("task", "SQL", permissionDeniedEx);
|
||||
assertEquals(permissionDeniedEx, pdaex.getCause());
|
||||
|
||||
SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLNonTransientConnectionException("", "", 0);
|
||||
DataAccessResourceFailureException darex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataAccessResourceEx);
|
||||
assertEquals(dataAccessResourceEx, darex.getCause());
|
||||
|
||||
SQLException badSqlEx2 = SQLExceptionSubclassFactory.newSQLSyntaxErrorException("", "", 0);
|
||||
BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", badSqlEx2);
|
||||
assertEquals("SQL2", bsgex2.getSql());
|
||||
assertEquals(badSqlEx2, bsgex2.getSQLException());
|
||||
|
||||
SQLException tranRollbackEx = SQLExceptionSubclassFactory.newSQLTransactionRollbackException("", "", 0);
|
||||
ConcurrencyFailureException cfex = (ConcurrencyFailureException) sext.translate("task", "SQL", tranRollbackEx);
|
||||
assertEquals(tranRollbackEx, cfex.getCause());
|
||||
|
||||
SQLException transientConnEx = SQLExceptionSubclassFactory.newSQLTransientConnectionException("", "", 0);
|
||||
TransientDataAccessResourceException tdarex = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx);
|
||||
assertEquals(transientConnEx, tdarex.getCause());
|
||||
|
||||
SQLException transientConnEx2 = SQLExceptionSubclassFactory.newSQLTimeoutException("", "", 0);
|
||||
TransientDataAccessResourceException tdarex2 = (TransientDataAccessResourceException) sext.translate("task", "SQL", transientConnEx2);
|
||||
assertEquals(transientConnEx2, tdarex2.getCause());
|
||||
|
||||
SQLException recoverableEx = SQLExceptionSubclassFactory.newSQLRecoverableException("", "", 0);
|
||||
RecoverableDataAccessException rdaex2 = (RecoverableDataAccessException) sext.translate("task", "SQL", recoverableEx);
|
||||
assertEquals(recoverableEx, rdaex2.getCause());
|
||||
|
||||
// Test classic error code translation. We should move there next if the exception we pass in is not one
|
||||
// of the new sub-classes.
|
||||
SQLException sexEct = new SQLException("", "", 1);
|
||||
BadSqlGrammarException bsgEct = (BadSqlGrammarException) sext.translate("task", "SQL-ECT", sexEct);
|
||||
assertEquals("SQL-ECT", bsgEct.getSql());
|
||||
assertEquals(sexEct, bsgEct.getSQLException());
|
||||
|
||||
// Test fallback. We assume that no database will ever return this error code,
|
||||
// but 07xxx will be bad grammar picked up by the fallback SQLState translator
|
||||
SQLException sexFbt = new SQLException("", "07xxx", 666666666);
|
||||
BadSqlGrammarException bsgFbt = (BadSqlGrammarException) sext.translate("task", "SQL-FBT", sexFbt);
|
||||
assertEquals("SQL-FBT", bsgFbt.getSql());
|
||||
assertEquals(sexFbt, bsgFbt.getSQLException());
|
||||
// and 08xxx will be data resource failure (non-transient) picked up by the fallback SQLState translator
|
||||
SQLException sexFbt2 = new SQLException("", "08xxx", 666666666);
|
||||
DataAccessResourceFailureException darfFbt = (DataAccessResourceFailureException) sext.translate("task", "SQL-FBT2", sexFbt2);
|
||||
assertEquals(sexFbt2, darfFbt.getCause());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.jdbc.support;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.UncategorizedSQLException;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since 13-Jan-03
|
||||
*/
|
||||
public class SQLStateExceptionTranslatorTests extends TestCase {
|
||||
|
||||
private SQLStateSQLExceptionTranslator trans = new SQLStateSQLExceptionTranslator();
|
||||
|
||||
// ALSO CHECK CHAIN of SQLExceptions!?
|
||||
// also allow chain of translators? default if can't do specific?
|
||||
|
||||
public void testBadSqlGrammar() {
|
||||
String sql = "SELECT FOO FROM BAR";
|
||||
SQLException sex = new SQLException("Message", "42001", 1);
|
||||
try {
|
||||
throw this.trans.translate("task", sql, sex);
|
||||
}
|
||||
catch (BadSqlGrammarException ex) {
|
||||
// OK
|
||||
assertTrue("SQL is correct", sql.equals(ex.getSql()));
|
||||
assertTrue("Exception matches", sex.equals(ex.getSQLException()));
|
||||
}
|
||||
}
|
||||
|
||||
public void testInvalidSqlStateCode() {
|
||||
String sql = "SELECT FOO FROM BAR";
|
||||
SQLException sex = new SQLException("Message", "NO SUCH CODE", 1);
|
||||
try {
|
||||
throw this.trans.translate("task", sql, sex);
|
||||
}
|
||||
catch (UncategorizedSQLException ex) {
|
||||
// OK
|
||||
assertTrue("SQL is correct", sql.equals(ex.getSql()));
|
||||
assertTrue("Exception matches", sex.equals(ex.getSQLException()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PostgreSQL can return null
|
||||
* SAP DB can apparently return empty SQL code
|
||||
* Bug 729170
|
||||
*/
|
||||
public void testMalformedSqlStateCodes() {
|
||||
String sql = "SELECT FOO FROM BAR";
|
||||
SQLException sex = new SQLException("Message", null, 1);
|
||||
testMalformedSqlStateCode(sex);
|
||||
|
||||
sex = new SQLException("Message", "", 1);
|
||||
testMalformedSqlStateCode(sex);
|
||||
|
||||
// One char's not allowed
|
||||
sex = new SQLException("Message", "I", 1);
|
||||
testMalformedSqlStateCode(sex);
|
||||
}
|
||||
|
||||
|
||||
private void testMalformedSqlStateCode(SQLException sex) {
|
||||
String sql = "SELECT FOO FROM BAR";
|
||||
try {
|
||||
throw this.trans.translate("task", sql, sex);
|
||||
}
|
||||
catch (UncategorizedSQLException ex) {
|
||||
// OK
|
||||
assertTrue("SQL is correct", sql.equals(ex.getSql()));
|
||||
assertTrue("Exception matches", sex.equals(ex.getSQLException()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.jdbc.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.dao.ConcurrencyFailureException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.TransientDataAccessResourceException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.UncategorizedSQLException;
|
||||
|
||||
/**
|
||||
* @author Rick Evans
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
*/
|
||||
public class SQLStateSQLExceptionTranslatorTests {
|
||||
|
||||
private static final String REASON = "The game is afoot!";
|
||||
|
||||
private static final String TASK = "Counting sheep... yawn.";
|
||||
|
||||
private static final String SQL = "select count(0) from t_sheep where over_fence = ... yawn... 1";
|
||||
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testTranslateNullException() throws Exception {
|
||||
new SQLStateSQLExceptionTranslator().translate("", "", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateBadSqlGrammar() throws Exception {
|
||||
doTest("07", BadSqlGrammarException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateDataIntegrityViolation() throws Exception {
|
||||
doTest("23", DataIntegrityViolationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateDataAccessResourceFailure() throws Exception {
|
||||
doTest("53", DataAccessResourceFailureException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateTransientDataAccessResourceFailure() throws Exception {
|
||||
doTest("S1", TransientDataAccessResourceException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateConcurrencyFailure() throws Exception {
|
||||
doTest("40", ConcurrencyFailureException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTranslateUncategorized() throws Exception {
|
||||
doTest("00000000", UncategorizedSQLException.class);
|
||||
}
|
||||
|
||||
|
||||
private void doTest(String sqlState, Class<?> dataAccessExceptionType) {
|
||||
SQLException ex = new SQLException(REASON, sqlState);
|
||||
SQLExceptionTranslator translator = new SQLStateSQLExceptionTranslator();
|
||||
DataAccessException dax = translator.translate(TASK, SQL, ex);
|
||||
assertNotNull("Translation must *never* result in a null DataAccessException being returned.", dax);
|
||||
assertEquals("Wrong DataAccessException type returned as the result of the translation", dataAccessExceptionType, dax.getClass());
|
||||
assertNotNull("The original SQLException must be preserved in the translated DataAccessException", dax.getCause());
|
||||
assertSame("The exact same original SQLException must be preserved in the translated DataAccessException", ex, dax.getCause());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<!--
|
||||
Whacky error codes for testing
|
||||
-->
|
||||
<bean id="Oracle" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="badSqlGrammarCodes"><value>1,2</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>1,1400,1722</value></property>
|
||||
<property name="customTranslations">
|
||||
<list>
|
||||
<bean class="org.springframework.jdbc.support.CustomSQLErrorCodesTranslation">
|
||||
<property name="errorCodes"><value>999</value></property>
|
||||
<property name="exceptionClass">
|
||||
<value>org.springframework.jdbc.support.CustomErrorCodeException</value>
|
||||
</property>
|
||||
</bean>
|
||||
</list>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,242 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.jdbc.support.rowset;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Date;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Time;
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
import org.easymock.MockControl;
|
||||
|
||||
import org.springframework.jdbc.InvalidResultSetAccessException;
|
||||
|
||||
/**
|
||||
* @author Thomas Risberg
|
||||
*/
|
||||
public class ResultSetWrappingRowSetTests extends TestCase {
|
||||
|
||||
private MockControl rsetControl;
|
||||
private ResultSet rset;
|
||||
private ResultSetWrappingSqlRowSet rowset;
|
||||
|
||||
public void setUp() throws Exception {
|
||||
rsetControl = MockControl.createControl(ResultSet.class);
|
||||
rset = (ResultSet) rsetControl.getMock();
|
||||
rset.getMetaData();
|
||||
rsetControl.setReturnValue(null);
|
||||
rset.getMetaData();
|
||||
rsetControl.setReturnValue(null);
|
||||
}
|
||||
|
||||
public void testGetBigDecimalInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), BigDecimal.valueOf(1));
|
||||
}
|
||||
|
||||
public void testGetBigDecimalString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBigDecimal", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBigDecimal", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", BigDecimal.valueOf(1));
|
||||
}
|
||||
|
||||
public void testGetStringInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), "test");
|
||||
}
|
||||
|
||||
public void testGetStringString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getString", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getString", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", "test");
|
||||
}
|
||||
|
||||
public void testGetTimestampInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Timestamp(1234l));
|
||||
}
|
||||
|
||||
public void testGetTimestampString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTimestamp", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTimestamp", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Timestamp(1234l));
|
||||
}
|
||||
|
||||
public void testGetDateInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Date(1234l));
|
||||
}
|
||||
|
||||
public void testGetDateString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDate", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDate", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Date(1234l));
|
||||
}
|
||||
|
||||
public void testGetTimeInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Time(1234l));
|
||||
}
|
||||
|
||||
public void testGetTimeString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getTime", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getTime", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Time(1234l));
|
||||
}
|
||||
|
||||
public void testGetObjectInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Object());
|
||||
}
|
||||
|
||||
public void testGetObjectString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getObject", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getObject", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Object());
|
||||
}
|
||||
|
||||
public void testGetIntInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Integer(1));
|
||||
}
|
||||
|
||||
public void testGetIntString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getInt", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getInt", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Integer(1));
|
||||
}
|
||||
|
||||
public void testGetFloatInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Float(1));
|
||||
}
|
||||
|
||||
public void testGetFloatString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getFloat", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getFloat", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Float(1));
|
||||
}
|
||||
|
||||
public void testGetDoubleInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Double(1));
|
||||
}
|
||||
|
||||
public void testGetDoubleString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getDouble", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getDouble", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Double(1));
|
||||
}
|
||||
|
||||
public void testGetLongInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Long(1));
|
||||
}
|
||||
|
||||
public void testGetLongString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getLong", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getLong", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Long(1));
|
||||
}
|
||||
|
||||
public void testGetBooleanInt() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
|
||||
doTest(rset, rowset, new Integer(1), new Boolean(true));
|
||||
}
|
||||
|
||||
public void testGetBooleanString() throws Exception {
|
||||
Method rset = ResultSet.class.getDeclaredMethod("getBoolean", new Class[] {int.class});
|
||||
Method rowset = ResultSetWrappingSqlRowSet.class.getDeclaredMethod("getBoolean", new Class[] {String.class});
|
||||
doTest(rset, rowset, "test", new Boolean(true));
|
||||
}
|
||||
|
||||
private void doTest(Method rsetMethod, Method rowsetMethod, Object arg, Object ret) throws Exception {
|
||||
if (arg instanceof String) {
|
||||
Method findMethod = ResultSet.class.getDeclaredMethod("findColumn", new Class[] {String.class});
|
||||
findMethod.invoke(rset, new Object[] {arg});
|
||||
rsetControl.setReturnValue(1);
|
||||
rsetMethod.invoke(rset, new Object[] {1});
|
||||
}
|
||||
else {
|
||||
rsetMethod.invoke(rset, new Object[] {arg});
|
||||
}
|
||||
if (ret instanceof Double) {
|
||||
rsetControl.setReturnValue(((Double) ret).doubleValue());
|
||||
}
|
||||
else if (ret instanceof Float) {
|
||||
rsetControl.setReturnValue(((Float) ret).floatValue());
|
||||
}
|
||||
else if (ret instanceof Integer) {
|
||||
rsetControl.setReturnValue(((Integer) ret).intValue());
|
||||
}
|
||||
else if (ret instanceof Short) {
|
||||
rsetControl.setReturnValue(((Short) ret).shortValue());
|
||||
}
|
||||
else if (ret instanceof Long) {
|
||||
rsetControl.setReturnValue(((Long) ret).longValue());
|
||||
}
|
||||
else if (ret instanceof Boolean) {
|
||||
rsetControl.setReturnValue(((Boolean) ret).booleanValue());
|
||||
}
|
||||
else if (ret instanceof Byte) {
|
||||
rsetControl.setReturnValue(((Byte) ret).byteValue());
|
||||
}
|
||||
else {
|
||||
rsetControl.setReturnValue(ret);
|
||||
}
|
||||
|
||||
if (arg instanceof String) {
|
||||
Method findMethod = ResultSet.class.getDeclaredMethod("findColumn", new Class[] {String.class});
|
||||
findMethod.invoke(rset, new Object[] {arg});
|
||||
rsetControl.setReturnValue(1);
|
||||
rsetMethod.invoke(rset, new Object[] {1});
|
||||
}
|
||||
else {
|
||||
rsetMethod.invoke(rset, new Object[] {arg});
|
||||
}
|
||||
rsetControl.setThrowable(new SQLException("test"));
|
||||
|
||||
rsetControl.replay();
|
||||
|
||||
rowset = new ResultSetWrappingSqlRowSet(rset);
|
||||
rowsetMethod.invoke(rowset, new Object[] {arg});
|
||||
try {
|
||||
rowsetMethod.invoke(rowset, new Object[] {arg});
|
||||
fail("InvalidResultSetAccessException should have been thrown");
|
||||
}
|
||||
catch (InvocationTargetException ex) {
|
||||
assertEquals(InvalidResultSetAccessException.class, ex.getTargetException().getClass());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<!--
|
||||
Whacky error codes for testing
|
||||
-->
|
||||
<bean id="Oracle" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="badSqlGrammarCodes"><value>1,2</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>1,1400,1722</value></property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<!--
|
||||
Whacky error codes for testing
|
||||
-->
|
||||
<bean id="Oracle" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="badSqlGrammarCodes"><value>1,2,942</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>1,1400,1722</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="DB0" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="databaseProductName"><value>*DB0</value></property>
|
||||
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="DB1" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="databaseProductName"><value>DB1*</value></property>
|
||||
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="DB2" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="databaseProductName"><value>*DB2*</value></property>
|
||||
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="DB3" class="org.springframework.jdbc.support.SQLErrorCodes">
|
||||
<property name="databaseProductName"><value>*DB3*</value></property>
|
||||
<property name="badSqlGrammarCodes"><value>-204,1,2</value></property>
|
||||
<property name="dataIntegrityViolationCodes"><value>3,4</value></property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
Reference in New Issue
Block a user