package com.royzhou.jdbc;
import java.util.ArrayList;
import java.util.List;
/**
* 当前页对象
* @author gengmm
* @param <E>
*/
public class CurrentPage<E> {
private int pageNumber;
private int pagesAvailable;
private List<E> pageItems = new ArrayList<E>();
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public void setPagesAvailable(int pagesAvailable) {
this.pagesAvailable = pagesAvailable;
}
public void setPageItems(List<E> pageItems) {
this.pageItems = pageItems;
}
public int getPageNumber() {
return pageNumber;
}
public int getPagesAvailable() {
return pagesAvailable;
}
public List<E> getPageItems() {
return pageItems;
}
}
package com.royzhou.jdbc;
public class JdbcSqlCollection {
//当前页最多显示记录数目
public static final int PAGERECORDS=10;
}
package com.royzhou.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
/**
* 分页的助手类
* @author gengmm
*
* @param <E>
*/
public class PaginationHelper<E> {
@SuppressWarnings("unchecked")
public CurrentPage<E> fetchPage(final JdbcTemplate jt,
final String sqlCountRows, final String sqlFetchRows,
final Object args[], final int pageNo, final int pageSize,
final ParameterizedRowMapper<E> rowMapper) {
// determine how many rows are available
final int rowCount = jt.queryForInt(sqlCountRows, args);
// calculate the number of pages
int pageCount = rowCount / pageSize;
if (rowCount > pageSize * pageCount) {
pageCount++;
}
// create the page object
final CurrentPage<E> page = new CurrentPage<E>();
page.setPageNumber(pageNo);
page.setPagesAvailable(pageCount);
// fetch a single page of results
final int startRow = (pageNo - 1) * pageSize;
jt.query(sqlFetchRows, args, new ResultSetExtractor() {
public Object extractData(ResultSet rs) throws SQLException,
DataAccessException {
final List pageItems = page.getPageItems();
int currentRow = 0;
while (rs.next() && currentRow < startRow + pageSize) {
if (currentRow >= startRow) {
pageItems.add(rowMapper.mapRow(rs, currentRow));
}
currentRow++;
}
return page;
}
});
return page;
}
}
package com.royzhou.jdbc;
public class PersonBean {
private int id;
private String name;
private int sex;
private int age;
private String homeAddress;
private String companyAddress;
private String aiHao;
private String remark;
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getCompanyAddress() {
return companyAddress;
}
public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}
public String getAiHao() {
return aiHao;
}
public void setAiHao(String aiHao) {
this.aiHao = aiHao;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public PersonBean() {
}
public PersonBean(String name) {
this.name = name;
}
public PersonBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.id + ":" + this.name;
}
}
package com.royzhou.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
@SuppressWarnings("unchecked")
public class PersonRowMapper implements ParameterizedRowMapper {
//默认已经执行rs.next(),可以直接取数据
public Object mapRow(ResultSet rs, int index) throws SQLException {
PersonBean pb = new PersonBean();
pb.setId(rs.getInt("id"));
pb.setName(rs.getString("name"));
pb.setAge(rs.getInt("age"));
pb.setSex(rs.getInt("sex"));
pb.setAiHao(rs.getString("ai_hao"));
pb.setCompanyAddress(rs.getString("company_address"));
pb.setHomeAddress(rs.getString("home_address"));
pb.setRemark(rs.getString("remark"));
return pb;
}
}
package com.royzhou.jdbc;
import java.util.List;
import org.springframework.dao.DataAccessException;
public interface PersonService {
public void addPerson(PersonBean person) throws Exception;
public void addBatchPerson(List<PersonBean> person) throws Exception;
public void updatePerson(PersonBean person);
public void deletePerson(int id);
public PersonBean queryPerson(int id);
public List<PersonBean> queryPersons();
public List<PersonBean> getAllCompanyTest(int pageNo) throws DataAccessException;
}
package com.royzhou.jdbc;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service("personService")
public class PersonServiceImpl implements PersonService {
@Resource
private JdbcTemplate jdbcTemplate;
/**
* 通过Spring容器注入datasource
* 实例化JdbcTemplate,该类为主要操作数据库的类
* @param ds
public void setDataSource(DataSource ds) {
this.jdbcTemplate = new JdbcTemplate(ds);
}
*/
public void addPerson(PersonBean person) throws Exception {
/**
* 第一个参数为执行sql
* 第二个参数为参数数据
* 第三个参数为参数类型
*/
try {
jdbcTemplate.update("insert into person (name,sex,age,home_address,company_address,ai_hao,remark) values(?,?,?,?,?,?,?)",
new Object[]{person.getName(),person.getSex(),person.getAge(),person.getHomeAddress(),person.getCompanyAddress(),person.getAiHao(),person.getRemark()},
new int[]{Types.VARCHAR,Types.INTEGER,Types.INTEGER,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR});
} catch (Exception e) {
throw new RuntimeException("运行期异常支持事务回滚");
}
//throw new RuntimeException("运行期异常支持事务回滚");
//throw new Exception("其他异常不支持事务回滚");
}
public void deletePerson(int id) {
jdbcTemplate.update("delete from person where id = ?", new Object[]{id}, new int[]{Types.INTEGER});
}
@SuppressWarnings("unchecked")
public PersonBean queryPerson(int id) {
/**
* new PersonRowMapper()是一个实现RowMapper接口的类,
* 执行回调,实现mapRow()方法将rs对象转换成PersonBean对象返回
*/
List<PersonBean> pbs = (List<PersonBean>)jdbcTemplate.query("select id,name from person where id = ?", new Object[]{id}, new PersonRowMapper());
PersonBean pb = null;
if(pbs.size()>0) {
pb = pbs.get(0);
}
return pb;
}
@SuppressWarnings("unchecked")
public List<PersonBean> queryPersons() {
List<PersonBean> pbs = (List<PersonBean>) jdbcTemplate.query(" select number,name from spt_values ", new PersonRowMapper());
return pbs;
}
public void updatePerson(PersonBean person) {
jdbcTemplate.update("update person set name = ? where id = ?", new Object[]{person.getName(), person.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});
}
@SuppressWarnings("unchecked")
public List<PersonBean> getAllCompanyTest(int pageNo) throws DataAccessException {
PaginationHelper<PersonBean> ph = new PaginationHelper<PersonBean>();
List<PersonBean> c=new ArrayList<PersonBean>();
try {
CurrentPage<PersonBean> p=ph.fetchPage(
jdbcTemplate,
" select count(*) from person ",
" select * from person ",
new Object[]{},
pageNo,
JdbcSqlCollection.PAGERECORDS,
new PersonRowMapper()
);
c=p.getPageItems();
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
public void addBatchPerson(final List<PersonBean> personList) throws Exception {
try {
String sql=" insert into person (name,sex,age,home_address,company_address,ai_hao,remark) values(?,?,?,?,?,?,?) ";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
public int getBatchSize() {
return personList.size();
}
public void setValues(PreparedStatement ps, int index)
throws SQLException {
String name = personList.get(index).getName();
int sex = personList.get(index).getSex();
int age = personList.get(index).getAge();
String homeAddress = personList.get(index).getHomeAddress();
String companyAddress = personList.get(index).getCompanyAddress();
String aiHao = personList.get(index).getAiHao();
String remark = personList.get(index).getRemark();
ps.setString(1, name);
ps.setInt(2, sex);
ps.setInt(3, age);
ps.setString(4, homeAddress);
ps.setString(5, companyAddress);
ps.setString(6, aiHao);
ps.setString(7, remark);
}
});
} catch (Exception e) {
throw new RuntimeException("运行期异常支持事务回滚");
}
}
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClassName}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}" />
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}" />
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}" />
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="${minIdle}" />
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 定义事务传播属性XML配置 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
<!-- 一致性事务 -->
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
<!-- 一致性事务 -->
<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
<!-- 一致性事务 -->
<tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" />
<!-- 只读事务-->
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointCut" expression="execution(* com.royzhou.jdbc..*.*(..))"/>
<aop:advisor pointcut-ref="transactionPointCut" advice-ref="txAdvice"/>
</aop:config>
</beans>
#sqlserver2008数据源
driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://192.168.1.123:1433;databaseName=gsjg
username=sa
password=12345
initialSize=1
maxActive=500
maxIdle=100
minIdle=1
log4j da控制台显示sql
## JdbcTemplate print sql
log4j.logger.org.springframework.jdbc.core.JdbcTemplate=debug