问题
I have a class hierarchy:
abstract DomainObject {
...
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SEQ")
@SequenceGenerator(name="SEQ",sequenceName="SEQ_DB_NAME")
@Column(name = "id", updatable = false, nullable = false)
private Long id;
...
}
BaseClass extends DomainObject {
...
// Fill in blank here where this class's @Id will use a unique sequence generator
// bonus points for any sort of automatic assignment of generator names that might
//prevent me from having to instrument all my domain objects uniquely
...
}
notes:
- I do not specifically need a base class generator, so if it behooves me to remove it no problem.
- This is an oracle 9i db if that is applicable
- Hibernate 3.4 JPA
- Spring 2.5 is available as well
Thanks
回答1:
Okay here's how I ended up solving the problem:
Base class:
@MappedSuperclass
public abstract class DomainObject implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SEQ")
@Column(name = "id", updatable = false, nullable = false)
private Long id;
.. rest of class
}
Descendant class:
@Entity
@SequenceGenerator(name="SEQ",sequenceName="SEQ_DB_NAME")
public class BusinessObject extends DomainObject {
...
}
回答2:
I would recommend you use the JOINED inheritance type for the base class. This puts all of the common fields in the base table and customizations in specific tables. Here is the annotation for that:
@Inheritance(strategy=InheritanceType.JOINED)
Once that is done, you can pretty much use any sequencing option as all of your IDs are always on the same table. You can use a separate sequence if you want but it is not supported in all database vendors. I guess that is not an issue since you are using Oracle specifically.
I've used this and it seems to work well.
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
来源:https://stackoverflow.com/questions/1032486/what-is-the-proper-jpa-mapping-for-id-in-parent-and-unique-sequence-in-base-cla