我可以在不与 Hibernate 映射的情况下使用 Hibernate Criteria 吗?

Can I use Hibernate Criteria without mapping with Hibernate?

我正在使用 JPA 注释来映射模型中的实体。但是,我发现 Hibernate Criteria 易于使用并且包含较少的代码编写,那么有没有一些方法可以使用 Criteria 而无需映射到 hibernate xml 方式?我在我的 DAO 实现中试过这个 class:

private SessionFactory sFactory; // of type org.hibernate.SessionFactory
....

Session session = sFactory.getCurrentSession();
Criteria criteria = session.createCriteria(BTerminal.class);

但是,如果没有 hibernate.cfg.xml,它会给出 nullpointerexception。当然是因为没有注入。但是要填充这个 cfg.xml 我必须添加映射 xml 文件,这不是我喜欢的方式。那么,我可以在使用 Hibernate Criteria 的同时使用 JPA 映射吗?

我没有使用 Spring。仍然怀疑哪个更容易:写 10+ 映射 xmls 与所有属性,或了解更多关于 Spring DaoSupport,或任何其他方式。

提前致谢。

是的,它会起作用。您可以使用 JPA 注释实体,同时使用 Hibernate Criteria 而不是 JPA Criteria 来查询您的实体。

其实我已经测试过了

我的实体 class 如下所示:

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>

注意,我仍然必须列出实体 classes,但我没有使用 Hibernate 映射文件 (hbm.xml)。我认为 Hibernate 不支持实体 classes 的自动检测,就像 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