spring JdbcTemplate 保存多条数据出现问题

kong_resty 发布于 2012/05/09 17:11
阅读 2K+
收藏 0

我在进行保存多条数据的时候出错

            首先是spring 配置文件信息beans.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"
       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">
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
   <property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=gbk"/>
   <property name="username" value="root"/>
   <property name="password" value="12345"/>
   <!--连接池初始值的大小 -->
   <property name="initialSize" value="1"/>
   <!--连接池的最大值 -->
   <property name="maxActive" value="500"/>
   <!--最大空闲时间-->
   <property name="maxWait" value="100000"/>
   <!--最大空闲值:当经过一个高峰之后,连接池可以慢慢的将已经用不到的连接慢慢释放一部分,直至减少到-->
   <property name="maxIdle" value="2"/>
   <!--最小空闲值:当空闲的连接数小于阈值时,连接池就会预申请一些连接,以免洪峰来时不及时 -->
   <property name="minIdle" value="2"></property>
      </bean>
    
     <!--事物管理上面的数据源-->
     <bean name="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"></property>
     </bean>
    
     <!--采用@Transactional注解方式使用事物-->
     <tx:annotation-driven transaction-manager="txManager"/>
    
     <bean id="userDaoImpl" class="dao.impl.UserDaoImpl">
      <constructor-arg index="0" ref="dataSource"/>
     </bean>
</beans>

然后是dao实现类:

 public class UserDaoImpl implements UserDAO {
 private JdbcTemplate template;
 
 public UserDaoImpl(DataSource dataSource){
  template = new JdbcTemplate(dataSource);
 }
 
 @Override
 public void delete(int id) {
  template.update("delete from employee where id=?",new Object[]{id},new int[]{java.sql.Types.INTEGER});
 }

 @Override
 public Employee getEmployee(int id) {
  return (Employee) template.queryForObject("select * from employee where id = ?",new Object[]{id},
    new int[]{java.sql.Types.INTEGER},new UserDaoMapper());
 }

 @Override
 public List<Employee> getEmployees() {
  return template.query("select * from employee",new UserDaoMapper());
 }

 @Override
 public void save(Employee emp) {
  template.update("insert into employee (id,name) values(?,?)",new Object[]{emp.getId(),
    emp.getName()},new int[]{java.sql.Types.INTEGER,java.sql.Types.VARCHAR});
 }

 @Override
 public void update(Employee emp) {
  template.update("update employee set name=? where id=?",
    new Object[]{emp.getName(),emp.getId()},
    new int[]{java.sql.Types.VARCHAR,java.sql.Types.INTEGER});
 }

}

最后在测试类中测试:

   @Test
 public void testSave(){
  AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
  UserDAO dao = (UserDAO)context.getBean("userDaoImpl");
  for(int i =0;i<30;i++){
      dao.save(new Employee(i,"zhangsan"+i));
  }
  context.close();
 }

出现如下异常:   

    org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [insert into employee (id,name) values(?,?)]; Duplicate entry '13' for key 'PRIMARY'; nested exception is java.sql.SQLException: Duplicate entry '13' for key 'PRIMARY'
 at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:228)
 at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
 at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:607)
 at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:792)
 at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:850)
 at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:854)
 at dao.impl.UserDaoImpl.save(UserDaoImpl.java:35)
 at main.SpringJDBCTest.testSave(SpringJDBCTest.java:18)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
 at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
 at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73)
 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
 at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
 at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
 at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
 at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.sql.SQLException: Duplicate entry '13' for key 'PRIMARY'
 at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
 at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
 at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1129)
 at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:681)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1368)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1283)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1268)
 at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:102)
 at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:798)
 at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:591)
 ... 29 more

 

更令人奇怪的是 我从数据库中查找到了一部分插入的数据,我把数据删了,重新运行代码

还是出现以上错误,但是奇怪的是数据库中还是有数据 且比上次对一条记录。再删 再执行

还是会多一条

最后我尝试了把循环次数改小 运行正常了!!!

求有遇到过类似问题的兄弟帮忙答疑解惑下... 是不是我数据源 配置有点问题啊

 

 

 

 

 

        

加载中
0
baijian
baijian

exception is java.sql.SQLException: Duplicate entry '13' for key 'PRIMARY'


你看这句啊,这个是数据库报的错误啊,跟spring没啥关系的,应该是主键唯一约束。

0
阿影
阿影
呃!!!主键重复了
返回顶部
顶部