I'm trying to figure out how to build JPA Entity beans to get the data working for my devices. The database is old and in stone, so I can't change schema. Device Models has a compound primary key, where one of the columns is a FK to Device Type.
I've tried a couple different things. First was the Device had a DeviceModel and a DeviceType, but that gave me the error that too many things were referencing dev_type. So then I tried to have DeviceModel have a reference to DeviceType but I ran into the same error.
If it helps/matters, I'm using Spring Data 4.2.x and Hibernate 4.3.8.Final to back everything.
Other answers I've found online (such as How to create and handle composite primary key in JPA) don't help me as they only map to basic data types. In fact, the answer above is implemented in my code below...but I need to go 1 level further.
The Schema:
create table devices
(
device_nbr serial(1),
device_id nchar(20) not null unique,
dev_type integer not null,
model_nbr integer default 1,
unit_addr nchar(32),
primary key (device_nbr),
foreign key (dev_type) references devtypes (dev_type),
foreign key (dev_type, model_nbr) references devmodels (dev_type, model_nbr)
);
create table devmodels
(
dev_type integer not null,
model_nbr integer not null,
model_desc nchar(20),
primary key (dev_type, model_nbr),
foreign key (dev_type) references devtypes (dev_type)
);
create table devtypes
(
dev_type integer not null,
dev_desc nchar(16) not null unique,
primary key (dev_type)
);
My Beans so far (which don't tie DeviceType to either Device or DeviceModel, that's what I need help with):
@Entity
@Table(name = "devices")
public class Device
{
@Id
@GeneratedValue
@Column(name = "device_nbr")
private Long number;
@Column(name = "device_id", length = 30)
private String id;
@Column(name = "unit_addr", length = 30)
private String unitAddress;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({
@JoinColumn(name = "dev_type"),
@JoinColumn(name = "model_nbr")
})
private DeviceModel deviceModel;
...Getters and setters
}
public class DeviceModelPK implements Serializable
{
private static final long serialVersionUID = -8173857210615808268L;
protected Integer deviceTypeNumber;
protected Integer modelNumber;
...Getters and setters
}
@Entity
@Table(name = "devmodels")
@IdClass(DeviceModelPK.class)
public class DeviceModel
{
@Id
@Column(name = "dev_type")
private Integer deviceTypeNumber;
@Id
@Column(name = "model_nbr")
private Integer modelNumber;
@Column(name = "model_desc")
private String description;
...Getters and setters
}
@Entity
@Table(name = "devtypes")
public class DeviceType
{
@Id
@GeneratedValue
@Column(name = "dev_type")
private Integer number;
@Column(name = "dev_desc", length = 30)
private String description;
...Getters and setters
}