Created
December 2, 2019 12:06
-
-
Save e7/4d593b06c3c93d4307f628c2894369de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 二进制数据与Set互转 | |
*/ | |
@MappedJdbcTypes({JdbcType.VARBINARY}) | |
public abstract class AbstractSetBinaryConverter<T> implements TypeHandler<Set<T>> { | |
/** | |
* 暂用json序列化 | |
*/ | |
private static final ObjectMapper OM = new ObjectMapper(); | |
@Override | |
public void setParameter( | |
PreparedStatement preparedStatement, int i, Set<T> objs, JdbcType jdbcType | |
) throws SQLException { | |
try { | |
var baos = new ByteArrayOutputStream(); | |
var oos = new ObjectOutputStream(baos); | |
oos.write(OM.writeValueAsBytes(objs)); | |
oos.flush(); | |
preparedStatement.setBinaryStream(i, new ByteArrayInputStream(baos.toByteArray())); | |
} catch (IOException e) { | |
throw new SQLException(e.getCause()); | |
} | |
} | |
private Type getParameterizedType() { | |
var superClazz = getClass().getGenericSuperclass(); | |
return ((ParameterizedType) superClazz).getActualTypeArguments()[0]; | |
} | |
private Set<T> getObjectFromInputStream(InputStream is) throws IOException { | |
var emptySet = new HashSet<T>(); | |
if (0 == is.available()) { | |
return emptySet; | |
} | |
var buf = new byte[is.available()]; | |
var ois = new ObjectInputStream(is); | |
ois.read(buf); | |
var cType = OM.getTypeFactory().constructCollectionType( | |
HashSet.class, (Class)getParameterizedType() | |
); | |
return OM.readValue(buf, cType); | |
} | |
@Override | |
public Set<T> getResult(ResultSet rs, String c) throws SQLException { | |
var is = rs.getBinaryStream(c); | |
try { | |
return getObjectFromInputStream(is); | |
} catch (Exception e) { | |
throw new SQLException(e.getCause()); | |
} | |
} | |
@Override | |
public Set<T> getResult(ResultSet rs, int i) throws SQLException { | |
var is = rs.getBinaryStream(i); | |
try { | |
return getObjectFromInputStream(is); | |
} catch (Exception e) { | |
throw new SQLException(e.getCause()); | |
} | |
} | |
@Override | |
public Set<T> getResult(CallableStatement cs, int i) throws SQLException { | |
var buf = cs.getBytes(i); | |
try { | |
var cType = OM.getTypeFactory().constructCollectionType( | |
HashSet.class, (Class)getParameterizedType() | |
); | |
return OM.readValue(buf, cType); | |
} catch (IOException e) { | |
throw new SQLException(e.getCause()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment