jpa学习1---jpa入门
1.目标:搭建jpa连接数据库,进行crud系列操作
2.工程结构图:
3.新建java工程,引入jar包,在META-INF下新建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.zl.jpa.main.Customer</class>
<!--
<class>com.zl.jpa.main.Order</class>
<class>com.zl.jpa.main.Department</class>
<class>com.zl.jpa.main.Manager</class>
<class>com.zl.jpa.main.Item</class>
<class>com.zl.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:///spring"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="tiger"/>
<!-- 配置 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>
4.新建entity类:
package com.zl.jpa.main;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
/**
*
* @author zenglong
*
* @Description:实体类
*/
@Cacheable(true)
@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;
}
private Set<Order> orders = new HashSet<>();
// @TableGenerator(name="ID_GENERATOR",
// table="jpa_id_generators",
// pkColumnName="PK_NAME",
// pkColumnValue="CUSTOMER_ID",
// valueColumnName="PK_VALUE",
// allocationSize=100)
// @GeneratedValue(strategy=GenerationType.TABLE,generator="ID_GENERATOR")
@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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Temporal(TemporalType.TIMESTAMP)
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;
}
//映射单向 1-n 的关联关系
//使用 @OneToMany 来映射 1-n 的关联关系
//使用 @JoinColumn 来映射外键列的名称
//可以使用 @OneToMany 的 fetch 属性来修改默认的加载策略
//可以通过 @OneToMany 的 cascade 属性来修改默认的删除策略.
//注意: 若在 1 的一端的 @OneToMany 中使用 mappedBy 属性, 则 @OneToMany 端就不能再使用 @JoinColumn 属性了.
// @JoinColumn(name="CUSTOMER_ID")
@OneToMany(fetch=FetchType.LAZY,cascade={CascadeType.REMOVE},mappedBy="customer")
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
//工具方法. 不需要映射为数据表的一列.
@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 + "]";
}
}
5.测试main类:
package com.zl.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);
//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();
}
}
这里是使用了事务保存。
=============================API==================================
1.查找
//类似于 hibernate 中 Session 的 get 方法.
@Test
public void testFind() {
Customer customer = entityManager.find(Customer.class, 1);
System.out.println("----------------到数据库中把全部查出来---------------------");
System.out.println(customer);
}
懒加载:
//类似于 hibernate 中 Session 的 load 方法
@Test
public void testGetReference(){
Customer customer = entityManager.getReference(Customer.class, 1);
System.out.println(customer.getClass().getName());
System.out.println("-------------------------------------");
// transaction.commit();
// entityManager.close();
System.out.println(customer);
}
2.保存:
//类似于 hibernate 的 save 方法. 使对象由临时状态变为持久化状态.
//和 hibernate 的 save 方法的不同之处: 若对象有 id, 则不能执行 insert 操作, 而会抛出异常.
//和 hibernate 的 save 方法的不同之处: 若对象有 id, 则不能执行 insert 操作, 而会抛出异常.
@Test
public void testPersistence(){
Customer customer = new Customer();
customer.setAge(15);
customer.setBirth(new Date());
customer.setCreatedTime(new Date());
customer.setEmail("bb@163.com");
customer.setLastName("BB");
customer.setId(100);
entityManager.persist(customer);
System.out.println(customer.getId());
}
3.删除:
//类似于 hibernate 中 Session 的 delete 方法. 把对象对应的记录从数据库中移除
//但注意: 该方法只能移除 持久化 对象. 而 hibernate 的 delete 方法实际上还可以移除 游离对象.
@Test
public void testRemove(){
// Customer customer = new Customer();
// customer.setId(2);
Customer customer = entityManager.find(Customer.class, 2);
entityManager.remove(customer);
}