简体   繁体   English

JPA-如何使用表默认值生成主键?

[英]JPA - How to use table default value for primary key generation?

I have a table with primary key generation of TO_NUMBER(TO_CHAR(SYSDATE@!,'YYDDD')||LPAD(TO_CHAR(SEQ_REFID.NEXTVAL),11,'0')) 我有一个主键生成为TO_NUMBER(TO_CHAR(SYSDATE@!,'YYDDD')||LPAD(TO_CHAR(SEQ_REFID.NEXTVAL),11,'0'))

This has been given as default value for the table. 这已作为表的默认值给出。 When I insert through JDBC, I could leave the column as NULL, so the pk would be generated/defaulted and i'll get the key using getGeneratedKeys() method. 当我通过JDBC插入时,我可以将该列保留为NULL,因此pk将被生成/默认,并且我将使用getGeneratedKeys()方法获取密钥。

I require similar behavior using JPA. 我需要使用JPA进行类似的行为。 I'm a beginner in JPA. 我是JPA的初学者。 Pl help. 请帮助。 Database used is Oracle 11g. 使用的数据库是Oracle 11g。

EDIT: The above mentioned value is not required to be table default. 编辑:上面提到的值不需要是表默认值。 It can be applied from JPA layer if it is possible. 如果可能,可以从JPA层应用它。

Other Entities depends on this Entity for the pk. 其他实体依赖于该实体的pk。 PK must be passed over to all child tables. PK必须传递到所有子表。

Add the following annotation to the id field: 将以下注释添加到id字段:

@Column(insertable = false)

This way, JPA will ignore the field when inserting new values and the database automatically generates the desired key. 这样,JPA在插入新值时将忽略该字段,并且数据库会自动生成所需的密钥。

However, you shouldn't use such a primary key. 但是,您不应使用这样的主键。 It effectively contains 2 different kinds of data in one column which should better be split into two seperate columns. 它有效地在一列中包含2种不同类型的数据,最好将其拆分为两个单独的列。

Make a simple id column with an ascending integer (and absolutely meaning other than " this is entry nr. x "). 用一个升序的整数创建一个简单的id列(绝对含义不是“ 这是条目nr。x ”以外的含义)。 Then add an additional column with the current timestamp. 然后添加带有当前时间戳的其他列。 This timestamp can have a default value and be protected against updates. 该时间戳记可以具有默认值,并可以防止更新。

This is how it's supposed to be and not only simplifies your queries, but also improves the performance. 这就是应该的样子,不仅可以简化查询,还可以提高性能。 You can query the table for entries of a specific hour, week and so on, or generate detailed statistics. 您可以查询表中特定小时,星期等的条目,或生成详细的统计信息。

Don't try to put multiple information into one column. 不要试图将多个信息放在一栏中。 There's no advantage. 没有优势。

@Entity
public class Entity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

}

Can also be 也可以是

GenerationType.AUTO
GenerationType.SEQUENCE
GenerationType.TABLE

This reference describes the various strategies 本参考资料描述了各种策略

Where did you get the idea that this default PK was a good idea? 您从哪里得知此默认PK是个好主意?

If you want the creation time of the row, add a column to your table. 如果要创建行的时间,请在表中添加一列。 Don't embed it in the PK like this. 不要像这样将其嵌入PK中。

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

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