我有2个班级:
RentedCar
public class User implements Serializable{
private String userName;
private Integer userId;
private String userParent;
}
public class RentedCar implements Serializable{
private Date stopDate;
private Date startDate;
private String carName;
private Integer carId;
private Integer userId; // Some userId from User.
}
这些类有各自的hbm.xml
个文件。基础表是不相关的。这意味着我知道userId
中的RentedCar
与userId
中的User
相关联,但它们之间没有PK / FK关系。我需要在many-to-one
和RentedCar
之间添加User
关联,并在one-to-many
和User
之间添加RentedCar
关联。我应该如何在hbm.xml文件中执行此操作?
这些是xml映射:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="user">
<composite-id>
<key-property name="userName" column="user_name" type="string"/>
<key-property name="userParent" column="user_parent" type="string"/>
</composite-id>
<property name="userId" column="user_id" type="int"></property>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="RentedCar" table="rented_car">
<composite-id>
<key-property name="stopDate" column="stop_date" type="date" />
<key-property name="carId" column="car_id" type="int" />
<key-property name="userId" column="user_id" type="int" />
</composite-id>
<property name="startDate" column="start_date" type="date"></property>
<property name="carName" column="car_name" type="float"></property>
</class>
</hibernate-mapping>
答案 0 :(得分:1)
我认为你的课程中应该有一些东西表明在hbm.xml文件中有一对多的关系:
public class User implements Serializable{
private String userName;
private Integer userId;
private String userParent;
private Set<RentedCar> rentedCars;
}
public class RentedCar implements Serializable{
private Date stopDate;
private Date startDate;
private String carName;
private Integer carId;
private User user;
}
然后在RentedCar.hbm.xml中你可以使用:
<many-to-one name="user" class="User">
<column name="userId" not-null="true"></column>
</many-to-one>
在User.hbm.xml中:
<set name="rentedCars" table="rented_car" fetch="select">
<key>
<column name="userId" not-null="true"></column>
</key>
<one-to-many class=" RentedCar "/>
</set>
本教程可以帮助您http://www.tutorialspoint.com/hibernate/hibernate_one_to_many_mapping.htm