如果使用JPA的目的只是利用Annotation的特性取代XML映射配置文件,并且你也不想使用JPA的编程接口或查询语言,想使用hibernate和HQL,只需在hibernate.cfg.xml中的<mapping class=""/> 注意这里的属性是class,不是resource(引用类路径上的资源配置文件xml)。同时用AnnotationConfiguration替代原来的Configuration来buildSessionFactory。
也可以使用原生的JPA编程接口,hibernate EntityManager提供了实现。
JPA基本配置:src/META-INF/persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="persistUnitName" transaction-type="RESOURCE_LOCAL">
<class>org.hibernate.ejb.HibernatePersistence</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="××××"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/jpadb"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
一个HSQL的配置
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="jpatest"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>com.lephix.entity.Car</class> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" /> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" /> <property name="hibernate.connection.username" value="sa" /> <property name="hibernate.connection.password" value="" /> <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost" /> <property name="hibernate.max_fetch_depth" value="1" /> <property name="hibernate.hbm2ddl.auto" value="update" /> <!-- 调整JDBC抓取数量的大小: Statement.setFetchSize() --> <property name="hibernate.jdbc.fetch_size" value="18" /> <!-- 调整JDBC批量更新数量 --> <property name="hibernate.jdbc.batch_size" value="10" /> <!-- 显示最终执行的SQL --> <property name="hibernate.show_sql" value="true" /> <!-- 格式化显示的SQL --> <property name="hibernate.format_sql" value="true" /> </properties> </persistence-unit> </persistence>
或则引用hibernate.cfg.xml
<persistence-unit name="persistUnitName">
<properties>
<property name="hibernate.ejb.cfgfile" value="hibernate.cfg.xml"/>
</properties>
</persistence-unit>
本文介绍如何将Java持久化API (JPA) 与 Hibernate 框架进行整合配置,包括使用注解而非XML映射文件的方式,以及具体的配置示例。文中详细解释了如何在 persistence.xml 文件中配置 JPA 和 Hibernate 的属性,如数据库连接参数、缓存设置等。
223

被折叠的 条评论
为什么被折叠?



