1. 創建Maven項目,並導入開發所需的jar包 pom.xml: <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.hibernate.version>5.0.7.Fi ...
1. 創建Maven項目,並導入開發所需的jar包
pom.xml:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.hibernate.version>5.0.7.Final</project.hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${project.hibernate.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
2.編寫JPA配置文件
JPA的配置文件的路徑必須為 資源文件夾 下的 META-INF 下的 persistence.xml
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<!--
持久化單元
name:持久化單元名稱
transaction-type:事務的管理方式
JTA:分散式
RESOURCE_LOCAL:本地事務管理
-->
<persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
<!-- JPA的實現方式 -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- 資料庫的信息 -->
<properties>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa"/>
<!-- 可選配置:配置JPA實現方式配置信息 -->
<!-- 是否顯示sql -->
<property name="hibernate.show.sql" value="true"/>
<!-- 是否自動創建資料庫表 -->
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
創建persistence.xml的便捷方式:
右擊META-INF-->New-->Edit File Templates-->Other-->JPA-->Deployment descriptors-->persistence_2_0.xml