Spring JDBC

通过Spring框架提供的模板功能,执行SQL。以下是相关代码

Application.java

package com.bf;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application {

  public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      
      JDBCDAO printer = (JDBCDAO)context.getBean("dao");
      SpitterObj spitter = printer.getSpitter(1038);
      System.out.println(spitter.getLOT());
  }
}

JDBCDAO.java

package com.bf;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class JDBCDAO implements SpitterDAO {
    private static String GET_SQL = "select code_item from table where ID_NO = ?";

    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public SpitterObj getSpitter(int ljdm) {
        return jdbcTemplate.queryForObject(GET_SQL, new RowMapper<SpitterObj>() {
            public SpitterObj mapRow(ResultSet rs, int rowNum) throws SQLException {
                SpitterObj obj = new SpitterObj();
                obj.setLOT(rs.getString(1));
                return obj;
            }
        }, ljdm);
    }
}

SpitterDAO.java

package com.bf;

public interface SpitterDAO {
    SpitterObj getSpitter(int ljdm);
}

SpitterObj.java

package com.bf;

public class SpitterObj {
     private String ljdm;

    public String getLOT() {
        return ljdm;
    }
    public void setLOT(String ljdm) {
        this.ljdm = ljdm;
    }
}

applicationContext.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@IP:Port:orcl" />
        <property name="username" value="**" />
        <property name="password" value="**" />
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="dataSource" />
    </bean>
    <bean id="dao" class="com.bf.JDBCDAO" autowire="byName">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>
</beans>

引用的类

posted @ 2016-03-08 08:54  Season2009  阅读(199)  评论(0编辑  收藏  举报