Best type for IP-address in Hibernate Entity?

╄→гoц情女王★ 提交于 2019-12-06 06:54:41

问题


What is the best type for storing IP-addresses in a database using Hibernate?

I though Byte[] or String, but is there a better way, or what do you use?

 @Column(name = "range_from",  nullable = false)
 public Byte[] getRangeFrom() {
  return rangeFrom;
 }
 public void setRangeFrom(Byte[] rangeFrom) {
  this.rangeFrom = rangeFrom;
 }

回答1:


I store it in a long, very fast for lookup. You can use the following functions for conversion.

public static string GetStandardIP(long numericIP)
{
    string w = Convert.ToString(Convert.ToInt64(numericIP / 16777216) % 256);
    string x = Convert.ToString(Convert.ToInt64(numericIP / 65536) % 256);
    string y = Convert.ToString(Convert.ToInt64(numericIP / 256) % 256);
    string z = Convert.ToString(Convert.ToInt64(numericIP) % 256);

    return w + "." + x + "." + y + "." + z;
}

And this one

public static long GetNumericIP(string standardIP)
{
    if (standardIP != null && standardIP != string.Empty)
    {
        string[] ipParts = standardIP.Split('.');
        long numericIP = 16777216 * Convert.ToInt64(ipParts[0]) + 65536 * Convert.ToInt64(ipParts[1]) + 256 * Convert.ToInt32(ipParts[2]) + Convert.ToInt32(ipParts[3]);

        return numericIP;
    }
    return 0;
}

You may want to improve them by doing checks on the parameters.




回答2:


It doesn't matter too much if you use Byte[] or String. Both will do the same job, it really just depends on your application and requirements.

I personally have always stored them as Strings.

I'm not aware of a better way to store them via Hibernate.

See https://forum.hibernate.org/viewtopic.php?f=1&t=996818&start=0

edit: Or you can use a long as in Pierre 303's example. In the end it really depends on your application and which type is the easiest to deal with for you.



来源:https://stackoverflow.com/questions/3342378/best-type-for-ip-address-in-hibernate-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!