Mapping & fetching entities with composite keys using spring data JPA

15,593

Change the mapping as follows.

@Entity
public class DeviceSetting implements Serializable {
    @EmbeddedId
    private DeviceSettingPk deviceSettingId;


    @ManyToOne
    @JoinColumn(name="deviceId", referencedColumnName="deviceId", insertable=false, updatable=false)
    private Device device;

    //Setters and Getters
}

And then use the following code to lookup.

DeviceSettingPk id = new DeviceSettingPk(deviceId, packageName, name);

// use the deviceSettingRespository to lookup
repository.findOne(id);
Share:
15,593
sunghun
Author by

sunghun

Updated on June 20, 2022

Comments

  • sunghun
    sunghun almost 2 years

    I have Spring MVC and Data JPA. I am trying to do mapping tables I have. The structure is like below:

    Device
    --------------
    PK deviceId
       deviceName
    
    
    Setting
    --------------
    PK deviceId
    PK packageName
    PK name
       value
    

    And I have classes for those tables:

    @Entity
    public class DeviceSetting implements Serializable {
        @EmbeddedId
        private String deviceId
        private String deviceName;
    
        @ManyToOne
        @JoinColumn(name="deviceId", referencedColumnName="deviceId", insertable=false, updatable=false)
        private Device device;
    
        //Setters and Getters
    }
    
    @Embeddable
    public class DeviceSettingPk implements Serializable {
    
        private String deviceId;
        private String packageName;
        private String name;
    
        public DeviceSettingPk(){}
        public DeviceSettingPk(String deviceId, String packageName, String name) {
            super();
            this.deviceId = deviceId;
            this.packageName = packageName;
            this.name = name;
        }
    
           //Setters and Getters
    }
    
    @Entity
    public class Device implements Serializable {
    
        private static final long serialVersionUID = 1L;
    
        @NotEmpty
        @Id
        @Column(name="deviceId")
        private String deviceId;
    
            private String deviceName;
    
            //Getters and Setters
    }
    

    But I did not get device data when I put device and setting data has same deviceId and queried DeviceSetting by using repository.findOne(deviceId);

    What else do I need to do to get the device data? Any advice would be helpful. Thanks.