H2 [Hibernate] @OneToOne-Beziehung

turmaline

Bekanntes Mitglied
Hallo Leute,

ich möchte eine die Klasse Comment mit der Klasse Attachment verbinden. So habe ich es gemacht:

Java:
@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(
			name = "attachmentId", unique = true, nullable = false, updatable = false)
	protected Attachment attachment;

	public Attachment getAttachment() {
		return attachment;
	}

	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;

Java:
 @OneToOne(optional = false, mappedBy = "comment")
    protected Comment comment;

    public Comment getComment() {
		return comment;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
	}

nun.. mir ist es nicht ganz klar wie die verbindung funktioniert. Wenn ich beim Attachment getComment() aufrufe, bekomme ich die Referenz auf den richtigen Comment oder soll ich das irgendwie noch setzten:

Klasse Comment
Java:
@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(
			name = "attachmentId", unique = true, nullable = false, updatable = false)
	protected Attachment attachment;

	public Attachment getAttachment() {
		return attachment;
	}

	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;
attachment.setComment(this);

Klasse Attachment
Java:
 @OneToOne(optional = false, mappedBy = "comment")
    protected Comment comment;

    public Comment getComment() {
		return comment;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
comment.setAttachment(this);
	}
 
die Beziehung zwischen Comment und Attachment ist nur unidirektional (Comment -> Attachment). Es sieht so aus:

Java:
@OneToOne(cascade = CascadeType.ALL)
	@JoinColumn(
			name = "attachmentId", unique = true, nullable = true, updatable = false)
	protected Attachment attachment;

Soweit ich CascadeType.ALL verstehe, sollte der referenzierte Attachment automatisch gelöscht werden, wenn ich den Comment lösche. Das funktioniert nicht. Was mach ich falsch?

Gruß,
madlena
 

Zurück
Oben