Reputation: 113
I'm trying to relate two classes in jpa with a OneToOne relation. I have the class A with this composite key:
@Embeddable
public static class AId implements Serializable
{
private static final long serialVersionUID = -3668842379109008885L;
private long idA;
private String codType;
private Date startDate;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((codType == null) ? 0 : codType.hashCode());
result = prime * result + (int) (idA ^ (idA >>> 32));
result = prime * result
+ ((startDate == null) ? 0 : startDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AId other = (AId) obj;
if (codType == null) {
if (other.codType != null)
return false;
} else if (!codType.equals(other.codType))
return false;
if (idA != other.idA)
return false;
if (startDate == null) {
if (other.startDate != null)
return false;
} else if (!startDate.equals(other.startDate))
return false;
return true;
}
public long getIdA() {
return idA;
}
public void setIdA(Long idA) {
this.idA = idA;
}
public String getCodType() {
return codType;
}
public void setCodType(String codType) {
this.codType = codType;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name="idA", column=@Column(name="ID_A")),
@AttributeOverride(name="codType", column=@Column(name="COD_TYPE")),
@AttributeOverride(name="startDate", column=@Column(name="START_DATE"))
})
private AId idAId;
and class B with a simple primary key
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="GEN_ID_STORE" )
@Column(name="ID")
private Long id;
@OneToOne(fetch=FetchType.EAGER)
private A a;
Now my question is, how can I relate these two classes only using the idAId.idA field? Because I would like to have in my B table only the ID_A column and not the other ones. I explain myself better, my problem is that I have to pick up from the table A only those records with codType = 'COD' and startDate = null, in fact the other two keys aren't important because they are fixed. What can I do?
A bridge table is not permitted :D
Thanks for your help.
Upvotes: 0
Views: 650
Reputation: 14061
Because I would like to have in my B table only the ID_A column and not the other ones
That's my main problem with composite keys. If you have a composite key in one table, this means that all of those keys, together, defines one record. Thus, if you need to refer to this one record in another table, you need to have all of the keys.
So, in short: you can't have only one field on table B that would contain the reference to a record on table A, if the table A has a composite primary key.
Upvotes: 1