Hello everybody,
I'm learning Hibernate for the moment, and I've envountered a question which i cannot answer.
For a personal project, i'm developping an Animal Store, It has simple mapping, but one thing is not clear to me.
There are three object classes:
The store itself, which has animals:
Code:
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "ANIMALSTORE_ID)
private long id;
@Column(name = "ANIMALSTORE_NAME")
private String name;
@OneToOne
@JoinColumn(name="PERSON_ANIMALSTORE_ID")
private Person owner;
@OneToMany(cascade = { CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.REMOVE }, mappedBy = "store")
private Collection<Animalr> animals;
There is also an animal owner, called Person, which can have a store, and animals:
Code:
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "PERSON_ID")
private long id;
@Column(name = "PERSON_NAME")
private String name;
@OneToMany(cascade = { CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.REMOVE }, mappedBy = "owner")
private Collection<ANIMAL> dieren;
@Column(name = "PERSON_BUDGET")
private int budget;
@OneToOne(mappedBy = "owner")
private DierenWinkel winkel;
Offcourse there is finally, also an Animal class
Code:
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "ANIMAL_ID")
private long id;
@Column(name = "ANIMAL_NAME")
private String name;
@Column(name = "ANIMAL_SPECIE")
private String specie;
@ManyToOne( targetEntity = Person.class )
@JoinColumn(name = "PERSON_ID", nullable=true)
private Person owner;
@ManyToOne( targetEntity = DierenWinkel.class )
@JoinColumn(name = "ANIMALSTORE_ID", nullable=true)
private AnimalStore winkel;
@Column(name = "ANIMAL_PRICE")
private int price;
The problem is that a Animal, can have a Person as an owner, or it can still be proprety of a Store, but it is not necessary, that it has both, an owner or a Store is sufficient.
This is the error message i get:
Code:
INFO: schema export complete
Hibernate:
insert
into
PERSOON
(PERSOON_NAAM, PERSOON_BUDGET)
values
(?, ?)
Hibernate:
insert
into
HUISDIER
(HUISDIER_NAAM, HUISDIER_SOORT, PERSOON_ID, DIERENWINKEL_ID, HUISDIER_PRIJS)
values
(?, ?, ?, ?, ?)
12-dec-2008 19:10:48 org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: 1048, SQLState: 23000
12-dec-2008 19:10:48 org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: Column 'DIERENWINKEL_ID' cannot be null
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] An exception occured while executing the Java class. null
Column 'DIERENWINKEL_ID' cannot be null
[INFO] ------------------------------------------------------------------------
But with this mapping, Hibernate demands logically that it has both.
Is there a way to work around this, i was thinking at a "ZeroToMany" annotation, in some sort.
Thank you very much, if you could help me!