Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate @OneToOne mapping with a @Where clause

Will this work -

@OneToOne()
@JoinColumn(name = "id", referencedColumnName = "type_id")
@Where(clause = "type_name = OBJECTIVE")
public NoteEntity getObjectiveNote() {
  return objectiveNote;
}

This is what I am trying to do - get the record from table note whose type_id is the id of the current object and type_name is OBJECTIVE.

I can't get the above mapping to work. What am I doing wrong here?

like image 469
nuaavee Avatar asked Dec 08 '10 00:12

nuaavee


People also ask

How to map one to one relationship in JPA?

The best way to map a @OneToOne relationship is to use @MapsId . This way, you don't even need a bidirectional association since you can always fetch the PostDetails entity by using the Post entity identifier. This way, the id property serves as both Primary Key and Foreign Key.

Is @entity annotation mandatory in hibernate?

The entity class must be annotated with the Entity annotation or denoted in the XML descriptor as an entity. So, if you use annotations for mappings, @Entity is mandated by the specification and Hibernate has to adhere to it.

What is difference between JPA unidirectional OneToOne and ManyToOne?

The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object's table to the target object's table, whereas a OneToOne relationship the foreign key may either be in the source object's table or the target object's table.


1 Answers

This just plain does not work, sorry :( You will need to do it as one to many and live with getting a collection with a single element.

If you really want it to work this way, you can trick hibernate by storing both the foreign key ID and the type_name in a join table and telling it that both columns make up the foreign key.

like image 159
Affe Avatar answered Sep 28 '22 08:09

Affe