天天看点

重写equals和hashCode方法重写equals和hashCode方法

重写equals和hashCode方法

重写equals方法

public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof User))
            return false;
        final User u = (User) other;
        if(!name.equals(u.getName()))
            return false;
        if(!birthday.equals(u.getBirthday()))
            return false;
        if(!name.equals(u.getName()))
            return false;
        if(!name.equals(u.getName()))
            return false;
        return true;
    }
           

重写hashcode方法

public int hashCode() {
    return Objects.hash(id, name, gender, age, birthday);
}
           

测试方法

@Test
    public void testOverrideMethod() {
        SessionFactory sf = null;
        Session session = null;
        Transaction ts = null;
        User u = new User();
        try {
            sf = HibernateUtil.getSessionFactory();
            session = sf.getCurrentSession();
            ts = session.beginTransaction();
            User user1 = session.get(User.class,1);
            session.evict(user1);
            User user2 = session.get(User.class,1);
            ts.commit();

            System.out.println(user1 == user2);
            System.out.println(user1.equals(user2));

        } catch (HibernateException e) {
            e.printStackTrace();
            if (ts != null) {
                ts.rollback();
            }
        } finally {
            session.close();
            HibernateUtil.closeSessionFactory(sf);
        }
    }
           

测试结果:

重写equals和hashCode方法重写equals和hashCode方法

继续阅读