Java/Spring/JdbcTemplate
Содержание
- 1 Control Parameter Type In JdbcTemplate.Query
- 2 Deal With TimeStamp
- 3 Execute Delete Statement
- 4 Execute Update and Delete Statements With JdbcTemplate
- 5 Number Of Row Affected
- 6 Pass DataSource to se JdbcTemplate
- 7 Pass Object Array To Query Method In JdbcTemplate
- 8 Pass Parameter As Object Array
- 9 Query For List
- 10 Query For List, Returns List Of Linked HashMap
- 11 Query For Map
- 12 Query For Object, Return String
- 13 Query For Rowset
- 14 UpdateStatement With Two Parameters
- 15 Use batchUpdate from JdbcTemplate To Execute Two UpdateStatements
- 16 Use JdbcTemplate To Create Table
- 17 Use JdbcTemplate To Execute Aggregate Function: queryForLong
- 18 Use JdbcTemplate To Execute Delete Statement With Parameter
- 19 Use queryForInt To Execute Aggregate Function
Control Parameter Type In JdbcTemplate.Query
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println(jdbcTemplate.query("select first_name from t_customer where id=?", new Object[] { 1L }, new int[] { Types.INTEGER }, new FirstColumnStringRowMapper())); }
} class FirstColumnStringRowMapper implements RowMapper {
public Object mapRow(ResultSet resultSet, int i) throws SQLException { return resultSet.getString(1); }
}
</source>
Deal With TimeStamp
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.query("select first_name from t_customer where last_login < ?", new Object[] { new java.util.Date() }, new int[] { Types.TIMESTAMP }, new StringExtractingRowCallbackHandler());
}
} class StringExtractingRowCallbackHandler implements RowCallbackHandler {
public void processRow(ResultSet resultSet) throws SQLException { while (resultSet.next()) { System.out.println(resultSet.getString(1)); } }
}
</source>
Execute Delete Statement
<source lang="java">
File: context.xml
File: Main.java import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("password"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("password"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); jt.execute("delete from employee"); Object[] parameters = new Object[] {new Integer(1)}; List l = jt.queryForList("select id, name from employee where id > ?", parameters); System.out.println(l.size()); ds.destroy(); }
}
</source>
Execute Update and Delete Statements With JdbcTemplate
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>sun.jdbc.odbc.JdbcOdbcDriver</value> </property> <property name="url"> <value>jdbc:odbc:test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>sql</value> </property> </bean> <bean id="datacon" class="Dataconimpl"> <property name="dataSource"><ref local="dataSource"/></property> </bean>
</beans>
File: Main.java import javax.sql.DataSource; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.core.JdbcTemplate; public class Main {
public static void main(String[] args) throws Exception { BeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml")); Dataconimpl bean1 = (Dataconimpl) factory.getBean("datacon"); JdbcTemplate jt = new JdbcTemplate(bean1.dbcon()); jt.execute("delete from table1 "); jt.execute("update table1 set table1.place="" "); }
} class Dataconimpl implements Datacon {
private DataSource dataSource; public void setDataSource(DataSource ds) { dataSource = ds; } public DataSource dbcon() { return dataSource; }
} interface Datacon {
public DataSource dbcon();
}
</source>
Number Of Row Affected
<source lang="java">
File: Main.java import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("password"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("password"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); int x = jt.update("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); System.out.println(x); Object[] parameters = new Object[] {new Integer(1)}; List l = jt.queryForList("select id, name from employee where id > ?", parameters); System.out.println(l.size()); ds.destroy(); }
}
</source>
Pass DataSource to se JdbcTemplate
<source lang="java">
File: Main.java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); int count = jt.queryForInt("select count(*) from employee"); System.out.println(count); ds.destroy(); }
}
</source>
Pass Object Array To Query Method In JdbcTemplate
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.query("select first_name from t_customer where id=?", new Object[] { 1L }, new StringExtractingRowCallbackHandler()); }
} class StringExtractingRowCallbackHandler implements RowCallbackHandler {
public void processRow(ResultSet resultSet) throws SQLException { while (resultSet.next()) { System.out.println(resultSet.getString(1)); } }
}
</source>
Pass Parameter As Object Array
<source lang="java">
File: context.xml
File: Main.java import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); Object[] parameters = new Object[] {new Integer(1)}; List l = jt.queryForList("select id, name from employee where id > ?", parameters); System.out.println(l.size()); System.out.println(l.get(0)); System.out.println(l.get(0).getClass()); ds.destroy(); }
}
</source>
Query For List
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); System.out.println(jdbcTemplate.queryForList("select id from t_customer", Long.class)); }
}
</source>
Query For List, Returns List Of Linked HashMap
<source lang="java">
File: context.xml
File: Main.java import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); Object[] parameters = new Object[] {new Integer(1)}; List l = jt.queryForList("select id, name from employee where id > ?", parameters); System.out.println(l.size()); System.out.println(l.get(0)); System.out.println(l.get(0).getClass()); ds.destroy(); }
}
</source>
Query For Map
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); System.out.println(jdbcTemplate.queryForMap("select * from customer")); }
}
</source>
Query For Object, Return String
<source lang="java">
File: Main.java
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); Object[] parameters = new Object[] {new Integer(2)}; Object o = jt.queryForObject("select name from employee where id = ?", parameters, String.class); System.out.println((String)o); ds.destroy(); }
}
</source>
Query For Rowset
<source lang="java">
File: Main.java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.rowset.SqlRowSet; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); int x = jt.update("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); Object[] parameters = new Object[] { new Integer(1) }; SqlRowSet srs = jt.queryForRowSet("select id, name from employee where id > ?", parameters); int rowCount = 0; while (srs.next()) { System.out.println(srs.getString("id") + " - " + srs.getString("name")); rowCount++; } System.out.println(rowCount); ds.destroy(); }
}
</source>
UpdateStatement With Two Parameters
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update("update customer set first_name=? where id=?", new Object[] { "A", 1L }, new int[] { Types.VARCHAR, Types.INTEGER }); }
}
</source>
Use batchUpdate from JdbcTemplate To Execute Two UpdateStatements
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/> </bean> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.rumonsDbcpNativeJdbcExtractor"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean>
</beans>
File: Main.java import java.sql.Types; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.batchUpdate(new String[] { "update customer set first_name = "FN#"", "delete from customer where id > 2" }); }
}
</source>
Use JdbcTemplate To Create Table
<source lang="java">
File: context.xml
File: Main.java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); int count = jt.queryForInt("select count(*) from employee"); System.out.println(count); ds.destroy(); }
}
</source>
Use JdbcTemplate To Execute Aggregate Function: queryForLong
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource"
destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/>
</bean> <bean id="employeeDao" class="EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean> </beans>
File: EmployeeDaoImpl.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback; import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.object.MappingSqlQuery; import org.springframework.jdbc.object.SqlUpdate; import org.springframework.jdbc.object.StoredProcedure; import org.springframework.jdbc.support.lob.DefaultLobHandler; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor; import org.springframework.util.FileCopyUtils; //import org.apache.rumons.dbcp.BasicDataSource;
public class EmployeeDaoImpl extends JdbcDaoSupport{
protected void initDao() throws Exception { super.initDao(); getJdbcTemplate().setNativeJdbcExtractor(new SimpleNativeJdbcExtractor()); } public int getTotalNumberOfEmployees() { return getJdbcTemplate().queryForInt("SELECT COUNT(0) FROM employees"); } public long getTotalAge() { return getJdbcTemplate().queryForLong("SELECT SUM(age) FROM employee"); } public long getAverageAge() { return getJdbcTemplate().queryForLong("SELECT AVG(age) FROM employee"); } public long getOldestAge() { return getJdbcTemplate().queryForLong("SELECT MAX(age) FROM employee"); } public long getYoungestAge() { return getJdbcTemplate().queryForLong("SELECT MIN(age) FROM employee"); }
}
class Employee {
private Integer id; private Name name = new Name(); private Integer age; private Sex sex; private Address address = new Address(); private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>(); public Employee() { } public Employee(String firstName, String lastName) { this.getName().setFirst(firstName); this.getName().setLast(lastName); } void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public Address getAddress() { return address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Name getName() { return name; } public List<PhoneNumber> getPhoneNumbers() { return Collections.unmodifiableList(phoneNumbers); } public void addPhoneNumber(PhoneNumber phoneNumber) { this.phoneNumbers.add(phoneNumber); } public void removePhoneNumber(PhoneNumber phoneNumber) { this.phoneNumbers.remove(phoneNumber); } public void removePhoneNumber(int index) { this.phoneNumbers.remove(index); } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; }
} abstract class Sex {
public static final Sex MALE = new Male(); public static final Sex FEMALE = new Female(); public boolean equals(Object o) { if (o == null) { return false; } return getClass().equals(o.getClass()); }
} class PhoneNumber { } class Address {
private String line1; private String line2; private String city; private String state; private String zip; public void setLine1(String line1) { this.line1 = line1; } public String getLine1() { return this.line1; } public void setLine2(String line2) { this.line2 = line2; } public String getLine2() { return this.line2; } public void setCity(String city) { this.city = city; } public String getCity() { return this.city; } public void setState(String state) { this.state = state; } public String getState() { return this.state; } public void setZip(String zip) { this.zip = zip; } public String getZip() { return this.zip; }
} final class Male extends Sex {
protected Male() { }
} final class Female extends Sex {
protected Female() { }
}
class Name {
private String first; private String middle; private String last; public void setFirst(String first) { this.first = first; } public String getFirst() { return this.first; } public void setMiddle(String middle) { this.middle = middle; } public String getMiddle() { return this.middle; } public void setLast(String last) { this.last = last; } public String getLast() { return this.last; }
}
File: Main.java import java.util.Date; import java.util.GregorianCalendar; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext( "context.xml"); EmployeeDaoImpl ws = (EmployeeDaoImpl) ctx.getBean("employeeDao"); }
}
</source>
Use JdbcTemplate To Execute Delete Statement With Parameter
<source lang="java">
File: context.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <bean id="dataSource" class="org.apache.rumons.dbcp.BasicDataSource"
destroy-method="close"> <property name="driverClassName" value="org.hsqldb.jdbcDriver"/> <property name="url" value="jdbc:hsqldb:mem:."/> <property name="username" value="sa"/> <property name="password" value=""/>
</bean> <bean id="employeeDao" class="EmployeeDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean> </beans>
File: EmployeeDaoImpl.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback; import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.jdbc.object.MappingSqlQuery; import org.springframework.jdbc.object.SqlUpdate; import org.springframework.jdbc.object.StoredProcedure; import org.springframework.jdbc.support.lob.DefaultLobHandler; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor; import org.springframework.util.FileCopyUtils; //import org.apache.rumons.dbcp.BasicDataSource;
public class EmployeeDaoImpl extends JdbcDaoSupport{
protected void initDao() throws Exception { super.initDao(); getJdbcTemplate().setNativeJdbcExtractor(new SimpleNativeJdbcExtractor()); }
public void delete(Employee employee) { getJdbcTemplate().update("DELETE FROM employee WHERE id = ?", new Object[] { employee.getId() }); }
}
class Employee {
private Integer id; private Name name = new Name(); private Integer age; private Sex sex; private Address address = new Address(); private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>(); public Employee() { } public Employee(String firstName, String lastName) { this.getName().setFirst(firstName); this.getName().setLast(lastName); } void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public Address getAddress() { return address; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Name getName() { return name; } public List<PhoneNumber> getPhoneNumbers() { return Collections.unmodifiableList(phoneNumbers); } public void addPhoneNumber(PhoneNumber phoneNumber) { this.phoneNumbers.add(phoneNumber); } public void removePhoneNumber(PhoneNumber phoneNumber) { this.phoneNumbers.remove(phoneNumber); } public void removePhoneNumber(int index) { this.phoneNumbers.remove(index); } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; }
} abstract class Sex {
public static final Sex MALE = new Male(); public static final Sex FEMALE = new Female(); public boolean equals(Object o) { if (o == null) { return false; } return getClass().equals(o.getClass()); }
} class PhoneNumber { } class Address {
private String line1; private String line2; private String city; private String state; private String zip; public void setLine1(String line1) { this.line1 = line1; } public String getLine1() { return this.line1; } public void setLine2(String line2) { this.line2 = line2; } public String getLine2() { return this.line2; } public void setCity(String city) { this.city = city; } public String getCity() { return this.city; } public void setState(String state) { this.state = state; } public String getState() { return this.state; } public void setZip(String zip) { this.zip = zip; } public String getZip() { return this.zip; }
} final class Male extends Sex {
protected Male() { }
} final class Female extends Sex {
protected Female() { }
}
class Name {
private String first; private String middle; private String last; public void setFirst(String first) { this.first = first; } public String getFirst() { return this.first; } public void setMiddle(String middle) { this.middle = middle; } public String getMiddle() { return this.middle; } public void setLast(String last) { this.last = last; } public String getLast() { return this.last; }
}
File: Main.java import java.util.Date; import java.util.GregorianCalendar; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; class Main {
public static void main(String args[]) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext( "context.xml"); EmployeeDaoImpl ws = (EmployeeDaoImpl) ctx.getBean("employeeDao"); }
}
</source>
Use queryForInt To Execute Aggregate Function
<source lang="java">
File: context.xml
File: Main.java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Main {
public static void main(String args[]) throws Exception { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); ds.setUrl("jdbc:hsqldb:data/tutorial"); ds.setUsername("sa"); ds.setPassword(""); // // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl("jdbc:mysql://localhost:3306/spring"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); // // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUrl("jdbc:oracle:thin:@fiji:1521:my10g"); // ds.setUsername("spring"); // ds.setPassword("t1cket"); JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("create table employee (id int, name varchar)"); jt.execute("insert into employee (id, name) values (1, "A")"); jt.execute("insert into employee (id, name) values (2, "B")"); jt.execute("insert into employee (id, name) values (3, "C")"); jt.execute("insert into employee (id, name) values (4, "D")"); jt.execute("insert into employee (id, name) values (5, "E")"); jt.execute("insert into employee (id, name) values (6, "F")"); Object[] parameters = new Object[] {"M"}; int count = jt.queryForInt("select count(*) from employee where name > ?", parameters); System.out.println(count); ds.destroy(); }
}
</source>