Search code examples
javajpaeclipselink

JPA - Why use @JoinColumn?


I am using JPA with EclipseLink (2.5.2) .

I have the following Entities :

@Entity
@Table(name="Consumer")
public class Consumer implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "PRODUCER_ID")
    private Producer producer;

    public Consumer() {
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Producer  getProducer() {
        return producer;
    }

    public void setProducer(Producer consumesFrom) {
        this.producer = consumesFrom;
    }




}

and

@Entity
@Table(name="Producer")
public class Producer implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer Id;
    private String dataType;

    private List<Consumer> consumers = new ArrayList<>();


    public Producer() {
    }

    public Integer getId() {
        return Id;
    }

    public void setId(Integer id) {
        this.Id = id;
    }

    public String getDataType() {
        return dataType;
    }

    public void setDataType(String dataType) {
        this.dataType = dataType;
    }


}

And the persistence of Consumer :

   consumer.setProducer(producer); 
   entityManager.persist(consumer);

There is practically no difference in the expected outcome if I remove @JoinColumn(name = "PRODUCER_ID"). So I am trying to figure out what is the real usage of it.

I have read various examples over the Internet, I understand that it's purpose is to define the column which is used to join the two tables, but this is achieved through @ManyToOne already.

So, what's the point in it?


Solution

  • There is no difference because the default way, specified in the JPA specifications, to map a ManyToOne is to use a join column (as opposed to to join table, for example), and to use the name you chose for your join column, and to reference the ID of the target entity. If you wanted a different column name, or to reference another column, the annotation would be necessary.

    JoinColumn also has many other attributes (just read the documentation) that can be useful, and would thus need the annotation to be specified if you wanted to use them.