Hibernate 使用复合主键

在数据库ssh下建立一个表dog

create table dog(
id int(11) not null,
dog_id int(11) not null,
name varchar(20) default null,
primary key(id,dog_id)
)engine=innodb default charset=gbk;

建立一个主键类DogId.java

package helloworld.compositeid;

public class DogId implements java.io.Serializable {

	// Fields

	private Integer id;
	private Integer dogId;

	// Constructors

	/** default constructor */
	public DogId() {
	}

	/** full constructor */
	public DogId(Integer id, Integer dogId) {
		this.id = id;
		this.dogId = dogId;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getDogId() {
		return this.dogId;
	}

	public void setDogId(Integer dogId) {
		this.dogId = dogId;
	}

	public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof DogId))
			return false;
		DogId castOther = (DogId) other;

		return ((this.getId() == castOther.getId()) || (this.getId() != null
				&& castOther.getId() != null && this.getId().equals(
				castOther.getId())))
				&& ((this.getDogId() == castOther.getDogId()) || (this
						.getDogId() != null
						&& castOther.getDogId() != null && this.getDogId()
						.equals(castOther.getDogId())));
	}

	public int hashCode() {
		int result = 17;

		result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
		result = 37 * result
				+ (getDogId() == null ? 0 : this.getDogId().hashCode());
		return result;
	}

}

建立一个类Dog.java

package helloworld.compositeid;

public class Dog implements java.io.Serializable {
	private DogId id;
	private String name;
	private String color;

	public Dog() {
	}

	public Dog(DogId id) {
		this.id = id;
	}

	public Dog(DogId id, String name, String color) {
		this.id = id;
		this.name = name;
		this.color = color;
	}


	public DogId getId() {
		return this.id;
	}

	public void setId(DogId id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getColor() {
		return this.color;
	}

	public void setColor(String color) {
		this.color = color;
	}

}

建立映射文件Dog.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="helloworld.compositeid.Dog" table="dog" catalog="ssh">
		<!--定义复合主键-->
		<composite-id name="id" class="helloworld.compositeid.DogId">
			<key-property name="id" type="java.lang.Integer">
				<column name="id" />
			</key-property>
			<key-property name="dogId" type="java.lang.Integer">
				<column name="dog_id" />
			</key-property>
		</composite-id>
		<property name="name" type="java.lang.String">
			<column name="name" length="20" />
		</property>
		<property name="color" type="java.lang.String">
			<column name="color" length="10" />
		</property>
	</class>
</hibernate-mapping>

编写一个测试类,实现基本CRUD操作,Test.java

package helloworld.compositeid;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Configuration管理Hibernate配置
		Configuration config = new Configuration().configure();
		// 根据Configuration建立 SessionFactory
		// SessionFactory用来建立Session
		SessionFactory sessionFactory = config.buildSessionFactory();

		// 增加记录
		// 建立主键类实例
		DogId dogid = new DogId();
		dogid.setId(1);
		dogid.setDogId(1);
		// 建立Dog对象
		Dog dog = new Dog();
		dog.setName("Tom");
		dog.setColor("yellow");
		dog.setId(dogid);

		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(dog);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		// 查找数据
		session = sessionFactory.openSession();
		dog = (Dog) session.get(Dog.class, dogid);
		System.out.println(dog.getId().getId() + " " + dog.getId().getDogId()
				+ " " + dog.getName());
		session.close();

		// 修改数据
		dog.setName("Kitty");
		session = sessionFactory.openSession();
		tx = null;
		try {
			tx = session.beginTransaction();
			session.update(dog);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		// 删除数据
		session = sessionFactory.openSession();
		tx = null;
		try {
			tx = session.beginTransaction();
			session.delete(dog);
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}

		// 关闭sessionFactory
		sessionFactory.close();

	}

}


源程序解读:

1.本实例使用了单独的主键类DogId。

2.主键类DogId重写了equals方法和hashCode方法,这一点非常重要。

3.Hibernate要求主键类必须实现Serializable接口。

4.复合主键的值是一个主键类,而不是一个普通的常见数值。

5.复合主键的映射文件使用composite-id表示。



 

你可能感兴趣的:(Hibernate 使用复合主键)