Dominic Dominic - 4 years ago 111
Java Question

Hibernate: Repeated Column in Mapping

So in this example scenario I have an attendance DTO, and a worker DTO, workers in this context are separated by department, and a worker can only ever be inside of one department. It is important to note that

Worker {id='123-123-123', department='a'}
is different to
Worker {id='123-123-123', department='b'}
, despite them both sharing the same Id.

I have the following class setup to try and separate functions by
id
and
department


public class IdAndDepartmentPK implements Serializable {

private String id;
private String department;

public IdAndDepartmentPK() {}
...
}


This key class is shared between DTOs that require both the
Worker
's
id
and
department
, below are the two DTOs that are causing a problem.

@Entity
@IdClass(IdAndDepartmentPK.class)
public class AttendencetDto {

@Id private String id; // This is a departmentally unique attendenceId
@Id private String department;
@Column private String workerId;

@JoinColumns({
@JoinColumn(name = "workerId"),
@JoinColumn(name = "department")
})
@ManyToOne(fetch = FetchType.EAGER)
private WorkerDto workerDto;
....
}

@Entity
@IdClass(IdAndDepartmentPK.class)
public class WorkerDto {

@Id
private String id;

@Id
private String department;
...
}


WorkerDto
does not need to have knowledge of
AttendencetDto
, but
AttendencetDto
, does need to have access to
WorkerDto
and the other data it contains.

Hibernate complains that fields like
workerId
should be mapped with insert="false" update="false", but if I was to do this then I wouldn't be able to persist those values to the database.

I essentially want to have those fields available whilst also having the
WorkerDto
available, is this possible?

Answer Source

You should remove @Column private String workerId; because you already map it by relation to WorkerDto.

If you want to create relation between that you should use setWorkerDto method in your AttendencetDto and just save. After transaction ends you will have your relation in DB.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download