首页 > 解决方案 > 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();

标签: javaspring-boothibernate

解决方案


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

@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注释(请参阅文档的这一部分


推荐阅读