红颜莎娜
面临同样的问题。我能够使用 InetAddress 读取 Inet Postgres 类型,但在将相同的 InetAddress 类型插入具有 inet 类型的 postgres 时遇到错误。通过定义自定义休眠类型解决了它PgInet-> public class PgInet implements Serializable { private InetAddress address; public PgInet() {} public PgInet(InetAddress address) { this.address = address; } public InetAddress getAddress() { return address; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof PgInet)) { return false; } PgInet other = (PgInet) obj; if (address == null) { if (other.address != null) { return false; } } else if (!address.equals(other.address)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PgInet [address="); builder.append(address); builder.append("]"); return builder.toString(); }}PGInetType -> public class PgInetType implements UserType { public PgInetType() {} @Override public Object assemble(Serializable cached, Object owner) { return deepCopy(cached); } @Override public Object deepCopy(Object value) { if (value != null) { return new PgInet(((PgInet) value).getAddress()); } return null; } @Override public Serializable disassemble(Object value) { return (value != null) ? (Serializable) deepCopy(value) : null; } @Override public boolean equals(Object x, Object y) { return x == y || ( x != null && y != null && x.equals( y ) ); } @Override public int hashCode(Object x) { return (x != null) ? x.hashCode() : 0; } @Override public boolean isMutable() { return false; } @Override public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException { PgInet address = null; String ipStr = rs.getString(names[0]); if (ipStr != null) { try { address = new PgInet(InetAddress.getByName(ipStr)); } catch (UnknownHostException e) { throw new HibernateException(e); } } return address; } @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws SQLException { if (value == null) { st.setNull(index, Types.VARCHAR); } else { PGobject pgObj = new PGobject(); pgObj.setType("inet"); pgObj.setValue(((PgInet) value).getAddress().getHostAddress()); st.setObject(index, pgObj); } } @Override public Object replace(Object original, Object target, Object owner) { return deepCopy(original); } @SuppressWarnings("rawtypes") @Override public Class returnedClass() { return PgInet.class; } @Override public int[] sqlTypes() { return new int[] {Types.OTHER}; }}用法->@TypeDefs({ @TypeDef(name="pgInet", typeClass=PgInetType.class)})public class Test{ @Column(name = "ip") @Type(type="pgInet") private PgInet ip;}