在网上查了一些资料,竟没有Hibernate自定义数据类型映射oracle中xmlType.到国外网站上去找了一些,也不是很齐.后来折腾了一天,终于搞定了.发出来希望对网友们有点用.
package com.fireeagle.common.UserType;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleResultSet;
import oracle.sql.OPAQUE;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
public class UserXmlTypeHibernate implements UserType, Serializable{
private static final Class returnedClass = String.class; //属性的java类型
private static final int[] SQL_TYPES = new int[] {oracle.xdb.XMLType._SQL_TYPECODE}; //数据中类型
public int[] sqlTypes() {
return SQL_TYPES;
}
public Class returnedClass() {
return returnedClass;
}
public boolean equals(Object arg0, Object arg1) throws HibernateException {
if(arg0 == null || arg1 == null){
throw new HibernateException("None of the arguments can be null.");
}
if(arg0 instanceof oracle.xdb.XMLType && arg1 instanceof oracle.xdb.XMLType){
return arg0.equals(arg1);
}
return false;
}
public int hashCode(Object arg0) throws HibernateException {
return 0;
}
public Object nullSafeGet(ResultSet rs, String[] names, Object arg2) throws HibernateException, SQLException {
OracleResultSet ors = (OracleResultSet) rs;
OPAQUE op = ors.getOPAQUE(names[0]);
oracle.xdb.XMLType xt= oracle.xdb.XMLType.createXML(op);
return xt.getStringVal();
}
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
Connection conn = st.getConnection ();
OPAQUE aClob=oracle.xdb.XMLType.createXML(conn,(String) value);
st.setObject(index, aClob);
}
public Object deepCopy(Object value) throws HibernateException {
return value;
}
public boolean isMutable() {
return false;
}
public Serializable disassemble(Object arg0) throws HibernateException {
return null;
}
public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
return null;
}
public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
return null;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.Test" table="Test">
<id name="resourceId" type="string" unsaved-value="" column="resourceId">
<generator class="uuid.hex"/>
</id>
//vo中xml为字符串.如
<root> <name>刘正仁<name></root>
数据库中testXml类型为xmlType
<property name="testXml" type="com.fireeagle.common.UserType.UserXmlTypeHibernate">
<column name="testXml" not-null="true"/>
</property>
</class>
</hibernate-mapping>
有三个jar包要放到lib下.xmlparserv2.jar xdb.jar nls_charset12.jar
这三个jar文件可以在oracle安装目录下面找到.