Java hibernate : Access foregin key



Processor.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;
}
}

Firmware.java

@Entity
public class Firmware {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String version;
private String filename;
//Getter & Settger
}

处理器存储库.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/hhibernate中是否可行?

// 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;
// ...
}

然后经由CCD_ 2设置CCD_。

对于这种情况,您可能还应该使用@NotFound注释(请参阅文档的本节)

p.getFirmware().getId() or p.getFirmware().setId(id) whatever works

最新更新