Hibernate同一性问题

package com.cg.foo;



// Generated 2012-7-19 11:40:57 by Hibernate Tools 3.4.0.CR1



import java.util.Date;

import java.util.HashSet;

import java.util.Set;



/**

 * TUser generated by hbm2java

 */

public class TUser implements java.io.Serializable {



	private long id;

	private String name;

	private String nickname;

	private Date birthday;

	private Set<TCard> TCards = new HashSet<TCard>(0);



	public TUser() {

	}



	public TUser(long id) {

		this.id = id;

	}



	public TUser(long id, String name, String nickname, Date birthday,

			Set<TCard> TCards) {

		this.id = id;

		this.name = name;

		this.nickname = nickname;

		this.birthday = birthday;

		this.TCards = TCards;

	}



	public long getId() {

		return this.id;

	}



	public void setId(long id) {

		this.id = id;

	}



	public String getName() {

		return this.name;

	}



	public void setName(String name) {

		this.name = name;

	}



	public String getNickname() {

		return this.nickname;

	}



	public void setNickname(String nickname) {

		this.nickname = nickname;

	}



	public Date getBirthday() {

		return this.birthday;

	}



	public void setBirthday(Date birthday) {

		this.birthday = birthday;

	}



	public Set<TCard> getTCards() {

		return this.TCards;

	}



	public void setTCards(Set<TCard> TCards) {

		this.TCards = TCards;

	}

	

	@Override

	public boolean equals(Object other) {

		if(this==other)return true;

		//if(id==null)return false;

		if(!(other instanceof TUser))return false;

		final TUser that = (TUser)other;

		return this.id == that.id;

	}



	@Override

	public int hashCode() {

//		return id==null? System.identityHashCode(this):this.id.hashCode();

		return (int)id;

	}

}









package com.cg.test;



import java.util.HashSet;

import java.util.Set;



import org.hibernate.Session;

import org.hibernate.tutorial.util.HibernateUtil;

import org.junit.Test;



import com.cg.foo.TUser;



public class TestObjIdentityEqual {



	@Test

	public void test() {

		Session session = HibernateUtil.getSessionFactory().openSession();

		session.beginTransaction();

		TUser a =(TUser) session.get(TUser.class	, 7L);

		TUser b =(TUser) session.get(TUser.class	, 7L);

		System.out.println("测试1个session的get对象同一性:");

		System.out.println(a == b);	//true

		

		session.getTransaction().commit();

		session.close();

		

		Session session2 = HibernateUtil.getSessionFactory().openSession();

		session2.beginTransaction();

		TUser c = (TUser) session2.get(TUser.class, 7L);

		

		System.out.println("测试两个session的get对象同一性:");

		System.out.println(a == c);		//false: detached & persisted

		

		session2.getTransaction().commit();

		session2.close();

		

		Set<TUser>	setAll =new HashSet();

		setAll.add(a);

		setAll.add(b);

		setAll.add(c);

		System.out.println(setAll.size());	//size:2

		

	}



}

  

你可能感兴趣的:(Hibernate)