【第一章 Design】 7 主键生成详细步骤

什么是自动生成列

Many databases allow users to define special columns with values that are automatically created by the the database to be unique for each inserted row. Main use if this feature is to generate a primary key. Such columns are often called "autoincrement" or "identity" columns. JDBC3 specification provides Java API to read values of such columns right after an insert is performed. JDBC calls such columns "generated keys", and Cayenne follows JDBC in that. Namely DbAttribute has a "generated" boolean property to indicate that a given column value is provided by the database on insert.

 

 

在Cayenne指定自动生成列

主键生成是Cayenne中自动生成列的唯一应用。

 

If a primary key column is marked as "generated" in CayenneModeler (see below), Cayenne will bypass its default PK generation mechanism and rely on the database to provide a key value. But only if the runtime DbAdapter is configured to allow that (see "Hints and Limitations" section for explanation). Currently only Derby, MySQL and SQLServer adapters allow generated columns by default. For the rest of the adapters, Cayenne will fall back to its default PK generation mechanism.

 

如果你的驱动支持自动生成API,但是在Cayenne中没有开启,可以手动开启:

 
在 CayenneModeler中,每个DbEntity 有独立的主键自动生成配置:

    
    
  • 找到DbEntity的"PK Generation Strategy"并设置它的值为 "Database-Generated":

 

  • 从已经存在的主键中,选择一个主键列,用于数据库的自增列:

 

 
 

提示和限制

  • Only a single DbAttribute can be marked as "generated" in a DbEntity. Most databases only allow a single generated column per table, and Cayenne consistently adheres to the same policy.
  • Generated attribute must also be a primary key.
  • Database must support this feature.
  • JDBC driver must support this feature. Even if database supports identity columns, the driver may not. By default Cayenne assumes that the following drivers support it: Derby, MySQL and SQLServer jTDS (but not the MS) driver.

MS SQLServer 注意

SQLServer2005之前不支持自动生成列,新的驱动和jTDS能很好支持。Cayenne可以自动检测驱动类型并配置SQLServerAdapter,但是仅当使用了AutoAdapter时。确定自动检测有效,清除模型中相应的DataNode的"Custom Adapter"字段。

 

 

原文:

 

http://cayenne.apache.org/doc/generated-columns.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值