EJB3 Entity-Relationships
Had some fun with EJB3 Entity definitions today, that showed a pitfall of “Quick-and-easy-don’t-think-about” relationship definition.
Situation is as follows:
A.java
@ManyToMany(mappedBy = "a" , fetch = FetchType.LAZY, cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<B> b = new HashSet<B>();
B.java
@OneToOne(fetch = FetchType.LAZY, cascade=CascadeType.ALL) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private A a;
The error is quite easy to spot if you look at it. Guessed it ?
@ManyToMany has to be replaced with @OneToMany, obviously.
The funny part about this is what Hibernate and its MySQL-Dialect make of it: It creates a table B referencing A’s id with a foreign key, which is just as expected. But unfortunately it created a self-referencing Foreign-Key on B like:
CREATE TABLE b ( uid int(11) NOT NULL auto_increment, a_uid int(11) default NULL, PRIMARY KEY (uid), KEY FK2CB2E99731B30EB6 (a_uid), CONSTRAINT 'FK2CB2E9972B5AECE0' FOREIGN KEY ('uid') REFERENCES 'b' ('uid'), CONSTRAINT 'FK2CB2E99731B30EB6' FOREIGN KEY ('a_uid') REFERENCES 'a' ('uid') ) TYPE=InnoDB;
which makes it quite impossible to insert an initial b row when using GenerationType.AUTO, like i do.
So if you’re unable to insert self-created relation classes, recheck
both
sides to make sure you did not peer OneToOne with ManyToMany.
Shouldn’t the EntityManager freak out when approaching incompatible definitions like that?

