Hibernate中联合主键映射学习

首先说下一个类中单个主键在hibernate中的映射配置

直接上代码:


	
		
			
		
		
		
	
对应的实体类:

package ray.po;

public class User {
	private int id;
	private String name, age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	public User(int id, String name, String age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public User() {
		super();
	}
	
}
测试代码:

package ray.po;

import org.hibernate.Session;

import ray.SessionUtil.HibernateSessionFactory;

public class UserTest {
	public static void main(String[] args) {
		User user = new User();
		user.setName("雷盼");
		user.setAge("26");
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}
}
Hibernate: 
    create table _user (
        id integer not null auto_increment,
        name varchar(255),
        age varchar(255),
        primary key (id)
    )
但是有时候我们再设计数据库表的时候,会用多个字段作为联合主键,那么在hibernate中怎么配置这中情况呢?

配置文件:


	
		
			
			
		
		
	
实体类代码:

package ray.compositeId;

public class Student {
	// 联合主键id
	private CompositeId id;
	private byte age;

	public CompositeId getId() {
		return id;
	}

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

	public byte getAge() {
		return age;
	}

	public void setAge(byte age) {
		this.age = age;
	}

}
联合主键的类:

package ray.compositeId;

import java.io.Serializable;

public class CompositeId implements Serializable {
	private String firstName, lastName;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}
测试代码:

package ray.compositeId;

import org.hibernate.Session;

import ray.SessionUtil.HibernateSessionFactory;
//测试联合主键
public class Test {
	public static void main(String[] args) {
		Student s = new Student();
		CompositeId sid = new CompositeId();
		sid.setFirstName("子诺");
		sid.setLastName("雷");
		s.setAge((byte) 12);
		s.setId(sid);
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		session.save(s);
		session.getTransaction().commit();
		session.close();
	}
}
Hibernate: 
    create table _Student (
        _firstName varchar(255) not null,
        lastName varchar(255) not null,
        age tinyint,
        primary key (_firstName, lastName)
    )








你可能感兴趣的:(Hibernate中联合主键映射学习)