ebean

Ebean with unidirectional OneToMany relationship causing duplicate column exception during insert


I have a table ENTRY with unique id UID. A second table PROGRAM with ID column as the key and PROGRAM_LIST_UID foreign key that refers to UID in ENTRY. I did not create the names, this is legacy code I am trying to maintain.

@Entity(name="entry")
public class Entry {
    @Id
    public int uid;
    
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="program_list_uid", referencedColumnName="uid")
    public List<Program> programList;

    ...
}

@Entity(name="program")
public class Program {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int id;

    @Column(length=150,name="program_name")
    public String programName;

    @Column(name="program_list_uid")
    public Integer entryId = 0;
}

When trying to save entry Ebean.save(entry), I get an exception

ERROR executing DML bindLog[] error[[SQL0121] Duplicate name PROGRAM_LIST_UID not allowed...

Trace shows that the insert statement indeed has the program_list_uid specified twice:

insert into program (program_list_uid, program_name, program_list_uid) 
values (?,?,?)

The only way I have found to make this work is to remove the entryId from Program. However this property is used elsewhere in the code.


Solution

  • The solution turns out to be adding insertable = false, updatable = false to @Column annotation on entryId. How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?

    @Entity(name="program")
    public class Program {
        @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
        public int id;
    
        @Column(length=150,name="program_name")
        public String programName;
    
        @Column(name="program_list_uid", insertable = false, updatable = false)
        public Integer entryId = 0;
    }