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

时间:2015-10-16 10:48:24

标签: spring hibernate annotations mapping

我正在使用JPA注释来映射模型中的实体。但是,我发现Hibernate Criteria易于使用并且包含的​​代码较少,因此有没有一种方法可以使用Criteria而不使用hibernate xml方式进行映射?我在DAO实现类中试过这个:

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或其他任何方式的更多信息。

提前致谢。

1 个答案:

答案 0 :(得分:2)

是的,它会起作用。您可以使用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
相关问题