2015-09-03 67 views
0

上不相關的對象映射關聯我有2類:休眠 - 在XML

  • 用戶
  • 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文件。基礎表是不相關的。這意味着我知道RentedCar中的userIdUser中的userId相關聯,但它們之間沒有PK/FK關係。我需要在UserRentedCar之間添加RentedCarUserone-to-many之間的關聯。我應該如何在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> 

回答

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

+0

以上不工作的用戶id是不是在用戶表中的ID。因此它會引發外鍵錯誤。 – Viraj

+0

對不起,你把它稱爲「用戶」表中的user_id和「用戶」類中的userId @Viraj – Ghntek

+0

我的意思是userId不是hbm.xml映射文件中「id」的一部分。 – Viraj