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-1" transaction-type="RESOURCE_LOCAL"> <!-- 配置使用什麼 ORM 產品來做爲 JPA 的實現 1. 實際上配置的是 javax.persistence.spi.PersistenceProvider 接口的實現類 2. 若 JPA 項目中只有一個 JPA 的實現產品, 則也能夠不配置該節點. --> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!-- 添加持久化類 --> <class>com.jpa.main.Customer</class> <class>com.jpa.main.Order</class> <class>com.jpa.main.Department</class> <class>com.jpa.main.Manager</class> <class>com.jpa.main.Item</class> <class>com.jpa.main.Category</class> <!-- 配置二級緩存的策略 ALL:全部的實體類都被緩存 NONE:全部的實體類都不被緩存. ENABLE_SELECTIVE:標識 @Cacheable(true) 註解的實體類將被緩存 DISABLE_SELECTIVE:緩存除標識 @Cacheable(false) 之外的全部實體類 UNSPECIFIED:默認值,JPA 產品默認值將被使用 --> <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode> <properties> <!-- 鏈接數據庫的基本信息 --> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///ssh01"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="wzy123"/> <!-- 配置 JPA 實現產品的基本屬性. 配置 hibernate 的基本屬性 --> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- 二級緩存相關 --> <property name="hibernate.cache.use_second_level_cache" value="true"/> <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/> <property name="hibernate.cache.use_query_cache" value="true"/> </properties> </persistence-unit> </persistence>
測試類
package com.jpa.main; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class Main { public static void main(String[] args) { //1. 建立 EntitymanagerFactory String persistenceUnitName = "jpa-1"; Map<String, Object> properites = new HashMap<String, Object>(); properites.put("hibernate.show_sql", true); EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName); //Persistence.createEntityManagerFactory(persistenceUnitName, properites); //使用這個構造器能夠添加一些屬性
//但必須是這樣的<property name="hibernate.show_sql" value="true"/>
//2. 建立 EntityManager. 相似於 Hibernate 的 SessionFactory EntityManager entityManager = entityManagerFactory.createEntityManager(); //3. 開啓事務 EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); //4. 進行持久化操做 Customer customer = new Customer(); customer.setAge(12); customer.setEmail("tom@atguigu.com"); customer.setLastName("Tom"); customer.setBirth(new Date()); customer.setCreatedTime(new Date()); entityManager.persist(customer);//保存操做 //5. 提交事務 transaction.commit(); //6. 關閉 EntityManager entityManager.close(); //7. 關閉 EntityManagerFactory entityManagerFactory.close(); } }
實體類映射
package com.jpa.main; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Basic; import javax.persistence.Cacheable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; @Table(name="JPA_CUTOMERS") @Entity public class Customer { private Integer id; private String lastName; private String email; private int age; private Date createdTime; private Date birth; public Customer() { // TODO Auto-generated constructor stub } public Customer(String lastName, int age) { super(); this.lastName = lastName; this.age = age; }// @TableGenerator(name="ID_GENERATOR", //Table主鍵生成策略,不經常使用 // table="jpa_id_generators", // pkColumnName="PK_NAME", // pkColumnValue="CUSTOMER_ID", // valueColumnName="PK_VALUE", // allocationSize=100)//id每次增加100 // @GeneratedValue(strategy=GenerationType.TABLE,generator="ID_GENERATOR") //註解通常標註在get方法上 @GeneratedValue(strategy=GenerationType.AUTO)//生成主鍵的方式 @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="LAST_NAME",length=50,nullable=false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Basic//不寫默認是這個註解,字段名就是這個名 public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Temporal(TemporalType.TIMESTAMP)//日期格式化@Temporal public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } @Temporal(TemporalType.DATE) public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } //工具方法. 不須要映射爲數據表的一列.表示這只是一個普通方法 ,和數據表字段無關 @Transient public String getInfo(){ return "lastName: " + lastName + ", email: " + email; } @Override public String toString() { return "Customer [id=" + id + ", lastName=" + lastName + ", email=" + email + ", age=" + age + ", createdTime=" + createdTime + ", birth=" + birth + "]"; } }