是的,它会起作用的。您可以使用 JPA 注释的实体,同时使用 Hibernate Criteria 而不是 JPA Criteria 来查询您的实体。
我已经测试过了。
我的实体类如下所示:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class TestEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Version
private Long version;
...
}
然后,我有 Hibernate 配置文件:hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.test.model.TestEntity" />
</session-factory>
</hibernate-configuration>
注意,我仍然需要列出实体类,但我没有使用 Hibernate 映射文件 (hbm.xml)。我不认为 Hibernate 支持自动检测实体类,就像 JPA 那样(所以即使它们被注释,你仍然必须将它们列出来)。
然后我将这段代码作为测试,持久化实体,然后使用 Hibernate Criteria 检索:
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
TestEntity testEntity = new TestEntity();
testEntity.setName("test");
session.save(testEntity);
List<TestEntity> tests = (List<TestEntity>) session.createCriteria(TestEntity.class).list();
for (TestEntity test : tests) {
System.out.println(test.getName());
}
session.getTransaction().commit();
我有 ff。在我的控制台中输出:
Hibernate: insert into TestEntity (name, version) values (?, ?)
Hibernate: select this_.id as id1_0_0_, this_.name as name2_0_0_, this_.version as version3_0_0_ from TestEntity this_
test