mybatis+mysql/oracle 数据库批量插入,主键自增长

1 mybatis+oracle

		
		
			com.oracle
			ojdbc6
			11.2.0.4.0-atlassian-hosted
		

1.1 oracle 序列

 创建序列

CREATE SEQUENCE SEQ_SMS_SUPPLIER   
INCREMENT BY 1  
NOMAXVALUE  
NOCYCLE  
CACHE 10; 

1.2 主键自增长

1.21 使用序列

 
  
   SELECT SEQ_SMS_SUPPLIER.nextval FROM dual
  
  INSERT INTO
  t_sms_supplier(id,supplierId,username,password,usestatus,connstatus,suppliername,supplieraddress)
  VALUES(#{id},#{supplierId,jdbcType=VARCHAR},
  #{username,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR},
  #{useStatus,jdbcType=NUMERIC},#{connStatus,jdbcType=NUMERIC},
  #{supplierName,jdbcType=VARCHAR},#{supplierAddress,jdbcType=VARCHAR})
 

keyProperty是指vo类中的主键属性名称,resultType是指vo类中的主键属性类型,order有两个属性,一个是AFTER是指限制性插入语句,一个是BEFORE是指先执行selectKey标签内的语句 

 或者,此时标签内的order属性为AFTER


  	insert into t_sms_supplier(ID,MEMBER_ID) values(SEQ_SMS_SUPPLIER.nextval,#{memberId})
  

详解 


	 
	 	
	 	
	 		
		 	
				SELECT seq_deptno.nextval FROM dual
			
	 	
	 		
			
				insert into dept(deptno,dname,loc) 
				values (#{deptno},#{dname},#{loc})
			
	

1.22 使用序列加触发器

创建触发器

create or replace trigger loginlog_trigger
before insert on ap_loginlog
for each row
begin
select loginlog_sequence.nextval into :new.id from dual;
end loginlog_trigger;

然后再sql语句中插入


    insert into ap_loginlog(MEMBER_ID) values(#{memberId})

 

1.3  借助序列插入和不借助序列批量插入

   insert into table(...) (select ... from dual) union all (select ... from dual)

方式一


        INSERT ALL
        
        INTO T_APPLAUD
        (
            ID,
            USER_ID,
            BUSINESS_TYPE,
            PRODUCT_ID,
            CREATE_TIME
        ) VALUES
        (
            #{item.id, jdbcType=NUMERIC},
            #{item.userId, jdbcType=VARCHAR},
            #{item.businessType, jdbcType=VARCHAR},
            #{item.productId, jdbcType=VARCHAR},
            #{item.createdTime, jdbcType=NUMERIC} 
        )
        
        SELECT 1 FROM DUAL
    

方式二

    
     
    
    
    
        INSERT INTO cm_termtypes
        (TERMTYPEID, PARENTTYPEID,
        TERMTYPECODE,TERMTYPENAME,ITEMSTYPE,ISENABLED,TYPEREMARK,CREATORID,CREATETIME,LASTMODIFYID,LASTMODIFYTIME)
         select cd.* from(
        
          select
            #{item.termTypeId},
            #{item.parentTypeId},
            #{item.termTypeCode},
            #{item.termTypeName},
            #{item.itemsType},
            #{item.isEnabled},
            #{item.typerEmark},
            #{item.creatorId},
            #{item.creatTime},
            #{item.lastModifyId},
            #{item.lastModifyTime}
           from dual
        
        ) cd
    

    
    
        INSERT INTO cm_treetermdata
        (   ID, 
            TERMTYPEID,
            PARENTID,
            TREETERMCODE,
            TREETERMNAME,
            ORDERID,
            ISENABLED,
            REMARK,
            CREATORID,
            CREATETIME,
            LASTMODIFYID,
            LASTMODIFYTIME  )
        select CM_TREETERMDATA_SEQUENCE.nextval ID, cd.* from(
        
            select
            #{item.termTypeId},
            #{item.parentId},
            #{item.treeTermCode},
            #{item.treeTermName},
            #{item.orderId},
            #{item.isEnabled},
            #{item.remark},
            #{item.creatorId},
            #{item.creatTime},
            #{item.lastModifyId},
            #{item.lastModifyTime}
            from dual
        
         ) cd
    

若包错mybatis 批量插入数据到oracle报 ”java.sql.SQLException: ORA-00933: SQL 命令未正确结束“  错误解决方法:  

mybatis批量插入oracle时需要显式指定为 useGeneratedKeys="false",没有指定useGeneratedKeys="false" 也不会报错

1.3 mybatis 插入oracle数据库报“Try setting a different JdbcType for this parameter or a different jdbcTypeForNull”错误 

postgreSQL,MySQL,SQLSERVER都支持JdbcType.NULL类型,Oracle,DB2是不支持,适配的时候也因为这个问题导致mybatis报错。

比如,之前配置#{submitDate},它会在oracle中报错:Error settingnull parameter

更改成#{submitDate,jdbcType=DATE},注意jdbcType是区分大小写的。

org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: org.apache.ibatis.type.TypeException: Error setting null for parameter #3 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: 无效的列类型
### The error may exist in UserMapper.xml
### The error may involve com.queen.mybatis.mapper.UserMapper.addUserMap-Inline
### The error occurred while setting parameters
### SQL: insert into   t_user(id,loginId,userName,role,note)   values(?,?,?,?,?)
### Cause: org.apache.ibatis.type.TypeException: Error setting null for parameter #3 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: 无效的列类型
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:154)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:141)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:51)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
	at com.sun.proxy.$Proxy2.addUserMap(Unknown Source)
	at com.queen.mybatis.MyBatisTest.testAdd(MyBatisTest.java:41)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.apache.ibatis.type.TypeException: Error setting null for parameter #3 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: 无效的列类型
	at org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:45)
	at org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(DefaultParameterHandler.java:81)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.parameterize(PreparedStatementHandler.java:80)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.parameterize(RoutingStatementHandler.java:61)
	at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:74)
	at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:47)
	at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:105)
	at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:71)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:152)
	... 28 more
Caused by: java.sql.SQLException: 无效的列类型
	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
	at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
	at oracle.jdbc.driver.OracleStatement.getInternalType(OracleStatement.java:3424)
	at oracle.jdbc.driver.OraclePreparedStatement.setNullCritical(OraclePreparedStatement.java:4197)
	at oracle.jdbc.driver.OraclePreparedStatement.setNull(OraclePreparedStatement.java:4186)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:70)
	at com.sun.proxy.$Proxy4.setNull(Unknown Source)
	at org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:43)
	... 36 more

MyBatis 插入空值时,需要指定JdbcType ,否则会报错。 

解决方法一:指定JdbcType


	
		select SEQ_T_USER_ID.nextval from dual
	
	insert into
	t_user(
		id,
		loginId,
		userName,
		role,
		note)
	values(
		#{id},
		#{loginId,jdbcType=VARCHAR},
		#{userName,jdbcType=VARCHAR},
		#{role,jdbcType=VARCHAR},
		#{note,jdbcType=VARCHAR}
	)

解决方法二:

MyBatis-config.xml 中设置当JDBC类型为空值时,要指定的值得,默认为OTHER,指定为NULL(注意是大写的NULL)。

       
             
                
                
                
               
                
                
               
                
             
               
                            

               
                              

               
                              

               
               
               
               
                              

               
               
             
               
                             

              
               
               
              
               
             
               
              
               
              
               
               
       

springboot 

application.yml

mybatis-plus:
  configuration:
    jdbc-type-for-null: 'null' #注意:单引号

解决方法三:

查看mp-starter-源码, 可以发现,第119行有一个configurationCustomizers,可以修改configuration

自定义一个,配上就完工

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new MybatisPlusCustomizers();
    }

    class MybatisPlusCustomizers implements ConfigurationCustomizer {

        @Override
        public void customize(org.apache.ibatis.session.Configuration configuration) {
            configuration.setJdbcTypeForNull(JdbcType.NULL);
        }

解决方法四:

第一步:把 可更新为空的 javabean 属性前加上注解:@TableField(el = "username, jdbcType=VARCHAR")

@Email
@TableField(el = "email, jdbcType=VARCHAR")
private String email;

 第二步: 使用updateAllColumnById方法,而不是updateById.    如:

 this.baseMapper.updateAllColumnById(user); 

2 mybatis+mysql

批量插入

	
		INSERT INTO common_termtypes
		(TERM_TYPE_ID, PARENT_TYPE_ID,
		TERM_TYPE_CODE,TERM_TYPE_NAME,ITEMS_TYPE,IS_ENABLED,TYPER_EMARK,CREATOR_ID,CREAT_TIME,LAST_MODIFY_ID,LAST_MODIFY_TIME)
		VALUES
		
			(#{item.termTypeId}, #{item.parentTypeId},
			#{item.termTypeCode},#{item.termTypeName},#{item.itemsType},#{item.isEnabled},#{item.typerEmark},#{item.creatorId},#{item.creatTime}
			,#{item.lastModifyId},#{item.lastModifyTime})
		
	

单条插入 


	
		insert into dept(dname,loc) values (#{dname},#{loc});
	

mysql 获取自增主键的下一个值

select AUTO_INCREMENT from INFORMATION_SCHEMA.TABLES where TABLE_NAME='表名'

 

 

你可能感兴趣的:(oracle,数据库,mybatis,Springboot,mysql)