Search code examples
hibernateone-to-one

Java Hibernate : findAll with include "one to one" relationship


I want return all command record with relationship of processor table


@Entity // This tells Hibernate to make a table out of this class
public class Command {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String type;
    private Integer status;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "processor_id", referencedColumnName = "id")
    private Processor processor;
    

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
  
    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

}


@Entity // This tells Hibernate to make a table out of this class
public class Processor {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;
    private String ip;
    private String mac;
    private boolean status;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getMac() {
        return mac;
    }

    public void setMac(String mac) {
        this.mac = mac;
    }
    public boolean getStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }
    
}

CommandRepository.java

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface CommandRepository extends CrudRepository<Command, Integer> {

}

main.java

@GetMapping(path="/all")
    public @ResponseBody Iterable<Command> getAllCommand() {
        // This returns a JSON or XML with the users
        return commandRepository.findAll();// this is not returning processor data
    }

Solution

  • Getter/Setters for processor are missing in the Command entity class. Add them check ,it should work.