My mappings are below.
Here is the base class for all classes. There is no table for this class. All subclasses user id as their PK.
开发者_如何转开发@MappedSuperclass
public abstract class Model {
private Long id;
@Id
@GeneratedValue(strategy=GenerationType.Sequence, generator="myGenerator")
public Long getId() { return id; }
}
A class for Comments that has its own table, with columns for all the fields in Model
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@Table(name = "COMMENT")
@SequenceGenerator(name="myGenerator", sequenceName="COMMENT_SEQ", allocationSize=1)
public class Comment extends Model {
//some data
}
A subclass of Comment that also has its own table, with columns for all the fields in Comment and Model
@Entity
@Table(name = "ORDER_COMMENT")
@SequenceGenerator(name="myGenerator", sequenceName="ORDER_COMMENT_SEQ", allocationSize=1)
public class OrderComment extends Model {
//some data
}
This class has its own table and can have one to many order comments.
@Entity
@Table(name="ORDER")
@SequenceGenerator(name="myGenerator", sequenceName="ORDER_SEQ", allocationSize=1)
public class Order extends Model {
private Set<OrderComment> = new HashSet<OrderComment>();
@OneToMany
@JoinColumn(name="ORDER_ID")
public Set<OrderComment> getComments() { return comments; }
}
The issue is that when I add a new OrderComment to an Order, Hibernate selects the id from the sequence for Comment instead of the sequence for OrderComment.
Any ideas on why this is happening and what I can change to fix this issue? Or is there a better way to map this?
A SequenceGenerator is globally identified by it's name, hence you can only have one called "myGenerator".
If you wish to use your identifier on a global variable, with @GeneratedValue, you'll need to define a single @SequenceGenerator and use a single sequence for all your tables.
Alternatively, you could keep an abstract getId method at your superclass and implement it on every subclass: hibernate is happy and you'll have a uniform way to reach your id's.
We use the sequence generator here to make each Model distinguishable, So a Comment is a Model, an OrderComment is a Model, an Order is a Model, too. They should share a sequence generator from this view.
You can define a single sequence generator used by multiple entities as this post.
精彩评论