java - Java休眠:访问外键
问题描述
处理器.java
@Entity
public class Processor {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private boolean running;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "firmware_id", referencedColumnName = "id")
private Firmware firmware;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
...
public Firmware getFirmware() {
return firmware;
}
public void setFirmware(Firmware firmware) {
this.firmware = firmware;
}
}
固件.java
@Entity
public class Firmware {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String version;
private String filename;
//Getter & Settger
}
ProcessorRepository.java
public interface ProcessorRepository extends CrudRepository<Processor, Integer> {
}
处理器控制器.java
...
@PutMapping(path = "/") // Map ONLY POST Requests
public @ResponseBody
Map<String, Object> addProcessor(@RequestBody Processor p) {
System.out.println("Put: " + p.getId());
processorRepository.save(p);
// I want to access : p.firmware_id;
// ex) p.setFirmware_id(8)
// ex) int tmp = p.getFirmware_id();
return Collections.singletonMap("success", true);
}
...
下面的代码可以在 java/spring-boot/hibernate 中使用吗?
// ex) p.setFirmware_id(8)
// ex) int tmp = p.getFirmware_id();
解决方案
您可以尝试以这种方式更正您的映射:
@Entity
public class Processor {
// ...
// @NotFound ( action = NotFoundAction.IGNORE )
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "firmware_id", referencedColumnName = "id", insertable = false, updatable = false)
private Firmware firmware;
@Column(name = "firmware_id")
private Integer firmwareId;
// ...
}
然后firmware_id
通过设置firmwareId
。
可能对于这种情况,您还应该使用@NotFound
注释(请参阅文档的这一部分)
推荐阅读
- javascript - AWS 控制台的 SessionBox 样式扩展:您可以使用 Chrome 扩展 API 创建新的 chrome 配置文件吗?
- sql - 从另一个表插入条件数据
- python - 如何在 pydantic 中重用 root_validator
- java - 获取 - 包 org.json 不存在 - 无法使用 JSONArray / JSONObject
- django - 为什么我会收到 heroku 错误:App 与 buildpack 不兼容
- flutter - 在颤动中对齐特定字符
- laravel - 无法使用 laravel echo 服务器接收事件
- javascript - 即使存在 id,javascript id 选择器也会返回 null
- python - 根据 pandas 数据框中的值创建文件夹结构
- here-api - HERE交通API解释速度数据