首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

应用spring的jdbcTemplate查询返回对象

2012-08-21 
使用spring的jdbcTemplate查询返回对象数据库中的数据表:create table client(????? clientId???? int ide

使用spring的jdbcTemplate查询返回对象

数据库中的数据表:

create table client

(

????? clientId???? int identity(1,1),

????? clientName??????? varchar(100)

)

?

创建返回对象类:

public class client

{

????? private Integer clientId;

????? private String clientName;

?

????? public client()

???? {

???? }

?

????? public Integer getClientId() {
?? ??? ?return this.clientId;
?? ?}

?? ?public void setClientId(Integer clientId) {
?? ??? ?this.clientId = clientId;
?? ?}

?? ?public String getClientName() {
?? ??? ?return this.clientName;
?? ?}

?? ?public void setClientName(String clientName) {
?? ??? ?this.clientName = clientName;
?? ?}

}

?

?

使用spring的jdbcTemplate查询返回对象

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("bean.xml"));

org.springframework.jdbc.core.JdbcTemplate template = (org.springframework.jdbc.core.JdbcTemplate) factory.getBean("jdbcTemplate");

java.util.List<client> list = (java.util.List<hbconfig.client>)template.query(
??? ??? ??? ??? "select * from client", new ResultSetExtractor() {

??? ??? ??? ??? ??? public Object extractData(ResultSet arg0)
??? ??? ??? ??? ??? ??? ??? throws SQLException, DataAccessException {
??? ??? ??? ??? ??? ??? java.util.List<hbconfig.Client> list = new java.util.ArrayList<Client>();
??? ??? ??? ??? ??? ??? while (arg0.next()) {
??? ??? ??? ??? ??? ??? ??? client c = new client();
??? ??? ??? ??? ??? ??? ??? c.setClientId(arg0.getInt("clientId"));
??? ??? ??? ??? ??? ??? ??? c.setClientName(arg0.getString("clientName"));
??? ??? ??? ??? ??? ??? ??? list.add(c);
??? ??? ??? ??? ??? ??? }
??? ??? ??? ??? ??? ??? return list;
??? ??? ??? ??? ??? }

??? ??? ??? ??? });
??? ??? for(hbconfig.Client c : list)
??? ??? {
??? ??? ??? System.out.println(c.getClientName());
??? ??? }

?

bean.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"
??? ??? xsi:schemaLocation="http://www.springframework.org/schema/beans
??? ???? ??? ??? ??? ??? ??? http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
??? ??? default-autowire="byName">

<bean id="dataSource" destroy-method="close">?????
<property name="driverClass" value="com.mysql.jdbc.Driver"/>?????
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/wangfu"/>?????
<property name="user" value="root"/>?????
<property name="password" value="root"/>?????
</bean>??
<bean id="jdbcTemplate" ref="dataSource"/>
</bean>

</beans>

热点排行