Java Hibernate: 访问外键

3

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
}

ProcessorRepository.java

public interface ProcessorRepository extends CrudRepository<Processor, Integer> {

}

ProcessorController.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();
2个回答

1
您可以尝试以这种方式更正您的映射:

@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;

   // ...
}

然后通过 firmwareId 设置 firmware_id

对于这种情况,您还应该使用 @NotFound 注释(请参见文档的 this section 部分)。


我不知道这个 , insertable = false, updatable = false 是什么意思,但是它运行良好,谢谢。 - Wang Liang

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

是的,但我不想使用 getFirmware() - Wang Liang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接