Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JPA equivalent to Hibernate's foreign id generator?

What is the JPA equivalent to Hibernate's foreign id generator?

<id column="PERSON_ID" name="id" type="java.lang.Long">
   <generator class="foreign">
      <param name="property">person</param>
   </generator>
</id>

2 Answers

AFAIK , JPA specification does not standardize the foreign ID generator . You have to programmatically set the PK value correctly before saving this instance.

As for Hibernate , it has an extension annotation to enable foreign ID generator . You may choose to use it if you don't mind:

  @Id
  @GeneratedValue(generator = "myForeignGenerator")
  @org.hibernate.annotations.GenericGenerator(
        name = "myForeignGenerator",
        strategy = "foreign",
        parameters = @Parameter(name = "property", value = "person")
  )
  @Column(name = "PERSON_ID")
  private Long id;
like image 121
Ken Chan Avatar answered Oct 30 '25 08:10

Ken Chan


For what it's worth JPA 2.0 adds a @MappedBy annotation that can be used for foreign key importing. Starting from Christian's example and boring briefly from Ken Chan's:

@Id
@Column
private Long personId;

@ManyToOne
@JoinColumn(name = "personId")
@MapsId
private Person person;

I know this question is from quite some time ago, but since I stumbled across it when solving the same issue and then dug up @MappedBy, I thought I'd add it for anyone who runs into this later.

like image 32
Geoffrey Wiseman Avatar answered Oct 30 '25 09:10

Geoffrey Wiseman