我已经坚持了一段时间,无法取得进展。问题是当 DB 中的限制字段是 FK 时如何使用 Hibernate 的createCriteria 。
这里有 2 个表:account和 *cf_account_type*,代表限定符(客户、员工等)
CREATE TABLE account (
usern character varying(30) NOT NULL,
cf_account_type character varying(30) NOT NULL
);
ALTER TABLE ONLY account
ADD CONSTRAINT pk_account366 PRIMARY KEY (usern);
CREATE TABLE cf_account_type (
cf_account_type character varying(30) NOT NULL
);
ALTER TABLE ONLY cf_account_type
ADD CONSTRAINT pk_cf_account_type373 PRIMARY KEY (cf_account_type);
ALTER TABLE ONLY account
ADD CONSTRAINT fk_account465 FOREIGN KEY (cf_account_type)
REFERENCES cf_account_type(cf_account_type);
Hibernate 文档建议的解决方案可在 此处找到,如下所示:
Cat cat = new Cat();
cat.setSex('F');
cat.setColor(Color.BLACK);
List results = session.createCriteria(Cat.class)
.add( Example.create(cat) )
.list();
但是,性别和颜色不是对象,而是纯文本字段。所以,问题是我的代码从account中返回所有行,并且似乎没有考虑到限制。
Session session = SF.getSession();
Transaction tx = session.beginTransaction();
//creating an example instance
Account instance = new Account();
instance.setCfAccountType(cfAccountType);
//fetching from db
List<Account> result = (List<Account>)session.
createCriteria(Account.class).
add(Example.create(instance)).list();
tx.commit();
附加信息:
数据库是 PostgreSQL 9.1.2,它通过 JDBC4 (postgresql-9.1-902.jdbc4.jar) 连接
从 hibernate.cfg.xml 文件中提取
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">CENSORED</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/CENSORED</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.search.autoregister_listeners">false</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>