2

My entity classes:

Order.java

public class Order {
    private int id;
    private Set<OrderLine> lines = new HashSet<OrderLine>();
   // Setters & Getters
}

OrderLine.java

public class OrderLine {
    private OrderLineId id;
    private String name;
    private Order order;
   // Setters & Getters
}

OrderLineId.java

public class OrderLineId implements Serializable{
    private int lineId;
    private int orderId;
    private int customerId;
   // Setters & Getters
}

My mapping file:

<hibernate-mapping>
   <class name="Order" table="TEST_Order">
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <set name="lines" cascade="all">
         <key column="orderId"/>
         <one-to-many class="OrderLine"/>
      </set>
   </class>

<class name="OrderLine" table="TEST_OrderLine">
    <composite-id name="id" class="OrderLineId">
        <key-property name="lineId"/>
        <key-property name="orderId"/>
        <key-property name="customerId"/>
    </composite-id>

    <property name="name"/>

    <many-to-one name="order" class="Order"
            insert="false" update="false">
        <column name="orderId"/>
    </many-to-one>
</class>
</hibernate-mapping>

I have created Separate DTO's for Order and OrderLine. Do I need to create a separate DTO for OrderLineId (which is a composite Identifier class as mentioned above) as well ?

  • Well I think you should create a Dto also for `OrderLineId` The entities returned by the `EntityManager` are attached to the `PersistenceContext`. I’m not sure but if you don’t make a Dto for `OrderLineId` It will refer to the id in the `OrderLine` Entity and if you set something new in that object you could fire an update – Pp88 Aug 23 '22 at 06:32
  • Did'nt understood. Could you please explain more on your front? – DrunkDragon Aug 23 '22 at 07:56
  • I mean if you make a `SomeEntity entity = entityManager.find(SomeEntity.class, id); entity.setField(someValue);` this will fire a select and then an update as explained [here](https://stackoverflow.com/questions/1607532/when-to-use-entitymanager-find-vs-entitymanager-getreference-with-jpa) so if you put in your Dto an instance of `OrderLineId` you will have the same reference in your `OrderLine` Entity and in your Dto. So if by mistake you set something in the `OrderLineId` you will change the reference that is also attached to the `PersistentContext`. You can make a test to see what happens – Pp88 Aug 23 '22 at 10:46

0 Answers0