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;
    }
  • 相关阅读:
    页面渲染速度增加的方法和建议
    五(六)、Package & import
    五(五)、构造器 & JavaBean &this
    五(四)、封装性
    五(三)、方法
    五(二)、匿名对象
    五(一)、类&对象概述
    六、java 异常处理
    四、java 数组
    三、java 基础提炼
  • 原文地址:https://www.cnblogs.com/wangdinghao/p/3684958.html
Copyright © 2011-2022 走看看