Reputation: 2360
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;
}
Upvotes: 3
Views: 2778
Reputation: 2360
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.
Upvotes: 4
Reputation: 5178
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
.
Upvotes: 0