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