zoukankan      html  css  js  c++  java
  • hibernate 持久化对象的 hashcode和equals

    hibernate 持久化对象经常需要重写hashcode和equals方法,什么情况下需要重写呢。

    1.需要将对象放到set集合中

    2.当需要比较对象不同的实例是否相等时

    重写的方式:

    1.eclipse自动生成

    2.根据需要自己写

    如果不写的话,hibernate会根据对象在内存中的地址来判断两个实例是否相等,最好是按照业务需求来写,如下,一个信息类,我设置了两个业务键,标题和发布时间,因为同一个时间发两个标题一样的几率很小小。。

    /**
     * 
     * @Override
     */
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((publishingtime == null) ? 0 : publishingtime.hashCode());
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Information other = (Information) obj;
        if (publishingtime == null) {
            if (other.publishingtime != null)
                return false;
        } else if (!publishingtime.equals(other.publishingtime))
            return false;
        if (title == null) {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        return true;
    }
  • 相关阅读:
    UVa 1331 最大面积最小的三角剖分
    UVa 1626 括号序列(矩阵连乘)
    POJ 3295 Tautology(构造法)
    POJ 2586 Y2K Accounting Bug(贪心)
    POJ 2109 Power of Cryptography
    abcd
    好数
    Gift
    密码游戏
    约瑟夫游戏
  • 原文地址:https://www.cnblogs.com/wangdinghao/p/3684958.html
Copyright © 2011-2022 走看看