Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}

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

Below code is possible in java/spring-boot/hibernate?

   // ex) p.setFirmware_id(8)  
   // ex) int tmp = p.getFirmware_id();
like image 367
Yang Yu Avatar asked Mar 26 '26 09:03

Yang Yu


1 Answers

You can try to correct your mapping in this way:

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

   // ...
}

and then set firmware_id via firmwareId.

Probably for this case you should use also @NotFound annotation (see this section of the documentation)

like image 118
SternK Avatar answered Apr 01 '26 07:04

SternK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!