一、关于JPA
关于JPA是什么,在这里不做解释,感兴趣的话可以参照:
http://blog.csdn.net/chjttony/article/details/6086298
http://www.cnblogs.com/holbrook/archive/2012/12/30/2839842.html
二、首先而且必要的事搭建JPA环境
1.千里之行始于jar包
2.配置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="JPA002" transaction-type="RESOURCE_LOCAL">
<class>com.tan.jpa.bean.Person</class>
<class>com.tan.jpa.bean.Customer</class>
<class>com.tan.jpa.bean.Order</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql:///tan " />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="123456" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
3.新建各种Bean
Person实体:
/*
* Creation : 2015年3月25日
*/
package com.tan.jpa.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "name", length = 10, nullable = false)
private String name;
@Temporal(TemporalType.DATE)
// 指定为日期类型
private Date birth;
@Lob
// 指定为处理大文本或二进制数据的映射注解
private String info;
public Person() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Person(String name, Date birth, String info) {
super();
this.name = name;
this.birth = birth;
this.info = info;
}
public Person(String name, String info) {
super();
this.name = name;
this.info = info;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", birth=" + birth + ", info=" + info + "]";
}
}
Customer实体:
/*
* Creation : 2015年3月26日
*/
package com.tan.jpa.bean;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Table(name = "customer")
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "Last_Name")
private String lastName;
@OneToMany(mappedBy = "customer")
private Set<Order> orders = new HashSet<Order>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
Order实体:
/*
* Creation : 2015年3月26日
*/
package com.tan.jpa.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Table(name = "orders")
@Entity
public class Order {
@Id
@GeneratedValue
private Integer id;
@Column(name = "ORDER_NAME")
private String orderName;
@JoinColumn(name = "CUST_ID")
@ManyToOne
private Customer customer;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
4.开始测试吧,从前往后依次渐入
/*
* Creation : 2015年3月26日
*/
package com.jpa.test;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.tan.jpa.bean.Customer;
import com.tan.jpa.bean.Order;
import com.tan.jpa.bean.Person;
public class JPATest {
public EntityManagerFactory factory = null;
public EntityManager em = null;
@Before
public void init() {
factory = Persistence.createEntityManagerFactory("JPA002");
em = factory.createEntityManager();
em.getTransaction().begin();
}
@After
public void close() {
em.getTransaction().commit();
em.close();
factory.close();
}
// 数据的持久化
@Test
public void save() {
em.persist(new Person("ccc", new Date(), "ccc"));
System.out.println(" insert data success!");
}
@Test
public void find() {
// find - get
// getReference - load
Person p2 = em.find(Person.class, 2);
Person p1 = em.getReference(Person.class, 1);
System.out.println(p1);
System.out.println(p2);
// Person [id=1, name=tzq, birth=2015-03-26, info=123]
// Person [id=2, name=tan, birth=2015-03-26, info=tanzhengqiang]
}
/*
* merge和saveOrUpdate区别: saveOrUpdate后的对象会纳入session的管理,对象的状态会跟数据库同步,再次查询该对象会直接从session中取, merge后的对 象不会纳入session的管理,再次查询该对象还是会从数据库中取。
*/
@Test
public void update() {
Person person = em.find(Person.class, 5);
System.out.println(person);
person.setName("ddd");
person.setInfo("update");
Person person2 = em.merge(person);
System.out.println("update success !");
System.out.println(person.getId() == person2.getId()); // true
}
@Test
public void delete() {
em.remove(em.find(Person.class, 7));
System.out.println("delete success !");
}
@Test
// ×
public void testmerge() {
Person p = new Person();
p.setId(6);
p.setName("xiaoming");
p.setBirth(new Date());
p.setInfo("java developer");
// 无法从临时状态中获取对应的记录,报告:空指针异常 ×
Person p2 = em.find(Person.class, 6);
System.out.println(p2.getName());
em.merge(p);
System.out.println(p2.getName());
System.out.println(p == p2);
}
@Test
public void testmerge2() {
Person p = new Person();
p.setId(6);
p.setName("xiaoming");
p.setBirth(new Date());
p.setInfo("java developer");
Person p2 = em.merge(p);
System.out.println(p == p2); // false
}
/*
* 一对多:有
*/
@Test
public void testOneToMany() {
Customer customer = new Customer();
customer.setLastName("cust1");
Order order1 = new Order();
order1.setOrderName("order1");
Order order2 = new Order();
order2.setOrderName("order2");
order1.setCustomer(customer);
order2.setCustomer(customer);
customer.getOrders().add(order1);
customer.getOrders().add(order2);
em.persist(customer);
em.persist(order1);
em.persist(order2);
}
/**
* jpql测试
*/
@Test
public void testJPQL() {
// 注意JPQL操作的事对象,莫不可以将Person写成表中的person
String jpql = "SELECT p FROM Person p WHERE p.name LIKE ?1";
Query query = em.createQuery(jpql);
query.setParameter(1, "%t%");
List<Person> stus = query.getResultList();
System.out.println(stus);
// [Person [id=1, name=tzq, birth=2015-03-26, info=123], Person [id=2, name=tan, birth=2015-03-26, info=tanzhengqiang]]
}
/*
* 查询部分属性
*/
@Test
public void testPartlyProperties() {
String jpql = "SELECT new Person( p.name,p.info) FROM Person p";
Query query = em.createQuery(jpql);
List<Person> stus = query.getResultList();
for (Person p : stus) {
System.out.println(p.getName());
}
}
/*
* 设置命名参数/查询ID>1的所有对象 共有6个,大于1的有5个
*/
@Test
public void testNamedParameter() {
String jpql = "SELECT new Person( p.name,p.info) FROM Person p WHERE p.id>:id";
Query query = em.createQuery(jpql).setParameter("id", 1);
List stus = query.getResultList();
System.out.println(stus.size());// 5
}
/*
* 子查询
*/
@Test
public void testSubQuery() {
String jpql = "SELECT s FROM Person s WHERE s.id = (SELECT min(p.id) FROM Person p)";
Query query = em.createQuery(jpql);
Person person = (Person) query.getSingleResult();
System.out.println(person.getName());// tzq
}
}
好了,大概的内容就是这样,不过一般会和Spring/SpringData进行集成,这样它的优越性更加明细。下一节将探讨和springData集成示例,欢迎板砖飞来~~