简体   繁体   English

如何将@TableGenerator注释用于非PK id

[英]How to use the @TableGenerator annotation for a non-PK id

This is an extract of the JPA entities schema 这是JPA实体架构的摘录



    @Entity
    @Table(name="customer")
    public class Customer implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="customer_id")
        private Long id;

        @ManyToOne
        @JoinColumn(name="company_id",nullable=false)
        private Company company;

    //...

    }

    @Entity
    @Table(name="company")
    public class Company implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="company_id")
        private Long id;

    //...

    }

    @Entity
    @Table(name="order_header")
    public class OrderHeader implements Serializable {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="order_id")
        private Long id;


        @ManyToOne
        @JoinColumn(name="customer_id",nullable=false)
        private Customer customer;

        private Long internalCompanyOrderId;

    //...

    }

I need to retreive an unique internalCompanyOrderId sequence for each Company_id. 我需要为每个Company_id检索一个唯一的internalCompanyOrderId序列。 It means that nevertheless the Order PK will be 'order_id', I need an "internal" order_id for each Company. 这意味着订单PK将是'order_id',我需要每个公司的“内部”order_id。

There is no occurrences of @TableGenerator in your code sample. 代码示例中不会出现@TableGenerator。 I assume you want to generate value with @GeneratedValue. 我假设您想要使用@GeneratedValue生成值。

What it comes to JPA 2.0, according specification you cannot use @GeneratedValue for field that is not part of the primary key: 它是什么来到JPA 2.0,根据规范,您不能将@GeneratedValue用于不属于主键的字段:

The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. GeneratedValue注释可以与Id注释一起应用于实体或映射超类的主键属性或字段。 [97] [97]
... ...
[97] Portable applications should not use the GeneratedValue annotation on other persistent fields or properties. [97]便携式应用程序不应在其他持久字段或属性上使用GeneratedValue批注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM