首页 > 代码库 > JPA开发入门实例

JPA开发入门实例

一. 什么是JPA

JPA是sun官方提出的Java持久化规范, 它为Java开发人员提供了一种对象/关系映射工具来管理Java应用中的关系数据, 

它的出现主要是为了简化现有的持久化开发工作和整合ORM技术.


JPA总体思想和现有的Hibernate、TopLink等ORM框架大体一致. 总的来说, JPA包括以下3方面的技术:

1. ORM映射元数据(JPA支持XML和注解两种元数据的形式) - 元数据描述对象和表之间的映射关系.

2. Java持久化API: 用来操作实体对象, 执行CRUD操作,框架在后台替我们完成所有的事情, 开发者可以从繁琐的JDBC和SQL代码中解脱出来.

3. 查询语句: 通过面向对象而非面向数据库的查询语句查询数据, 避免程序和SQL语句紧密耦合.


二. JPA实例:

1. 代码结构图:



2. 配置persistence.xml

<?xml version="1.0"?>
<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/persistence 
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
   <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
   	  <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <properties>
         <property name="hibernate.dialect" value=http://www.mamicode.com/"org.hibernate.dialect.MySQL5Dialect"/>>

JPA规范要求在类路径的META-INF目录下放置persistence.xml,文件的名称是固定的


3. 实体类

(1) Person:

@Entity
@Table(name = "person")
public class Person {
	private Integer id;
	private String name;
	private Date birthday;
	private Gender gender = Gender.MAN;
	private String info;
	private Byte[] file;
	private String imagepath;

	public Person() {
	}

	public Person(String name, Date d) {
		this.name = name;
		this.birthday = d;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(length = 20, nullable = false, name = "personName")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Temporal(TemporalType.DATE)
	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Enumerated(EnumType.STRING)
	@Column(length = 5, nullable = false)
	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	@Lob
	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	@Lob
	@Basic(fetch = FetchType.LAZY)
	public Byte[] getFile() {
		return file;
	}

	public void setFile(Byte[] file) {
		this.file = file;
	}

	@Transient
	public String getImagepath() {
		return imagepath;
	}

	public void setImagepath(String imagepath) {
		this.imagepath = imagepath;
	}
}


(2) Gender

public enum Gender {
	MAN, WOMAN
}

4. 测试代码

public class PersonTest {
	private static EntityManager em;
	private static EntityManagerFactory factory;

	@BeforeClass
	public static void before() throws Exception {
		factory = Persistence.createEntityManagerFactory("test");
		em = factory.createEntityManager();
	}
	
	@AfterClass
	public static void after() throws Exception {
		em.close();
		factory.close();
	}

	@Test
	public void save() {
		em.getTransaction().begin();
		em.persist(new Person("wangwu", new Date()));
		em.getTransaction().commit();
	}

	@Test
	public void getPerson1() {
		Person person = em.find(Person.class, 1); // get()
		System.out.println(person.getName());
	}

	@Test
	public void getPerson2() {
		Person person = em.getReference(Person.class, 2); // load()
		System.out.println(person.getName());
	}

	@Test
	public void updatePerson1() {
		em.getTransaction().begin();
		Person person = em.find(Person.class, 1);
		person.setName("老张");
		em.getTransaction().commit();
	}

	@Test
	public void updatePerson2() {
		em.getTransaction().begin();
		Person person = em.find(Person.class, 1);
		em.clear(); // 把实体变成游离状态
		person.setName("老王");
		em.merge(person); // 用于把游离状态的对象更新同步到数据库
		em.getTransaction().commit();
	}

	@Test
	public void delete() {
		em.getTransaction().begin();
		Person person = em.find(Person.class, 1);
		em.remove(person); // 把托管状态的实体删掉
		em.getTransaction().commit();
	}

	@Test
	public void query() {
		Query query = em.createQuery("select o from Person o where o.id=?1");
		query.setParameter(1, 2);
		Person person = (Person) query.getSingleResult();
		System.out.println(person.getName());
	}

	@Test
	public void deletequery() {
		em.getTransaction().begin();
		Query query = em.createQuery("delete from Person o where o.id=?1");
		query.setParameter(1, 2); // id为2的删除
		query.executeUpdate();
		em.getTransaction().commit();
	}

	@Test
	public void updatequery() {
		em.getTransaction().begin();
		Query query = em.createQuery("update Person o set o.name=:name where o.id=:id");
		query.setParameter("name", "xxx");
		query.setParameter("id", 3);
		query.executeUpdate();
		em.getTransaction().commit();
	}
}

三. 总结:

JPA不是一种新的ORM框架,他的出现只是用于规范现有的ORM技术,他不能取代现有的Hibernate、TopLink等ORM框架。相反,在采用JPA开发时,我们仍将使用到这些ORM框架,只是此时开发出来的应用不再依赖于某个持久化提供商。应用可以在不修改代码的情况下在任何JPA环境下运行,真正做到低耦合,可扩展的程序设计。



JPA开发入门实例