简体   繁体   English

使用外键关联进行一对一映射休眠

[英]one-to-one mapping hibernate using foreign key association

am new to Hibernate learning entity mapping using hibernate framework via instead of annotation am using XML for mapping the entities 是使用hibernate框架而不是通过注释使用Hibernate学习实体映射的新方法,是使用XML映射实体的方法

Here I have two classes Employee and Address [Address is the target class and Employee is the source class ie is Employee table will have the foreign key column refers to Address table primary key] 在这里,我有两个类Employee和Address [地址是目标类,而Employee是源类,即Employee表将具有指向地址表主键的外键列]

class Employee{
String name;
int id;
Address addr;
//getter and setter methods
}

class Address{
String state;
String city
}

mapping.hbm.xml file:- mapping.hbm.xml文件:-

<hibernate-mapping>
<class name="Employee" table="emp">
<id name="id" column="id">
<generator class="assigned"/>
</id>
<property name="name" column="emp_name"/>
<one-to-one name="addr" class="Address" foreign-key="addr_id" cascade="all"/>
</class>

<!--mapping for Address Entity-->
<class name="Address" table="address>
<property name="city"/>
<property name"state"/>
</class>
</hibernate-mapping>

Note:- am using MySQL in table level I did not add a foreign key constraint to the employee table 注意:-在表级别使用MySQL时,我没有向employee表添加外键约束

And My Question while am try to save employee entity addr_id value is not stored in employee table how to resolve this issue.IN web most of the things are using annotations or shared a primary key.How to solve this issue kindly help me 而我的问题是在尝试保存员工实体的addr_id值时未将其存储在employee表中。如何解决此问题。在Web中,大多数事情都使用注释或共享主键。如何解决此问题请帮帮我

Change your mapping. 更改您的映射。 You need to fully qualify class name and indicate join column, which is PK of Employee, column id . 您需要完全限定类名并指示join列,这是Employee的PK,列id

Employee 雇员

<class name="Employee" table="emp">
<id name="id" column="id">
<generator class="assigned"/>

Address entity have to refer to the PK of Employee, which is id in your case : 地址实体必须引用Employee的PK,在您的情况下为id

 <one-to-one name="addr" class="my.package.Employee"
                   unique="true" not-null="true" cascade="all"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM