简体   繁体   中英

Hibernate create foreign key to itself

I have a very strange problem with hibernate at the moment. Somehow on a table, it create a foreign key which reference to itself. the column is also a primary key. This essentially prevent me from delete any row from that table.

In the log I could see a line:

DEBUG org.hibernate.SQL - alter table Device add index FK79D00A76C682495E (id), add constraint FK79D00A76C682495E foreign key (id) references Device (id)

Other table with similar table seems fine. and this seems to be true for both MySQL and Derby. I'm using hibernate 4.1.4

the annotated class is as follow.

@Entity(name = "Device")
public class Device extends DomainObject implements Searchable {

    @Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected long id;

    @Column(name = "Type")
    @Enumerated(EnumType.STRING)
    private DeviceTypeEnum type = DeviceTypeEnum.AccessControlDevice;

    @Column(name = "Name", length = Constance.DATABASE_NAME_FIELD_LENGTH)
    private String name;

    @Column(name = "Description", length = Constance.DATABASE_DESCRIPTION_FIELD_LENGTH)
    private String description;

    @Column(name = "Identifier", length = Constance.DATABASE_IDENTIFIER_FIELD_LENGTH, unique = true)
    private String identifier;

    @ManyToMany
    @JoinTable(name = "Device2Group", joinColumns = {@JoinColumn(name = "DeviceID")}, inverseJoinColumns = {@JoinColumn(name = "DeviceGroupID")})
    private List<DeviceGroup> groups = new ArrayList<DeviceGroup>();

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "location")
    private Location location;

    @ManyToOne(cascade = {CascadeType.ALL})
    @JoinColumn(name = "Address")
    private Address address;


    @ManyToOne
    @JoinColumn(name = "Link", nullable = false)
    private Link link;
}

It turns out that in one of the Entity Class "Location" which the Device entity references, it has a @ManyToMany mapped collection of Device, where it really should be @OneToMany . After change the @ManyToMany to @OneToMany the constrain disappears.

I see no references to Device class in your code. So I am assuming that this class has been modified, but its table has not, because it has some data . (Why else should it have a foreign-key to itself?)

Try dropping this table in your database to make hibernate create it once more, or set p.hibernate.hbm2ddl.auto to create-drop .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM