日期:2014-05-20 浏览次数:21077 次
@Entity @IdClass(GirlPK.class) public class Girl{ private int id; private String name; private int age; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Id public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public class GirlPK implements Serializable { private static final long serialVersionUID = 1L; private int id; private String name; 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 boolean equal(Object obj){ if(this == obj){ return true; } if(obj != null && obj.getClass() == GirlPK.class){ GirlPK target = (GirlPK)obj; if(target.getId() == getId() && target.getName().equals(getName())){ return true; } } return false; } public int hashCode(){ return getId()*7+getName().hashCode(); }
public class Test { private static SessionFactory sessionFactory; private static ServiceRegistry serviceRegistry; public static void main(String[] args) { GirlPK gpk = new GirlPK(); Girl g = new Girl(); g.setAge(23); Configuration config = new Configuration().configure(); // 读取hibernate配置文件 serviceRegistry = new ServiceRegistryBuilder().applySettings( config.getProperties()).buildServiceRegistry(); sessionFactory = config.buildSessionFactory(serviceRegistry); // 创建SessionFactory Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(g); session.flush(); session.getTransaction().commit(); } }
drop table Girl create table Girl ( id int identity not null, name varchar(255) not null, age int not null, primary key (id, name) )