getJdbcTemplate().batchUpdate(sql,new BatchPreparedStatementSetter() {})总是返回-2怎么办

yinweihong 2008-10-10 05:41:35
纪录已经被正确更新了
如题,各位兄弟,急

网上搜了一下,有人说是因为数据库驱动的原因,但是做批处理以外的操作都没有问题啊,oracle9的
...全文
1704 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yinweihong 2008-10-13
  • 打赏
  • 举报
回复
揭帖,谢谢楼上几位~
yinweihong 2008-10-13
  • 打赏
  • 举报
回复
从上面两个连接,写成这样子过去了。。

public class LockDaoEx extends JdbcDaoSupport {

private static final Log log = LogFactory.getLog(LockDaoEx.class);

private UpdateLock updateLock;

protected void initDao() throws Exception {
updateLock = new UpdateLock(getDataSource());
}

public int batchUpdate(Object[] params) {
log.debug("BatchingBatcher#batchUpdate() start.");
int ret = 0;
try {
ret = updateLock.batchUpdate(params);
} catch (DataAccessException _ex) {
throw _ex;
} finally {
log.debug("BatchingBatcher#batchUpdate() end.");
}
return ret;
}

private static class UpdateLock extends SqlUpdate {

private static final String sql = ResourceBean.getResourceStr(
MPEConstant.QUERY_PROP_LOCATION, "UPDATE_LOCK");

public UpdateLock(DataSource ds) {
super(ds, sql);
// SQL実行タイムアウトの設定
this.setJdbcTemplate(new JdbcTemplate(ds) {
protected void applyStatementSettings(Statement state)
throws SQLException {
state.setQueryTimeout(MPEConstant.QUERY_TIMEOUT);
}
});
declareParameter(new SqlParameter(Types.CHAR));
declareParameter(new SqlParameter(Types.CHAR));
declareParameter(new SqlParameter(Types.CHAR));
compile();
}

protected int batchUpdate(Object[] params) throws DataAccessException {
if (params != null) {
String[] sqlArray = new String[params.length];
for (int i = 0; i < params.length; i++) {
sqlArray[i] = MPEDBUtil.getFullSqlString(
(Object[]) params[i], sql);
}
return flush(sqlArray);
}
return -1;
}

private int flush(String[] sql) {
int[] affected = getJdbcTemplate().batchUpdate(sql);
int totalRowsAffected = 0;
for (int i = 0; i < affected.length; i++) {
totalRowsAffected += affected[i];
}
return totalRowsAffected;
}
}

public static void main(String[] args) {
LockDaoEx updateLock = (LockDaoEx) SpringWrpCmp.getComponent("updateLock");
Object[] orgs1 = new Object[] { "T_SGYOTEI ", "yinwh ",
MPEDBUtil.fillingAfterStr("1", " ", 20) };
Object[] orgs2 = new Object[] { "T_SGYOTEI ", "yinwh ",
MPEDBUtil.fillingAfterStr("2", " ", 20) };
Object[] orgs3 = new Object[] { "T_SGYOTEI ", "yinwh ",
MPEDBUtil.fillingAfterStr("3", " ", 20) };
System.out.println(""
+ updateLock.batchUpdate(new Object[] { orgs1, orgs2, orgs3 }));
}
}
yinweihong 2008-10-12
  • 打赏
  • 举报
回复
找到2个东西
hibernate
http://forum.hibernate.org/viewtopic.php?p=2394664
Spring
http://forum.springframework.org/archive/index.php/t-23378.html

明天去公司再弄一下才知道~。。。
無名VF 2008-10-12
  • 打赏
  • 举报
回复
UP
sebatinsky 2008-10-11
  • 打赏
  • 举报
回复
这两天搞得头晕,希望你早日解决,呵呵,等我也成为高手,再来探讨了,网上查查
sunyujia 2008-10-10
  • 打赏
  • 举报
回复
如果是数据库驱动的问题确实除了换驱动就无解了,只能是换驱动(oracle每个驱动bug都很多)
可以写个存储过程实现需求,性能更高。
yinweihong 2008-10-10
  • 打赏
  • 举报
回复
如果说是驱动的问题,意思就是没解? 还是想问问,看各位是否碰到类似问题~
Spring 出品的 JdbcTemplate 对于不想使用hibernate或者ibatis那样需要大量学习成本而且还想获得对象化的人来说是很好用的。但是 JdbcTemplate还是有很多不足之处或者说是缺点。比如你没法像hibernate那样直接传一个对象给它让他拆分成sql并保存起来,当然这也是可以理解的,毕竟它并没有要求你去写 hbm.xml 文件所以无法知道你哪些字段要映射,哪些不要等等。又比如JdbcTemplate 可以帮忙把一个查询结果传化为一个对象列表,但是你需要查阅一些资料才知道要用 BeanPropertyRowMapper 。如果下次要用的时候又忘记了这个类,又要查一次或者翻以前的代码来看,其实完全可以提供一个方法直接传一个PO类进去自动创建BeanPropertyRowMapper 。基于以上的一些不足之处,我建立了 JdbcTemplateTool 它有以下特性:把查询结果转换为PO列表,不需要调用BeanPropertyRowMapper传一条统计sql比如 aselect count(1) from table可以直接返回一个数字作为结果,不需要自己实现中间步骤。可以直接把一个PO类存到数据库通过PO类和一个id可以获取到该对象通过PO类可以直接update数据库记录不需要实现 BatchPreparedStatementSetter, 就可以批量update通过一个对PO对象删除对应的数据库记录依然可以使用原始的JdbcTemplate目前只在mysql上测试.Maven 依赖   org.crazycake   jdbctemplatetool   1.0.4-RELEASE 快速开始STEP 1. 创建一个maven项目    创建一个maven项目叫testjtt. 添加jdbctemplatetool 依赖到pom.xml. 再添加以下依赖到 pom.xml.   junit   junit   4.11   test     org.springframework     spring-context     3.2.2.RELEASE     test     com.mchange     c3p0     0.9.2.1     test     mysql     mysql-connector-java     5.1.19     test     org.springframework     spring-test     3.2.2.RELEASE     test 最好使用 1.6 jdk. 我并没有在 1.5 下测试STEP 2. 创建测试数据库    创建一个测试的数据库叫jtt_test创建一个用户travis不要分配密码. 赋予jtt_test的权限给travis.CREATE USER 'travis'@'%' IDENTIFIED BY ''; GRANT ALL ON jtt_test.* TO 'travis'@'%'; flush privileges;创建一张表employee插入一些测试数据.DROP TABLE IF EXISTS `employee`; CREATE TABLE `employee` (   `id` int(11) NOT NULL,   `name` varchar(300) NOT NULL,   `join_date` datetime NOT NULL,   `age` int(11) NOT NULL,   PRIMARY KEY  (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `employee` */ insert  into `employee`(`id`,`name`,`join_date`,`age`) values (1,'jack','2014-09-22 00:00:00',23),(2,'ted','2014-08-30 00:00:00',25),(3,'jim','2014-06-22 00:00:00',33);STEP 3. 配置一下spring    在test文件夹下创建resources文件夹. 添加resources到 source folder 修改输出为target/test-classes创建spring.xml在 test/resources 里面<?xml version="1.0" encoding="UTF-8"?>              jdbc:mysql://localhost:3306/jtt_test?characterEncoding=utf8         com.mysql.jdbc.Driver         travis         password">          jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">                          jdbcTemplateTool" class="org.crazycake.jdbcTemplateTool.JdbcTemplateTool">         jdbcTemplate" ref="jdbcTemplate" />      STEP 4. 创建PO类    创建Employee.javaimport java.sql.Timestamp; import javax.persistence.Id; public class Employee {     private Integer id;     private String name;     private Timestamp joinDate;     private Integer age;     @Id     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;     }     public Timestamp getJoinDate() {         return joinDate;     }     public void setJoinDate(Timestamp joinDate) {         this.joinDate = joinDate;     }     public Integer getAge() {         return age;     }     public void setAge(Integer age) {         this.age = age;     } }STEP 5. 创建测试用例    创建HelloJTTTest.javaimport static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; import org.crazycake.jdbcTemplateTool.JdbcTemplateTool; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; @ContextConfiguration(locations={"classpath:spring.xml"}) public class HelloJTTTest extends AbstractJUnit4SpringContextTests{     @Test     public void testSave(){         JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);         Employee e = new Employee();         e.setId(4);         e.setName("billy");         Date now = new Date();         e.setJoinDate(new Timestamp(now.getTime()));         e.setAge(33);         try {             jtt.save(e);         } catch (Exception e1) {             e1.printStackTrace();         }     } }STEP 6. 启动!    运行测试用例,等待绿色条。然后去数据库会看到多了一条记录 :idnamejoin_dateage4billy2014-09-24 22:51:2033高级教程    以下是各个方法的详细介绍list把查询结果转换为PO列表,不需要调用BeanPropertyRowMapper。 自动根据数据库的列将下划线转为驼峰命名规则映射类的属性.@Test public void testList(){     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     List es = jtt.list("select * from employee where age < ? order by id desc", new Object[]{30}, Employee.class);     assertThat(new Integer(es.size()),is(2));     assertThat(es.get(1).getName(),is("jack")); }count    传一条统计sql比如 aselect count(1) from table可以直接返回一个数字作为结果,不需要自己实现中间步骤。@Test public void testCount() throws IOException, SQLException {     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     int total = jtt.count("select count(1) from employee", null);     assertThat(total,is(4));     }save可以直接把一个PO类存到数据库。如果你不想把某个列映射为数据库字段可以使用 @Trasient 注解在getter上public class Student {     private Integer id;     private String name;     private String nothing;     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;     }     @Transient     public String getNothing() {         return nothing;     }     public void setNothing(String nothing) {         this.nothing = nothing;     } }这个字段会被跳过@Test public void testSave() throws Exception {     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     Student s = new Student();     s.setName("michael");     s.setNothing("nothing");     jtt.save(s); }get    通过PO类和一个id可以获取到该对象。但是前提是需要在主键的getter上标上 @Id 注解@Id public Integer getId() {     return id; }例子@Test public void testGet() throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException, IOException, SQLException {     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     Employee e = jtt.get(Employee.class, 3);     assertThat(e.getName(),is("jim")); }update    自动根据PO类更新数据库. 记得增加@Id.@Test public void testUpdate() throws Exception {     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     Employee e = jtt.get(Employee.class, 1);     e.setAge(23);     jtt.update(e); }batchUpdate    批量更新@Test public void testBatchUpdate() throws SQLException, IOException {     build();     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     List<Object[]> params = new ArrayList<Object[]>();     Object[] p1 = new Object[]{23,"jack"};     params.add(p1);     Object[] p2 = new Object[]{29,"tim"};     params.add(p2);     jtt.batchUpdate("update employee set age = ? where name = ?", params); }delete    删除数据库对象@Test public void testDelete() throws Exception {     JdbcTemplateTool jtt = super.applicationContext.getBean("jdbcTemplateTool",JdbcTemplateTool.class);     Employee e = new Employee();     e.setId(1);     jtt.delete(e); }getJdbcTemplate    你依然可以使用原始的JdbcTemplate. 调用JdbcTemplateTool.getJdbcTemplate()to getJdbcTemplate就可以了。

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧