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;
    }
  • 相关阅读:
    解决Cannot change version of project facet Dynamic web module to 3.0
    mysql 存储过程
    查看建表语句
    mysql query cache 查询缓存
    数据库连接池
    JDBC Statement PrepareStatement
    mysql 改变表结构 alter
    maven 获取pom.xml的依赖---即仓库搜索服务
    windows常用快捷键
    oracle 的数据完整性
  • 原文地址:https://www.cnblogs.com/wangdinghao/p/3684958.html
Copyright © 2011-2022 走看看