Target: 实现如下,通过Spring Jdbc,传入sql,查询满足条件的Java数据对象:
pojo:
public class ZmTest { public ZmTest() { // TODO Auto-generated constructor stub } private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ZmTest
sql:
create table zm_test_sjdbc( id number(3), name varchar2(20) );
表结构
SELECT id, name FROM ZM_TEST_SJDBC WHERE id = ?
query
Step:
一、自定义映射查询
package springjdbc; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql.DataSource; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.object.MappingSqlQuery; public class CustomerMappingQuery extends MappingSqlQuery { public CustomerMappingQuery(DataSource ds) { super(ds, "SELECT id, name FROM ZM_TEST_SJDBC WHERE id = ?");// WHERE id = ? super.declareParameter(new SqlParameter("id", Types.INTEGER)); compile(); } public ZmTest mapRow(ResultSet rs, int rowNumber) throws SQLException { ZmTest zmTest = new ZmTest(); zmTest.setId(Integer.valueOf(rs.getObject("id").toString())); zmTest.setName(rs.getString("name")); return zmTest; } }
CustomerMappingQuery
二、测试类
import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.springframework.jdbc.datasource.DriverManagerDataSource; public class Get_cmd_log { public Get_cmd_log(){ } public static void main(String[] args){ Get_cmd_log gcl = new Get_cmd_log(); gcl.getData(1); } //get Datasource public DataSource getDataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); ds.setUrl("jdbc:oracle:thin:@ip:port:name"); ds.setUsername("*******"); ds.setPassword("*******"); return ds; } @SuppressWarnings("unchecked") public List<ZmTest> getData(Integer id){ Get_cmd_log gcl = new Get_cmd_log(); DataSource dsource = gcl.getDataSource(); CustomerMappingQuery query = new CustomerMappingQuery(dsource); Object[] params = new Object[1]; params[0] = id; List resZm = query.execute(params); ZmTest zTest = new ZmTest(); zTest = (ZmTest)(resZm.get(0)); System.out.println(zTest.getName()); return resZm; } }
Get_cmd_log
测试结果: 获得对应id的name。
原理:
底层通过JdbcTemplate实现。
应用场景:
简单对象查询:如登录。
优点:
无需通过第三方ORM框架,提高效率。
Tips:
oracle 数字类型对应Java类型:
http://www.cnblogs.com/codegod/p/6826133.html
时间: 2024-12-20 01:21:44