I am new to Play framework and yml notation, and know just the basics for Hibernate. I am trying to set up some test data by using a .yml file. I try to define several Question objects and an ActiveCompetition object that refer to the same Competition object. My .yml file looks like this (I have removed what I think is not relevant):
ActiveCompetition(1): &myactivecompetition
activeCompetition: &mycompetition
name: Name of the competition
Question(11):
title: Title 1
competition: *mycompetition
Question(12):
title: Title 2
competition: *mycompetition
Question(13):
title: Title 3
competition: *mycompetition
I works, but it seems that Hibernate saves *mycompetition 4 times.
In the java beans the attributes for javax.persistence are set as follows:
@Entity
@Transactional
public class ActiveCompetition extends Model {
@Required
@OneToOne(cascade= CascadeType.ALL)
private Competition activeCompetition;
}
@Entity
@Transactional
public class Question extends Model {
...
@Required
@OneToOne(cascade= CascadeType.ALL)
private Competition competition;
}
How do I make Hibernate understand that *mycompetition should be stored only once in the database? Should I write the database id on the .yml file? If so, how do I do this? I have tried already to add for example ‘id: 99’ under activeCompetition but it doesn’t help.
There are two possible issues:
First one is that you are declaring the relatiosn OneToOne, but then in your YAML file you create a ManyToOne relation. OneToOne means that each ActiveCompetition has, at most, one question, and each Question relates to, at most, one ActiveCompetition.
What you you want is a ManyToOne relation where an ActiveCompetition has many Question. You should update your Java code.
Second one is that you are defining your ActiveCompetition as:
In YAML, AFAIK, you reference other entities in the file by the reference provided with the entity (or that’s how I did it). In the declaration above the reference is the number
1between ().So you should change your file to: