1. 程式人生 > >1 JPA入門----項目搭建以及CRUD

1 JPA入門----項目搭建以及CRUD

eat jpql oot code JD parent merge nec employee

maven搭建JPA開發環境 1 依賴的maven pom文件 主要有hibernate-core、hibernate-entitymanager、javax-persistence、mysql驅動
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"
> <parent> <artifactId>jap-xx</artifactId> <groupId>com.cmos</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>jpa-01</artifactId> <properties
> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <hibernate.version>4.3.8.Final</hibernate.version> <junit.version>4.12</junit.version> <java.version>1.8</java.version> </properties> <
dependencies> <!--hibernate-core--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- hibernate-entitymanager--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!--javax.persistence--> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0.2</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> </dependencies> </project>
2 配置persistence.xml文件 在資源文件夾下創建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/persistencehttp://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="com.cmos.jpa" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql:///jpa"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="gosaint"/>
            <!--mysql方言-->
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <!--顯示sql-->
            <property name="hibernate.show_sql" value="true"/>
            <!--自動建表-->
            <property name="hibernate.hbm2ddl.auto" value="create"/>
            <!--格式化sql-->
            <property name="hibernate.format_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>
3 創建實體類Employee類。 新建數據庫,名為jpa,配置好上述的persistence.xml文件;新建實體類Employee
package com.cmos.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column
    private String name;
    private String password;
    ...
    省略getter()和setter()
}

4 新建測試類EmployeeTest

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.cmos.jpa.Employee;

import org.junit.Test;

public class EmployeeTest {
    
    @Test
    public void save() throws Exception {
        Employee employee=new Employee();
        employee.setName("張三");
        employee.setPassword("123456");
        String persistenceUnitName="com.cmos.jpa";
        // 1 獲取實例管理工廠
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
        // 2 獲取實例管理對象
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        // JAP默認事務不開啟
        EntityTransaction transaction = entityManager.getTransaction();
        //3 開啟事務
        transaction.begin();
        //4 持久化操作
        entityManager.persist(employee);
        //5 提交事務
    transaction.commit();
        //6 關閉資源
        entityManager.close();
        entityManagerFactory.close();

    }
}
如下的結果顯示: 技術分享圖片 查看數據庫,發現存在測試數據! 5 註解解釋 上述的註解解釋: ① @Entity:表示實體對象,這個對象和數據庫的表建立對應關系 ② @Table(name="表名") 如果沒有配置該註解或者該註解使用默認值關系,那麽表的名稱為類名稱,首字母小寫 ③ @Id 表示主鍵 ④ @GeneratedValue 配置主鍵的生成策略,默認值是@GeneratedValue(strategy = GenerationType.AUTO) 主鍵策略如果是:strategy = GenerationType.AUTO 在Mysql中就是:主鍵:AUTO_INCREMENT,在Oracle中就是序列; 表示主鍵自動 ⑤ @Column註解:加在字段上,如果希望字段的名稱和數據庫對應的字段不一致,可以使用該註解,並且設置對應的列名;如果希望一致,可以不用加該註解 6 工具類抽取
public class JPAUtils {
    private static EntityManagerFactory entityManagerFactory;
    static {
        try {
            String persistenceUnitName="com.cmos.jpa";
            entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName);
        }catch (Exception e){
            throw new RuntimeException("配置文件出錯"+e.getMessage());
        }

    }
    public static EntityManager getEntity(){
        return entityManagerFactory.createEntityManager();
    }

    public static void close(){
        if(entityManagerFactory!=null){
            entityManagerFactory.close();
        }
    }
}
7 測試CRUD操作 補充:建表策略是create:表示先刪除表,然後建立新的表;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.cmos.jpa.Employee;
import com.cmos.jpa.JPAUtils;

import org.junit.Before;
import org.junit.Test;

/**
* 查詢一個: find(T.class,Long id)
* 修改: merge(T)
* 保存:persistence(T)
* 刪除:remove(T) 直接刪除對象
*
*/
public class EmployeeTest2 {
    /**
     * 保存
     */
    @Before
    public void save(){
        Employee employee=new Employee();
        employee.setName("張三");
        employee.setPassword("123456");
        Employee employee2=new Employee();
        employee2.setName("裏斯");
        employee2.setPassword("123456");
        EntityManager entity = JPAUtils.getEntity();
        EntityTransaction transaction = entity.getTransaction();//獲取事務
        transaction.begin();
        entity.persist(employee);
        transaction.commit();
    }
    @Test
    public void queryAndUpdate(){
        EntityManager entity = JPAUtils.getEntity();
        entity.getTransaction().begin();
        //查詢
        Employee employee = entity.find(Employee.class, 1L);
        System.out.println(employee);
        employee.setName("xyz");
        employee.setPassword("99999");
        //修改
        entity.merge(employee);
        System.out.println(employee);
        entity.getTransaction().commit();
    }

    @Test
    public void delete(){
        EntityManager entity = JPAUtils.getEntity();
        entity.getTransaction().begin();
        Employee employee = entity.find(Employee.class, 1L);
        entity.remove(employee);
        System.out.println(employee);
        entity.getTransaction().commit();
    }
   
    //JPQL查詢
    @Test
    public void queryJPQL(){
        EntityManager entity = JPAUtils.getEntity();
        entity.getTransaction().begin();
        String jpql="select o from Employee o";
        Query query = entity.createQuery(jpql);
        List<Employee> resultList = query.getResultList();
        for (Employee e:resultList) {
            System.out.println("0000000000");
            System.out.println(e);
        }
        entity.getTransaction().commit();
        
    }


}
7 配置自動建表 create-drop:刪除表----建表----刪除表(一般不用) 刪除表的時間:EntityManageFactory關閉之後 create----刪除表----建立表 update----用在項目中 validate----數據庫已經存在(項目已經上線) 總結:JPA的CRUD操作: 查詢:find或者使用JPQL查詢; 保存:persistence 修改:merge 刪除: remove

1 JPA入門----項目搭建以及CRUD