Istao
Istao

Reputation: 7585

JPA : relation with other column than id

When I do a relation one to one with to entities, JPA use the id to register the target ; but I should want an other column. How is possible ?

For instance I have two entities :

@Entity
public class Target
{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id;

  @Column(unique=true, nullable=false)
  private String code;

 // and so on 
}

That's make a table with columns ID and CODE.

A second entity with a link to Coder :

@Entity
public class ToTarget
{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private String id;

 private Target targeted;

 // and so on 
}

That's make a table with column ID and TARGET_ID. In TARGET_ID I have some id from column ID in table Target.

All is good, but I should want, in TARGET_ID, some code value from table Coder. How is it possible ?

Thanks.

Upvotes: 2

Views: 3949

Answers (1)

JB Nizet
JB Nizet

Reputation: 691943

Use the referencedColumnName attribute of the @JoinColumn annotation. I'm not sure this is supported by the standard though. It might work in some implementations, and not in others.

See http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html#entity-mapping-association for Hibernate, and http://openjpa.apache.org/builds/2.1.0/apache-openjpa-2.1.0/docs/manual/manual.html#ref_guide_mapping_notes_nonstdjoins for OpenJPA.

Upvotes: 3

Related Questions