我有三张桌子: 用户>简介 - > ProfileDetails
用户在个人资料表中有一行
Profile在ProfileDetails表中有一行
CREATE TABLE IF NOT EXISTS mydb.User (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(45) NULL,
PRIMARY KEY (id))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS mydb.Profile (
userId INT NOT NULL,
profileData VARCHAR(45) NULL)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS mydb.ProfileDetails (
profileId INT NOT NULL,
details VARCHAR(45) NULL)
ENGINE = InnoDB;
如何使用一对一关系在hbm.xml文件中描述所有这些关系?
答案 0 :(得分:0)
我解决了这个问题。 我使用主键关系:
CREATE TABLE IF NOT EXISTS mydb.User (
id INT NOT NULL,
name VARCHAR(45) NULL,
PRIMARY KEY (id))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS mydb.Profile (
user_id INT NOT NULL,
profile_data VARCHAR(45) NULL,
PRIMARY KEY (user_id),
CONSTRAINT fk_Profile_User1
FOREIGN KEY (user_id)
REFERENCES mydb.User (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS mydb.ProfileDetails (
profile_id INT NOT NULL,
details INT NOT NULL,
PRIMARY KEY (profile_id, details),
INDEX fk_ProfileDetails_Profile1_idx (profile_id ASC),
CONSTRAINT fk_ProfileDetails_Profile1
FOREIGN KEY (profile_id)
REFERENCES mydb.Profile (user_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
和下一个hbm.xml映射:
<强> User.hbm.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ru.myapp.User" table="User">
<id name="id" column="id" type="long">
<generator class="native" />
</id>
<property name="name" column="name" type="string" />
<one-to-one name="profile" class="ru.myapp.Profile" />
</class>
</hibernate-mapping>
<强> Profile.hbm.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ru.myapp.Profile" table="Profile">
<id name="id" column="user_id" type="long">
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>
<property name="profileData" column="profile_data" type="string" />
<one-to-one name="user" class="ru.myapp.User" />
<one-to-one name="profileDetails" class="ru.myapp.profileDetails" />
</class>
</hibernate-mapping>
<强> ProfileDetails.hbm.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="ru.myapp.ProfileDetails" table="ProfileDetails">
<id name="id" column="profile_id" type="long">
<generator class="foreign">
<param name="property">profile</param>
</generator>
</id>
<property name="details" column="details" type="string" />
<one-to-one name="profile" class="ru.myapp.Profile" />
</class>
</hibernate-mapping>