Hibernate OneToOne bidirectional relationship not working in the same class

I am trying to create a "chain of command" using a one-to-one hibernation relationship with 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 such a relationship? During initialization, it throws the following exception:

 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

      

but the parentCommand property is missing as you can see.

I am using hibernate 4.3.8

+3


source to share


2 answers


I think your problem is that you are defining two properties mappedBy

for the same mapping, so Hibernate will get confused about the mapping.

So there is no need to use two of them, you have two options:

1. To use only one object Command

inside your class and map it to OneToOne

like this:



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

      

2. Or for bidirectional use of two objects Command

in your class like you, and map them using OneToOne

, butmappedBy

only use with the child to reference parentCommand

:

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

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

      

+1


source


You need to specify who will carry the foreign key in a bidirectional relationship (owner-side) if parent or child

the child will contain a link (FK) of the parrent file

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

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

      



The parent will contain the link (FK) of the child

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

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

      

+1


source







All Articles