What is the proper JPA mapping for @Id in parent and unique sequence in base classes

我是研究僧i 提交于 2020-01-24 02:26:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!