是的,它會工作。您可以使用JPA標註實體,而使用Hibernate標準來查詢您的實體,而不是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
來源
2015-10-16 11:47:09
Ish
我想這和它給這樣的:在線程/ R/n'Exception「主」 org.hibernate.HibernateException:當「hibernate.dialect」沒有設置 連接不能爲空\t在org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97) \t在org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67) \t at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:174)' – FaithReaper
它正在工作,因爲我使用正確的方式在Hibernate 4.3.11中加載'hibernate.cfg.xml'。謝謝。其實我發現我的問題更多地涉及到「如何閱讀hibernate.cfg.xml以使Hibernate Criteria正常工作」。我在這裏留下了更多相關的[鏈接](http://stackoverflow.com/questions/7986750/create-session-factory-in-hibernate-4),以便有人找到我的答案。 – FaithReaper