Search code examples
javahibernatejpa

Hibernate @JoinColumn reusing column name to map to another entity


I have a column that contains a string, representing the name (and thereby primary key) of another entity, to which I am attempting to join the columns to store the entity in the parent. The entities look like so:

@Entity
public class Thing {

    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Id
    @Column(name = "thingname")
    private String name;
}

@Entity
public class Consumer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    @Column(name = "sourcething")
    private String source;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "sourcething", referencedColumnName = "thingname")
    private Thing thing;
}

This will throw a mapping error, denoting duplicate column mappings, so from this question I added the additional arguments:

@JoinColumn(name = "sourcething", referencedColumnName = "thingname", insertable = false, updatable = false)

However, this beings to fail with ConstraintViolationExceptions during unit testing.

Is there something I am missing for completing this mapping/column join?


Solution

  • I do not know your exact use case but the table defintions look strange to me. First of all an identifier (@ID) should be a numeric value or at least an UUID but not an arbitrary string. Why do not store the numeric ID in the table you mentioned pointing to that string? Something like this:

    @Entity
    public class Thing {
    
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Id
        private Long id;
    
        @Column(name = "thingname")
        private String name;
    }
    
    @Entity
    public class Consumer {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "sourcething_id")
        private Thing thing;
    }
    

    By this you can also access the string bby Consumer.thing.name

    BTW: the constraint violation presumably occurrs as you defined the sourcething as @JoinColumn(name = "sourcething", referencedColumnName = "thingname", insertable = false, updatable = false) but at the same time you insert a value using @Column(name = "sourcething") private String source; column.