JPA / Hibernate for storing months and days in months

I have the 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 in the following database structure using JPA + Hibernate:

Table MONTH:

id; description;

DAYS table:

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

What is the best solution for this situation?

0


source to share


3 answers


If you can't change your pojo or table structure, you're screwed up a bit. 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;

}

      



---- Requires surrogate key DB change for the days table

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

      

+1


source


Here is one of the solutions 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 is that Day.nr gets saved twice: first as an IndexColumn from the list (0 based counter) and second time as a field of the Day class (1 based counter).

0


source


Is it possible to map the @Entity UNIDIRECTIONAL month relation to the Day @Entity class without @Embeddable to CascadeType.PERSIST where the @Entity Day class id consists of the month id and the list index as shown below?

@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>();

      

}

@ Normal class of class Day {

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

      

}

I hope you can solve this problem.

Relationship Arthur Ronald F. D. Garcia (Java Programmer) Natal / Rn - Brazil

0


source







All Articles