制图&使用spring数据JPA获取具有复合键的实体

时间:2013-05-28 03:49:06

标签: jpa spring-data-jpa

我有Spring MVC和Data JPA。我正在尝试做我有的映射表。结构如下:

Device
--------------
PK deviceId
   deviceName


Setting
--------------
PK deviceId
PK packageName
PK name
   value

我有这些表的课程:

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

但是当我把设备和设置数据放在同一个deviceId并使用repository.findOne(deviceId)查询DeviceSetting时,我没有得到设备数据;

我还需要做些什么来获取设备数据?任何意见将是有益的。感谢。

1 个答案:

答案 0 :(得分:10)

更改映射如下。

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

然后使用以下代码进行查找。

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

// use the deviceSettingRespository to lookup
repository.findOne(id);