Hibernate's bidirectional OneToOne relationship not working within the same class

528 views Asked by At

I'm trying to create "a chain of commands" using One to One hibernate relationship withing the same class:

@Entity
public class Command {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true)
private Long id;

@ElementCollection
@LazyCollection(LazyCollectionOption.FALSE)
private List<String> commandWithArguments = new ArrayList<String>();

private ExecutionStatus status = ExecutionStatus.NOT_EXECUTED;


@OneToOne(mappedBy = "parentCommand", cascade = CascadeType.ALL)
private Command child;

@OneToOne(mappedBy = "child", cascade = CascadeType.ALL)
private Command parentCommand;

@OneToOne(mappedBy = "command")
private ExecutionResult result;

public Command() {
}
....

Does hibernate support relationships like this? It throws the following exception during initialization:

 Initial SessionFactory creation failed.org.hibernate.AnnotationException: Unknown mappedBy in: com.dockerhosting.domain.system.Command.child, referenced property unknown: com.dockerhosting.domain.system.Command.parentCommand

yet the parentCommand property is not missing as you can see.

I'm using hibernate 4.3.8

2

There are 2 answers

4
cнŝdk On BEST ANSWER

I think your problem is that you are defining two mappedBy properties for the same mapping, so Hibernate will get confused in the mapping.

So it's unecessary to use the two of them, you have two choices here:

1. To use only one Command object inside your class and map it with OneToOne like this:

@OneToOne(cascade = CascadeType.ALL)
private Command parentCommand;

2. Or to make it bidirectional use two Command objects in your class like you did and map the two of them with OneToOne but use mappedBy only with child to refer the parentCommand:

@OneToOne(mappedBy = "parentCommand", cascade = CascadeType.ALL)
private Command child;

@OneToOne(cascade = CascadeType.ALL)
private Command parentCommand;
0
Milkmaid On

You need to specify who will carry foreign key in your bidirectional relation(the owning side) if parent or child

child will contains reference(FK) of parrent

@OneToOne(cascade = CascadeType.ALL)
private Command child;

@OneToOne(mappedBy = "child", cascade = CascadeType.ALL)
private Command parentCommand;

Parent will contains reference(FK) of child

@OneToOne(mappedBy = "parentCommand", cascade = CascadeType.ALL)
private Command child;

@OneToOne(cascade = CascadeType.ALL)
private Command parentCommand;