1. 程式人生 > 實用技巧 >JPA配置檔案persistence.xml及相關依賴

JPA配置檔案persistence.xml及相關依賴

JPA的配置檔案要放在類路徑下的META-INF下,預設命名為persistence.xml。

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <!--
        transaction-type有兩個取值:
                            RESOURCE_LOCAL:本地事務管理,當只用一個數據庫時選擇這個
                            JTA:分散式事務管理,當資料庫採用分散式時使用
    
--> <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="123456"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value
="jdbc:mysql://localhost:3306/jpa"/> <!--配置jpa實現方(hibernate)的配置資訊--> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>

相關maven依賴:

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.7.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.0.7.Final</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>