Java/Spring/SqlUpdate
Содержание
Delete Statement With Parameter
<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 java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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.SqlParameter; import org.springframework.jdbc.object.SqlUpdate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; 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"); DeleteWhereIdGreater deleteWhereIdGreater = new DeleteWhereIdGreater(dataSource); deleteWhereIdGreater.update(1L); }
} class DeleteWhereIdGreater extends SqlUpdate {
private static final String SQL = "delete from customer where id > ?"; DeleteWhereIdGreater(DataSource dataSource) { super(dataSource, SQL); declareParameter(new SqlParameter(Types.INTEGER)); }
}
</source>
Extends SqlUpdate And Provide Customized 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="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean> <bean id="mysqlDataSource" class="org.apache.rumons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://dbhost-prospring-psql/prospring"/> <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 java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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.SqlParameter; import org.springframework.jdbc.object.SqlUpdate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; 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"); Insert insert = new Insert(dataSource); insert.update(new Object[] { 3L, "A", "B", null, null }); }
} class Insert extends SqlUpdate {
private static final String SQL = "insert into t_customer (id, first_name, last_name, last_login, " + "comments) values (?, ?, ?, ?, ?)"; Insert(DataSource dataSource) { super(dataSource, SQL); declareParameter(new SqlParameter(Types.INTEGER)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.TIMESTAMP)); declareParameter(new SqlParameter(Types.CLOB)); } void insert(long id, String firstName, String lastName, Date lastLogin, String comments) { update(new Object[] { id, firstName, lastName, lastLogin, comments }); }
}
</source>
Extends SqlUpdateExecute Update Statement
<source lang="java">
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{
private UpdateAgeQuery updateAgeQuery; protected void initDao() throws Exception { super.initDao(); getJdbcTemplate().setNativeJdbcExtractor(new SimpleNativeJdbcExtractor()); updateAgeQuery = new UpdateAgeQuery(getDataSource()); } public void updateAge(Integer employeeId, Integer age) { updateAgeQuery.update(new Object[] { age, employeeId }); }
} class UpdateAgeQuery extends SqlUpdate {
private static final String SQL_QUERY = "UPDATE employee SET age = ? WHERE id = ?"; public UpdateAgeQuery(DataSource dataSource) { super(dataSource, SQL_QUERY); declareParameter(new SqlParameter("age", Types.INTEGER)); declareParameter(new SqlParameter("id", Types.INTEGER)); compile(); }
}
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"); }
}
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>
</source>
extends SqlUpdate to create named sql statement with 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 java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; 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.SqlParameter; import org.springframework.jdbc.object.SqlUpdate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; 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"); NamedInsert namedInsert = new NamedInsert(dataSource); Map<String, Object> parameterMap = new HashMap<String, Object>(); parameterMap.put("id", 6L); parameterMap.put("firstName", "A"); parameterMap.put("lastName", "B"); parameterMap.put("lastLogin", null); parameterMap.put("comments", null); namedInsert.updateByNamedParam(parameterMap); }
} class NamedInsert extends SqlUpdate {
private static final String SQL = "insert into t_customer (id, first_name, last_name, last_login, " + "comments) values (:id, :firstName, :lastName, :lastLogin, :comments)"; NamedInsert(DataSource dataSource) { super(dataSource, SQL); declareParameter(new SqlParameter(Types.INTEGER)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.VARCHAR)); declareParameter(new SqlParameter(Types.TIMESTAMP)); declareParameter(new SqlParameter(Types.CLOB)); }
}
</source>
Extends SqlUpdate To Execute Insert Statement
<source lang="java">
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{
private AddEmployeeQuery addEmployeeQuery; protected void initDao() throws Exception { super.initDao(); getJdbcTemplate().setNativeJdbcExtractor(new SimpleNativeJdbcExtractor()); addEmployeeQuery = new AddEmployeeQuery(getDataSource()); } public void add(Employee employee) { addEmployeeQuery.update(new Object[] { employee.getName().getFirst(), employee.getName().getMiddle(), employee.getName().getLast(), employee.getAddress().getLine1(), employee.getAddress().getLine2(), employee.getAddress().getCity(), employee.getAddress().getState(), employee.getAddress().getZip(), employee.getAge(), }); }
} class AddEmployeeQuery extends SqlUpdate {
private static final String SQL_QUERY = "INSERT INTO employee (name_first, name_middle, name_last, address_line1, " + "address_line2, address_city, address_state, address_zip, age) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; public AddEmployeeQuery(DataSource dataSource) { super(dataSource, SQL_QUERY); declareParameter(new SqlParameter("name_first", Types.VARCHAR)); declareParameter(new SqlParameter("name_middle", Types.VARCHAR)); declareParameter(new SqlParameter("name_last", Types.VARCHAR)); declareParameter(new SqlParameter("address_line1", Types.VARCHAR)); declareParameter(new SqlParameter("address_line2", Types.VARCHAR)); declareParameter(new SqlParameter("address_city", Types.VARCHAR)); declareParameter(new SqlParameter("address_state", Types.VARCHAR)); declareParameter(new SqlParameter("address_zip", Types.VARCHAR)); declareParameter(new SqlParameter("age", Types.INTEGER)); compile(); }
}
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"); }
}
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>
</source>