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



我使用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标准时使用JPA映射吗?

我不使用Spring。还是不知道哪一种更容易:编写10多个包含所有属性的映射xml,还是学习更多关于Spring DaoSupport的知识,或者任何其他方法。

是的,它会工作。当您使用Hibernate标准来查询您的实体而不是JPA标准时,您可以拥有JPA注释实体。

我实际上已经测试过了。

我的实体类看起来像这样:

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标准检索:

    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

最新更新