微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【第一章 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐