我有:
- PostgreSQL 9.4
- 阿帕奇卡宴 4.0.M3
由一个最简单的表“proba”组成的模式:
CREATE TABLE proba ( id bigint NOT NULL, value character varying(255), CONSTRAINT proba_pkey PRIMARY KEY (id) )
一个简单的 Main 方法:
public static void main(String[] args) { ServerRuntime runtime = ServerRuntimeBuilder.builder() .addConfig("cayenne-project.xml") .build(); ObjectContext ctx = runtime.newContext(); CayenneDataObject newObject = new CayenneDataObject(); newObject.writeProperty("value", "proba1"); ctx.registerNewObject(newObject); ctx.commitChanges(); }
一个简单的 cayenne-project.xml:
<?xml version="1.0" encoding="utf-8"?> <domain project-version="7"> <map name="datamap"/> <node name="datanode" factory="org.apache.cayenne.configuration.server.XMLPoolingDataSourceFactory" schema-update-strategy="org.apache.cayenne.access.dbsync.SkipSchemaUpdateStrategy"> <map-ref name="datamap"/> <data-source> .... </data-source> </node> </domain>
一个简单的datamap.map.xml(手工制作):
<?xml version="1.0" encoding="utf-8"?> <data-map xmlns="http://cayenne.apache.org/schema/7/modelMap" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cayenne.apache.org/schema/7/modelMap http://cayenne.apache.org/schema/7/modelMap.xsd" project-version="7"> <property name="defaultPackage" value="ru.xxx"/> <property name="defaultSchema" value="public"/> <db-entity name="proba" schema="public"> <db-attribute name="id" type="BIGINT" isPrimaryKey="true" isGenerated="false" length="19"/> <db-attribute name="value" type="VARCHAR" length="255"/> </db-entity> <obj-entity name="Proba" dbEntityName="proba"> <obj-attribute name="value" type="java.lang.String" db-attribute-path="value"/> </obj-entity> </data-map>
尝试一下,我得到了以下输出:
INFO: --- transaction started.
Nov 15, 2016 5:06:26 PM org.apache.cayenne.log.CommonsJdbcEventLogger logQuery
INFO: SELECT nextval('public.pk_proba')
Exception in thread "main" org.apache.cayenne.CayenneRuntimeException: [v.4.0.M3 Feb 08 2016 16:38:05] Commit Exception
at org.apache.cayenne.access.DataContext.flushToParent(DataContext.java:776)
at org.apache.cayenne.access.DataContext.commitChanges(DataContext.java:693)
at com.echelon.proba.cayenne.Main.main(Main.java:27)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "public.pk_proba" does not exist
Position: 16
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2458)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2158)
因此,cayenne 需要一个名为 pk_proba 的序列。为什么?我并不是要生成它。我在我的模式和 Cayenne 映射中都没有提到任何 postgresql 序列。
所以,我有两个问题:
- 如果在提交时没有为特定实体提供身份,我如何抑制 Cayenne 尝试生成 ID 并使 Cayenne 快速失败?
- 我是否可以自定义一种 Cayenne 在我的项目中管理 PK 自动生成的方式(最好的解决方案是不涉及 Cayenne Modeller 的解决方案)?