0

How to map a @ManyToOne association using a non-Primary Key in Hibernate? I can use a @NaturalId annotation, but sill have a error:

A Foreign key refering POJO.Question from POJO.Answer has the wrong number of column. should be 4

Question class (with multiple primary key):

    @Entity
    @Table(name = "[dbo].[Question]")
    public class Question implements Serializable {

        @Column(name = "[Id]", unique = true, nullable = false) 
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @NaturalId
        private Integer id;

        @EmbeddedId
        private QuestionEmbeddable questionEmbeddable;
}

Primary key

    public class QuestionEmbeddable implements Serializable{

        @Column(name = "[Development Template Id]")
        private int templateId;

        //Sekcja w templejcie
        @Column(name = "[Section]")
        private Integer section;

        //Numer w sekcji
        @Column(name = "[Number]")
        private Integer number;

        //Wersja 
        @Column(name = "[Version]")
        private Integer version;
}

Answer class:

    @Entity
    @Table(name = "[dbo].[Answer]")
    public class Answer implements Serializable {

        @Id
        @Column(name = "[Id]", unique = true, nullable = false) 
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;

        @JoinColumn(name = "[Question Id]")
        @ManyToOne(fetch=FetchType.LAZY)
        private Question question;

It looks like the association is still to @EmbeddedId instead of @Naturalid. I don't know why?

SternK
  • 11,649
  • 22
  • 32
  • 46
Eiten
  • 73
  • 8
  • duplicate of https://stackoverflow.com/questions/27215607/annotationexception-a-foreign-key-refering-has-the-wrong-number-of-column-shou – Dmitrii Bocharov Mar 20 '20 at 09:08
  • It is not, I'm not creating association with Embedded like in a example. I would like to create it with not-Primary key mark as @NaturalId – Eiten Mar 20 '20 at 12:13

1 Answers1

0

This is the answer, it is necessary to use a referencedColumnName

@ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
        name = "[Question Id]", referencedColumnName = "[Id]"
    )
    private Question question;
Eiten
  • 73
  • 8