亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java InetAddress 到 PostgreSQL inet,反之亦然

Java InetAddress 到 PostgreSQL inet,反之亦然

白豬掌柜的 2022-12-28 15:43:34
我想使用 PSQL inet 數據類型,但它不接受字符串 (getRemoteAddr()) 或 byte[] (InetAddress)。有沒有辦法使用 Java 正確轉換它?
查看完整描述

3 回答

?
紅顏莎娜

TA貢獻1842條經驗 獲得超13個贊

面臨同樣的問題。我能夠使用 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;

}


查看完整回答
反對 回復 2022-12-28
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

只需調用 InetAddress.getByName(String host) 并傳入您的文本 IP 地址。

來自 JavaDoc:主機名可以是機器名,例如“java.sun.com”,也可以是其 IP 地址的文本表示。

~ InetAddress javadoc

如果你問的是從 IP 獲取字符串:

String getHostAddress() 以文本形式返回 IP 地址字符串。

String getHostName() 獲取此 IP 地址的主機名。


查看完整回答
反對 回復 2022-12-28
?
九州編程

TA貢獻1785條經驗 獲得超4個贊

我認為這與How to get inet in entity class in spring using hibernate是同一個問題。


經過幾天的研究,我發現 2022 年不需要重新發明輪子。

有一個 lib vladmihalcea/hibernate-types implement Inet column typeInet Hibernate Type

資源

mvn 回購協議:https ://search.maven.org/search?q=g:com.vladmihalcea

教程:https ://vladmihalcea.com/postgresql-inet-type-hibernate/

GitHub:https ://github.com/vladmihalcea/hibernate-types

教程中的示例

@Entity(name = "Event")

@Table(name = "event")

@TypeDef(

    name = "ipv4",

    typeClass = PostgreSQLInetType.class,

    defaultForType = Inet.class

)


public class Event {

    @Id

    @GeneratedValue

    private Long id;

 

    @Column(

        name = "ip",

        columnDefinition = "inet"

    )

    private Inet ip;

 

    public Long getId() {

        return id;

    }

 

    public Inet getIp() {

        return ip;

    }

 

    public void setIp(String address) {

        this.ip = new Inet(address);

    }

}

spring-boot 2.7.1在,中按預期工作hibernate 5.6.9。


查看完整回答
反對 回復 2022-12-28
  • 3 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號