views:

899

answers:

3

I have following POJOs:

class Month {
    long id;
    String description;
    List<Day> days; // always contains 29, 30 or 31 elements
}

class Day {
    byte nr; // possible values are 1-31
    String info;
}

Is there a way to store these objects into following DB structure using JPA+Hibernate:

Table MONTHS:

id;description;

Table DAYS:

id-of-month;nr-of-day;info;

Any better solution for this situation?

A: 

Here is one solution I found:

class Month {
    long id;
    String description;

    @CollectionOfElements(fetch = FetchType.EAGER)
    @IndexColumn(name = "nr-of-day")
    List<Day> days; // always contains 29, 30 or 31 elements
}

@Embeddable
class Day {
    byte nr; // possible values are 1-31
    String info;
}

@CollectionOfelements and @IndexColumn are Hibernate annotations. If I use @OneToMany annotation available in JPA, hibernate creates 3 tables instead of 2.

My only problem now is that Day.nr is saved twice: first as IndexColumn of the List (0-based counter) and second time as field of class Day (1-based counter).

Vilmantas Baranauskas
+1  A: 

If you can't change your pojo's or table structure you are a bit screwed. If you can then a simple annotated pojo will work.

class Month {
   @Id
   private long id;
   private String description;
   @OneToMany(mappedBy="month",fetchType=Lazy)
   private List<Day> days;

}

---- Surrogate key required DB change for Days table

class Day {
    @Id
    private int id;
    private Month month;
    private byte nr; // possible values are 1-31
    private String info;
}
mxc
A: 

Can you map a Month @Entity class UNIDIRECTIONAL relationship with Day @Entity class without @Embeddable with CascadeType.PERSIST instead, where the identifier of @Entity Day class is composed by Month identifier and the list index as follow ?

@Entity public class Month {

@Id
@GeneratedValue
private Integer id;


// one way relationship
@OneToMany(cascade=CascadeType.PERSIST)
@JoinColumn(name="MONTH_ID")
@IndexColumn(name="childIndex")
private List<Day> dayList = new ArrayList<Day>();

}

@Entity public class Day {

@EmbeddedId // composed by month foreign key and index column
private DayId id;

}

I hope you solve this problem

Regards Arthur Ronald F D Garcia (Java programmer) Natal/Rn - Brazil