- Java code
@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; } }
- Java code
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(); }
- Java code
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(); }}
如代码所示
GirlPK为复合主键
Girl为实体类
用hibernate自动生成表显示的SQL为
- SQL code
drop table Girl create table Girl ( id int identity not null, name varchar(255) not null, age int not null, primary key (id, name) )
但是之后执行test的时候报错为
ERROR: HHH000123: IllegalArgumentException in class: test.GirlPK, setter method of property: id
二月 10, 2012 9:21:32 下午 org.hibernate.property.BasicPropertyAccessor$BasicSetter set
ERROR: HHH000091: Expected type: int, actual value: org.hibernate.id.IdentifierGeneratorHelper$2
Exception in thread "main" org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of test.GirlPK.id
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:119)
at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:436)
at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)