mybatis如何读取clob数据 详细过程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis如何读取clob数据 详细过程相关的知识,希望对你有一定的参考价值。
1、MyBatis介绍
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)
2、CLOB
SQL CLOB 是内置类型,它将字符大对象 (Character Large Object) 存储为数据库表某一行中的一个列值。默认情况下,驱动程序使用 SQL locator(CLOB) 实现 Clob 对象,这意味着 CLOB 对象包含一个指向 SQL CLOB 数据的逻辑指针而不是数据本身。Clob 对象在它被创建的事务处理期间有效。
3、MyBatis对CLOB类型数据实现增删改查
oracle表结构
create table T_USERS(
ID NUMBER not null,
NAME VARCHAR2(30),
SEX VARCHAR2(3),
BIRS DATE,
MESSAGE CLOB
)
create sequence SEQ_T_USERS_ID
minvalue 1
maxvalue 99999999
start with 1
increment by 1
cache 20;
配置mybatis配置文件UsersMapper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN">
<mapper namespace="examples.mapper.UsersMapper" >
<!-- Result Map-->
<resultMap type="examples.bean.Users" id="BaseResultMap">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="sex" column="sex" />
<result property="birs" column="birs" jdbcType="TIMESTAMP"/>
<result property="message" column="message" jdbcType="CLOB"
javaType = "java.lang.String" typeHandler ="examples.service.OracleClobTypeHandler"/>
</resultMap>
<sql id="Tabel_Name">
t_users
</sql>
<!-- 表中所有列 -->
<sql id="Base_Column_List" >
id,name,sex,birs,message
</sql>
<!-- 查询条件 -->
<sql id="Example_Where_Clause">
where 1=1
<trim suffixOverrides=",">
<if test="id != null">
and id = #id
</if>
<if test="name != null and name != \'\'">
and name like concat(concat(\'%\', \'$name\'), \'%\')
</if>
<if test="sex != null and sex != \'\'">
and sex like concat(concat(\'%\', \'$sex\'), \'%\')
</if>
<if test="birs != null">
and birs = #birs
</if>
<if test="message != null">
and message = #message
</if>
</trim>
</sql>
<!-- 2.查询列表 -->
<select id="queryByList" resultMap="BaseResultMap" parameterType="Object">
select
<include refid="Base_Column_List" />
from t_users
<include refid="Example_Where_Clause"/>
</select>
</mapper>
Mapper类接口
package examples.mapper;import java.util.List;
public interface UsersMapper<T>
public List<T> queryBySelective(T t);
public List<T> queryByList(T t);
类型转换工具类
package examples.service;import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.sql.CLOB;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class OracleClobTypeHandler implements TypeHandler<Object>
public Object valueOf(String param)
return null;
@Override
public Object getResult(ResultSet arg0, String arg1) throws SQLException
CLOB clob = (CLOB) arg0.getClob(arg1);
return (clob == null || clob.length() == 0) ? null : clob.getSubString((long) 1, (int) clob.length());
@Override
public Object getResult(ResultSet arg0, int arg1) throws SQLException
return null;
@Override
public Object getResult(CallableStatement arg0, int arg1) throws SQLException
return null;
@Override
public void setParameter(PreparedStatement arg0, int arg1, Object arg2, JdbcType arg3) throws SQLException
CLOB clob = CLOB.empty_lob();
clob.setString(1, (String) arg2);
arg0.setClob(arg1, clob);
Spring配置文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="
xmlns:xsi="
xmlns:mvc="
xmlns:tx="
xsi:schemaLocation="
default-autowire="byType">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>oracle.jdbc.driver.OracleDriver</value></property>
<property name="url"><value>jdbc:oracle:thin:@127.0.0.1:1521:pms</value></property>
<property name="username"><value>pms</value></property>
<property name="password"><value>pms</value></property>
</bean>
<!-- 配完数据源 和 拥有的 sql映射文件 sqlSessionFactory 也可以访问数据库 和拥有 sql操作能力了 -->
<!--
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations">
<list>
<value>classpath:examples/mybatis/oracle/UsersMapper.xml</value>
</list>
</property>
</bean>
<!-- 通过设置 mapperInterface属性,使接口服务bean 和对应xml文件管理 可以使用其中的sql -->
<bean id="dao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 此处等同于 Mybatis 中 ServerDao serverDao = sqlSession.getMapper(ServerDao.class); 指明映射关系 -->
<property name="mapperInterface" value="examples.mapper.UsersMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
测试类
package examples.service;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import examples.bean.Users;
import examples.mapper.UsersMapper;
public class TestUsersService
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ParseException
ApplicationContext ac =
new ClassPathXmlApplicationContext("classpath:/examples/service/spring.xml");
UsersMapper<Users> dao = (UsersMapper<Users>)ac.getBean("dao");
//查询
Users nullBean = new Users();
List<Users> list = dao.queryByList(nullBean);
if(list != null)
for(Users user : list)
System.out.println(user);
参考技术A
例子:
表结构
CREATE TABLE USERINFO(USERID VARCHAR2(5),USERNAME VARCHAR2(20),
MEMO CLOB,
constraint PK_USERINFO primary key(USERID));
java代码:
public class OracleClobTypeHandlerCallback implements TypeHandlerCallbackpublic void setParameter(ParameterSetter setter, Object obj)
throws SQLException
CLOB clob = CLOB.empty_lob();
clob.setString(1, (String)obj);
setter.setClob(clob);
public Object getResult(ResultGetter getter) throws SQLException
CLOB clob = (CLOB) getter.getClob();
return (clob == null || clob.length() == 0 )? null :clob.getSubString((long)1, (int)clob.length());
public Object valueOf(String param)
return null;
sqlmap配置:
<resultMap id="userResult" class="com.prs.application.ehld.sample.common.dto.UserInfoDTO"><result property="userID" column="USERID" columnIndex="1"/>
<result property="userName" column="USERNAME" columnIndex="2"/>
<result property="memo" column="memo" jdbcType="CLOB" javaType = "java.lang.String" typeHandler =" OracleClobTypeHandlerCallback "/>
</resultMap>
oracle如何操作clob数据类型
在存储过程里面,需要有个变量存储一段字符串,因为这段字符串可能很长,可能达到几万个字符,所以考虑用clob来存储,但是我在存储过程中如下写,报错message:=empty_clob();
DBMS_LOB.WRITEAPPEND(message, 10, '0123456789');说指定的lob定位符无效,谁知道如何往clob里面直接写入字符串,在线等。
CREATE OR REPLACE PROCEDURE prc_read_clob(
table_name IN VARCHAR2,
clob_column_name IN VARCHAR2,
primary_Key_Column_names IN VARCHAR2,
primary_key_values IN VARCHAR2,
offset_i IN NUMBER,
read_length_i IN NUMBER,
RES OUT VARCHAR2,
total_length OUT NUMBER
) AS
/**
Autor:Hanks_gao.
Create Date:2008/12/10
Description:This procedure is to read clob value by conditions
--------------------------------------------------------------
-----------------Parameters descritption----------------------
table_name : The table that contains clob/blob columns(表名)
clob_column_name : Clob/blob column name of table_name(类型为clob的字段名)
primary_key_column_names : The columns seperated by '' that can fix only one row data (that is primary key) (主键名,以''分隔的字符串)
primary_key_values : The primary keyes values that seperated by ''(主键键值,以''分隔的字符串)
offset_i : The offset of reading clob data(要读取的位移量)
read_length_i : The length of reading clob data per times(要读取的长度)
res : Return value that can be referenced by application(读取的结果)
total_length : The total length of readed clob data(数据库查询到的clob数据的总长度)
-----------------End Parameters descritption------------------
*/
tmpPrimaryKeys VARCHAR2(2000); --To save primary_Key_Column_names temporarily(暂存主键,主键是以''分隔的字符串)
tmpPrimaryKeyValues VARCHAR2(2000); --To save primary_key_values temporarily(暂存主键键值,以''分隔的字符串)
i NUMBER; --循环控制变量
tmpReadLength NUMBER; --暂存要读取的长度
sqlStr VARCHAR2(6000); --Query string(查询字符串)
sqlCon VARCHAR2(5000); --Query condition(查询条件)
TYPE tmparray IS TABLE OF VARCHAR2(5000) INDEX BY BINARY_INTEGER;
arrayPrimaryKeys tmparray; --To save the analyse result of primary_Key_Column_names (暂存分析后得到的主键名)
arrayPrimaryKeyValues tmparray; --To save the analyse result of primary_key_values(暂存分析后得到的主键键值)
BEGIN
total_length := 0;
RES := '';
DECLARE
clobvar CLOB := EMPTY_CLOB;
BEGIN
tmpPrimaryKeys:=primary_Key_Column_names;
tmpPrimaryKeyValues:=primary_key_values;
i:=0;
WHILE INSTR(tmpPrimaryKeys,'')>0 LOOP --Analyse the column names of primary key(将主键分开,相当于arrayPrimaryKeys =tmpPrimaryKeys.split("") )
arrayPrimaryKeys(i):=subSTR(tmpPrimaryKeys,1,(INSTR(tmpPrimaryKeys,'')-1));
tmpPrimaryKeys:=subSTR(tmpPrimaryKeys,(INSTR(tmpPrimaryKeys,'')+1));
i:=i+1;
END LOOP;
i:=0;
WHILE INSTR(tmpPrimaryKeyValues,'')>0 LOOP --Analyse the values of primary key
arrayPrimaryKeyValues(i):=subSTR(tmpPrimaryKeyValues,1,(INSTR(tmpPrimaryKeyValues,'')-1));
tmpPrimaryKeyValues:=subSTR(tmpPrimaryKeyValues,(INSTR(tmpPrimaryKeyValues,'')+1));
i:=i+1;
END LOOP;
IF arrayPrimaryKeys.COUNT()<>arrayPrimaryKeyValues.COUNT() THEN --判断键与键值是否能匹配起来
res:='KEY-VALUE NOT MATCH';
RETURN;
END IF;
i := 0;
sqlCon := '';
WHILE i < arrayPrimaryKeys.COUNT() LOOP
sqlCon := sqlCon || ' AND ' || arrayPrimaryKeys(i) || '='''
|| replace(arrayPrimaryKeyValues(i),'''','''''') || '''';
i := i + 1;
END LOOP;
sqlStr := 'SELECT ' || clob_column_name || ' FROM ' || table_name
|| ' WHERE 1=1 ' || sqlCon || ' AND ROWNUM = 1' ; --组查询字符串
dbms_lob.createtemporary(clobvar, TRUE);
dbms_lob.OPEN(clobvar, dbms_lob.lob_readwrite);
EXECUTE IMMEDIATE TRIM(sqlStr) INTO clobvar; --执行查询
IF offset_i <= 1 THEN
total_length:=dbms_lob.getlength(clobvar);
END IF;
IF read_length_i <=0 THEN
tmpReadLength := 4000;
ELSE
tmpReadLength := read_length_i;
END IF;
dbms_lob.READ(clobvar,tmpReadLength,offset_i,res); --读取数据
IF dbms_lob.ISOPEN(clobvar)=1 THEN
dbms_lob.CLOSE(clobvar);
END IF;
END;
EXCEPTION
WHEN OTHERS THEN
res:='';
total_length:=0;
END; 参考技术A clob 类型的操作很容易的,可以当成 varchar2 一样处理。blob处理上才困难一些。
以上是关于mybatis如何读取clob数据 详细过程的主要内容,如果未能解决你的问题,请参考以下文章