JPA(二):HellWord工程
使用JPA持久化對象的操作步驟:
1)創建persistence.xml,在這個文件中配置持久化單元:
--- 需要指定跟哪個數據庫進行交互;
--- 需要指定JPA使用哪個持久化的框架以及配置該框架的基本屬性。
2)創建實體類,使用annotation來描述實體類跟數據庫表之間的映射關系。
3)使用JPA API完成數據增加、刪除、修改和查詢擦操作:
--- 創建EntityManagerFactory(對應hibernate中的SessionFactory)
--- 創建EntityManager(對應hibernate中的Session)
4)JPA規範要求在類路徑的MATA-INF目錄下放置persistence.xml,文件的名字是固定的。
演示HelloWord工程:
1)創建jpa project
之後點擊“Finish”按鈕完成工程創建。
工程創建好後,會發現在src下的META-INF文件夾下包含一個persistence.xml文件,該文件是用來配置jpa相關信息的。
2)導入依賴包:
a、從hibernate官網下載hibernate開發包:hibernate-release-5.3.0.Final.zip,把解壓後的文件中的數據拷貝到工程下新建的lib文件夾中:
備註:把上圖中選中的兩個文件夾下的所有包拷貝到lib中
b、導入mysql驅動包:
c、右鍵lib文件夾下所有jar文件,彈出菜單中選擇Build Path-> Add to Build Path
3)在src下添加Person實體類
package com.dxsoft.jpa.helloword; 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(name= "jpa_person") public class Person { private Integer id; private String fullName; private int age; public Person() { } @GeneratedValue(strategy = GenerationType.AUTO) @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name = "full_name") public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [id=" + id + ", fullName=" + fullName + ", age=" + age + "]"; } }
備註:
1)@Id註解為唯一主鍵;
2)@GeneratedValue(strategy = GenerationType.AUTO)註解自增,並制定自增方式。JPA提供了四種主鍵生成策略,其被定義在枚舉類GenerationType中,包括GenerationType.TABLE,GenerationType.SEQUENCE,GenerationType.IDENTITY和GenerationType.AUTO;
3)@Column(name="")可以重新定義數據庫對應字段的名字,如果類中定義屬性字段和數據不一樣時需要定義,否則可省略。
4)修改persistence.xml配置內容
<?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="Jpa-helloword" transaction-type="RESOURCE_LOCAL"> <!-- 配置使用什麽 ORM 產品來作為 JPA 的實現 --> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <!-- 添加持久化類 --> <class>com.dxsoft.jpa.helloword.Person</class> <properties> <!-- 數據庫的相關配置 --> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/jpa" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="root" /> <!-- 指定方言 MySQL org.hibernate.dialect.MySQLDialect MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect MySQL5 org.hibernate.dialect.MySQL5Dialect MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect --> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <!-- create :每次加載hibernate時都會刪除上一次的生成的表,然後根據你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致數據庫表數據丟失的一個重要原因。<br> create-drop :每次加載hibernate時根據model類生成表,但是sessionFactory一關閉,表就自動刪除。<br> update :最常用的屬性,第一次加載hibernate時根據model類會自動建立起表的結構(前提是先建立好數據庫),以後加載hibernate時根據 model類自動更新表結構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要註意的是當部署到服務器後,表結構是不會被馬上建立起來的,是要等 應用第一次運行起來後才會。<br> validate :每次加載hibernate時,驗證創建數據庫表結構,只會和數據庫中的表進行比較,不會創建新表,但是會插入新值。 <br> --> <property name="hibernate.hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence>
5)添加測試類:
package com.dxsoft.jpa.helloword; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class Client { public static void main(String[] args) { // 1.創建EntityManagerFactory String persistenceUnitName = "Jpa-helloword"; EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName); // 2.創建EntityManager EntityManager entityManager = entityManagerFactory.createEntityManager(); // 3.開始事務 EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin(); // 4.進行持久化操作 Person person = new Person(); person.setAge(31); person.setFullName("tommmy duan"); entityManager.persist(person); // 5.提交事務 entityTransaction.commit(); // 6.關閉EntityManager entityManager.close(); // 7.關閉EnityManagerFactory entityManagerFactory.close(); System.out.println("complete.."); } }
執行打印信息如下:
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@1950e8a6] for (non-JTA) DDL execution was not in auto-commit mode; the Connection ‘local transaction‘ will be committed and the Connection will be set into auto-commit mode. Hibernate: create table hibernate_sequence ( next_val bigint ) engine=InnoDB Hibernate: insert into hibernate_sequence values ( 1 ) Hibernate: create table jpa_person ( id integer not null, age integer not null, full_name varchar(255), primary key (id) ) engine=InnoDB Wed May 23 15:41:34 CST 2018 WARN: Establishing SSL connection without server‘s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn‘t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false‘. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Hibernate: select next_val as id_val from hibernate_sequence for update Hibernate: update hibernate_sequence set next_val= ? where next_val=? Hibernate: insert into jpa_person (age, full_name, id) values (?, ?, ?) 五月 23, 2018 3:41:34 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/jpa] complete..
JPA(二):HellWord工程