hibernate一对一双向映射

本文探讨了SceneryPhoto与SceneryInformation两个类之间的双向一对一关联关系,并通过实例代码展示了这种关系的具体实现方式。注意在定义双向关联时不可直接初始化对象,否则将导致运行时错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SceneryPhoto和SceneryInformation 一对一双向关系,注意红色字体

package com.dio.blog.news.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;

@Entity
public class SceneryPhoto {


private int id;
private String name;
[color=red]private SceneryInformation sceneryInformation;[/color]

@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@OneToOne(mappedBy="sceneryPhoto")
public SceneryInformation getSceneryInformation() {
return sceneryInformation;
}
public void setSceneryInformation(SceneryInformation sceneryInformation) {
this.sceneryInformation = sceneryInformation;
}

}


package com.dio.blog.news.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class SceneryInformation {

private int id;
private String content;
[color=red] private SceneryPhoto sceneryPhoto; [/color]
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@OneToOne
@JoinColumn(name="sceneryPhotoId")
public SceneryPhoto getSceneryPhoto() {
return sceneryPhoto;
}
public void setSceneryPhoto(SceneryPhoto sceneryPhoto) {
this.sceneryPhoto = sceneryPhoto;
}

}

[color=red][size=x-large]在定义对应关系是不能初始化对象,否则会报错[/size][/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值