用户可通过CREATE OPAQUE TYPE 语句创建自定义不透明类型。
同时, JDBC 调用该类型时,需要添加对应的映射关系并实现部分读写方法。
以数据库内置UDT类型 longlvarchar 为例,以下示例添加类型映射及完成插入及查询。
longlvarchar 定义为 4 字节对齐,不能使用内置的哈希函数,LVARCHAR最大256字节(超过按CLOB处理)。
create opaque type gbasedbt.longlvarchar ( internallength=variable, maxlen=256, alignment=4, cannothash );
longlvarchar对应readSQL、writeSQL实现
package udt;
import com.gbasedbt.jdbc.*;
import java.sql.*;
/**
* @author username
* @date 2024/4/29 9:15
*/
import java.sql.SQLException;
public class IfxLonglvarchar implements SQLData {
private String sql_type = "Longlvarchar";
public String str_value;
public IfxLonglvarchar() {
this.str_value="";
}
public IfxLonglvarchar(String str_value) {
this.str_value = str_value;
}
@Override
public String getSQLTypeName() throws SQLException {
return this.sql_type;
}
@Override
public void readSQL(SQLInput stream, String typeName) throws SQLException {
sql_type = typeName;
str_value = ((IfmxUDTSQLInput) stream).readString(((IfmxUDTSQLInput) stream).length());
}
@Override
public void writeSQL(SQLOutput stream) throws SQLException {
((IfmxUDTSQLOutput) stream).writeString(this.str_value,this.str_value.length());
}
@Override
public String toString() {
return this.str_value;
}
}
测试DEMO
import udt.IfxLonglvarchar;
import java.sql.*;
/**
* @author username
*/
public class Demo {
public static final String DBDRIVER = "com.gbasedbt.jdbc.Driver";
public static final String DBURL = "jdbc:gbasedbt-sqli://172.16.3.23:9351/mydb:GBASEDBTSERVER=gbase351;DB_LOCALE=zh_CN.utf8;CLIENT_LOCALE=zh_CN.utf8;IFX_USEPUT=1;OPTOFC=1;LOBCACHE=-1";
public static final String DBUSER = "gbasedbt";
public static final String DBPASS = "GBase123";
public static void main(String args[]) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
java.util.Map customtypemap = conn.getTypeMap();
if (customtypemap == null)
{
System.out.println("\n***ERROR: typemap is null!");
return;
}
customtypemap.put("longlvarchar", Class.forName("udt.IfxLonglvarchar"));
/*
create table test_longlvarchar (c1 int,c2 test_longlvarchar);
*/
IfxLonglvarchar llvc = new IfxLonglvarchar("test_longlvarchar");
pstmt = conn.prepareStatement("insert into tablonglvarchar values(1,?);");
pstmt.setObject(1,llvc);
pstmt.executeUpdate();
pstmt = conn.prepareStatement("select * from tablonglvarchar");
ResultSet resultSet = pstmt.executeQuery();
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
while (resultSet.next()) {
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
System.out.println(resultSetMetaData.getColumnName(i)+":"+resultSet.getObject(i).toString());
}
}
conn.close();
System.exit(0);
}
}