我是 hibernate 和 JPA 的新手,我在注释方面遇到了一些问题。
我的目标是在数据库中创建这个表(带有个人详细信息的PERSON_TABLE)
ID ADDRESS NAME SURNAME MUNICIPALITY_ID
首先,我在 db 中有一个 MUNICIPALITY 表,其中包含我国家的所有自治市。我在这个实体中映射了这个表:
@Entity
public class Municipality implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String country;
private String province;
private String name;
@Column(name="cod_catasto")
private String codCatastale;
private String cap;
public Municipality() {
}
...
然后我制作了一个 EMBEDDABLE 类地址,其中包含实现简单地址的字段......
@Embeddable
public class Address implements Serializable {
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="id_municipality")
private Municipality municipality;
@Column(length=45)
private String address;
public Address() {
}
...
最后我将这个类嵌入到 Person ENTITY
@Entity
public class Person implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private String surname;
@Embedded
private Address address;
public Person() {
}
...
当我必须保存一个新的 Person 记录时,一切都很好,事实上,hibernate 根据我的需要创建了一个 PERSON_TABLE,但是如果我尝试检索一个 Person 记录,我会遇到一个异常。HQL 只是“来自 Person”的 excpetion 是(实体是包含上述所有类的包):
org.hibernate.AnnotationException: @OneToOne or @ManyToOne on Entities.Person.address.municipality references an unknown entity: Entities.Municipality
@OneToOne 注释是问题吗?
我的 hibernate.cfg.xml 是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:tcp://localhost/DB_PATH</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="Entities.Person"/>
<mapping class="Entities.Municipality"/>
<mapping class="Entities.Address"/>
</session-factory>
</hibernate-configuration>
谢谢。