是否可以使用 Hibernate XML 映射配置避免主键设置器?使用注释时,您不必声明 setter 方法。见例子。我正在使用休眠版本 4.1.2。
基于 XML 的配置
public class Entity { private Integer id; public Integer getId() { return id; } } <class name="Language" table="language"> <id name="id" column="id"> <generator class="native" /> </id> </class>
初始化 Hibernate 时抛出异常
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property id in class net.kreuzman.eshop.core.domain.l10n.Language at org.hibernate.property.BasicPropertyAccessor.createSetter(BasicPropertyAccessor.java:252) at org.hibernate.property.BasicPropertyAccessor.getSetter(BasicPropertyAccessor.java:245) at org.hibernate.mapping.Property.getSetter(Property.java:325) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertySetter(PojoEntityTuplizer.java:444) at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:182) at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82) ... 49 more
基于注释的配置
@Entity @Table(name="entity") public class Entity { @Id @Column(name="id") @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; public Integer getId() { return id; } }
这很好用。