persistence@glassfish.java.net

Re: using composition with JPA

From: Sahoo <Sahoo_at_Sun.COM>
Date: Tue, 24 Jul 2007 20:28:15 +0530

Introducing a third class of embeddable type should help as shown below:

@Embeddable
public class VehicleData {
   private String model;
   private String color;
   // any other data that need to be part of both Vehicle as well as Permit
}

@Entity
public class Vehicle {
   @Id
   private int VIN;
   @Embedded
   private VehicleData vehicleData;
}

@Entity
public class Permit {
  @Id
   private int number;
   private Date issueDate;
   @Embedded
   private VehicleData vehicleData;
   @ManyToOne
   private Vehicle vehicle;
   ...
}


-- Sahoo
sud wrote:
> I'm still unclear about the solutions proposed. Here's a more detailed
> real-life explanation of what I'm trying to achieve and I'd any
> appreciate help figuring this out.
>
>
> I have a JPA entity class called Vehicle as below
>
> @Entity
> public class Vehicle {
> @Id
> private int VIN;
>
> private String model;
>
> private String color;
> .....
> .....
> }
>
> I have a second JPA entity class called Permit which represents
> vehicle permits issued by the agency
>
> @Entity
> public class Permit {
> @Id
> private int number;
>
> private Date issuedDate;
>
> private Vehicle vehicle;
> ....
> ....
> }
>
> My business rule is a Vehicle can have many permits issued to it and a
> Permit can be issued to one and only one Vehicle. You should always be
> able to retrieve a specific permit and say what was the vehicle it was
> issued to. So if a permit was issued to a vehicle with color Red, and
> if the same vehicle has since been updated to color Blue, the permit
> that was issued should still say vehicle color Red. This is what I
> meant by the Permit is composed of Vehicle and that the instance
> variable vehicle in Permit is a snapshot of a vehicle when that permit
> is created.
>
> All this leads mean to believe that I need to be able to store the
> values of the Vehicle object in the Permit table and not create a
> reference from the Permit table to the Vehicle table. That way if the
> vehicle was updated, the permit still has the original properties of
> vehicle it was issued to.
>
> I hope I explained myself better now. Please let me know how to go
> about this in JPA.
> -sud
>
> My issue is with the vehicle object in the Permit class. If
>
> ------------------------------------------------------------------------
> Take the Internet to Go: Yahoo!Go puts the Internet in your pocket:
> <http://us.rd.yahoo.com/evt=48253/*http://mobile.yahoo.com/go?refer=1GNXIC>
> mail, news, photos & more.