I spent many long hours trolling google, trying to find the correct syntax for a few of complicated annotations. I wanted to post what I did as an example for anyone else struggling. Just a note that had I followed Occam's Razor, I would have saved myself a lot of trouble.
Map of java object to embedded object:
Say I have an embedded object FruitValues that contains information about fruit types and information about said fruit grown and I want to get a map of name -> Embedded type. More specifically, I want to return a Map<String, FruitValues>.
So if I have two tables, one called all_orchards and one called fruit_types, each with a column orchard_name (where in fruit_types orchard name represents an orchard that fruit is grown in. Subsequently, the key must be the tuple <fruit_type, orchard_name>), I can generate a map for a given orchard of fruit_type->{information about the fruit}:
@Embeddable
public class FruitValues implements Serializable
{
private String mColor;
private String mFlavor;
...
}
@Entity
@Table(name="all_orchards")
public class Orchard implements Serializable
{
...
@CollectionOfElements
@JoinTable(name="fruit_types", joinColumns=@JoinColumn(name="orchard_name"))
@MapKey(columns=@Column(name="fruit_type"))
public Map<String, FruitType> getFruitTypes()
{
....
}
....
}
Joined Subclasses (This shouldn't be as hard as it was...):
Now, say that Orchard is a Joined subclass of an abstract class farm, joined on farm_id. Farm has some information in a table called farm.
@Entity
@Table(name="farm")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Farm implements Serializable
{
...
}
@Entity
@Table(name="all_orchards")
@PrimaryKeyJoinColumn(name="farm_id")
public class Orchard implements Serializable
{
...
}
Mapping an Embedded Type to an Embedded Type:
Lastly, say for a given fruit in a given season, I want to know how to grow it. Thus, I create my embedded classes FruitSeason and GrowingInstructions (not shown) but they would exist in tables fruit_and_season, and growing_instructions.
@Entity
@Table(name="all_orchards")
@PrimaryKeyJoinColumn(name="farm_id")
public class Orchard implements Serializable
{
...
@CollectionOfElements
@JoinTable(name="growing_instructions", joinColumns={@JoinColumn(name="fruit_id")})
@MapKey(columns={@Column(name="fruit_type"), @Column(name="season"), targetElement=FruitSeason.class}
public Map<FruitSeason, GrowingInstructions> getFruitSeasonToGrowingInstructionsMap()
{
...
}
...
}
|