Best type for IP-address in Hibernate Entity?
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)
开发者_JAVA技巧 public Byte[] getRangeFrom() {
return rangeFrom;
}
public void setRangeFrom(Byte[] rangeFrom) {
this.rangeFrom = rangeFrom;
}
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.
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.
精彩评论