/*****************************************
*Author:Java619
*Time:2007-06-02
*******************************************/
JPA(Java Persistence API)是EJB 3.0(Enterprise JavaBean 3.0)规范的重要组成
部分,它是基于POJO的标准化O/R Mapping(对象关系映射)技术。JPA为Java开发者们在管理
关系型数据库方面提供了一种对象--关系映射技术。
JPA主要包含以下三个方面:
Java持久化编程接口
Java持久化查询语言(JPA-QL)
对象/关系映射元数据
实体(Entities)
实体是一轻量级持久化域对象。典型地一个实体代表关系型数据库中的一个表,而实体的每个
实例就代表者表中的行(或记录)。实体的主要编程架构是实体类,尽管它还可以有其他帮助类。
一个实体的持久化状态既可以通过持久域(persistent fields)实现也可以通过持久属性(persistent properties)
实现。这些持久域或持久属性用对象/关系映射元注释(annotation)把实体及实体间的关系映射到底
层的数据库。
管理实体(Managing Entities)
实体由实体管理器管理。实体管理器是javax.persistence.EntityManager的实例。每个实体管理器
都跟一个持久性(persistence context)上下文关联。持久性上下文定义了具体实体创建、持久化、删除
的范围。
下面介绍JPA在J2SE中的应用(采用ANT构建)
目录结构如下
jpademo1
|-src
|-META-INF
|-persistence.xml
|-org
|-jceun
|-model
Book.java
|-test
|-org
|-jceun
|-test
BookTest.java
|-lib
mysql-connector-java-5.0.4-bin.jar
toplink-esstential.jar
toplink-esstential-agent.jar
junit.jar
|-build
|-prod
|-META-INF
|-persistence.xml
|-org
|-jceun
|-model
Book.class
|-test
|-org
|-jceun
|-test
BookTest.class
build.xml
build.xml文件内容如下
<?xml version="1.0" encoding="UTF-8"?>
<project name="JpaApp1" default="compile" basedir=".">
<description>Builds, tests, and runs the project JpaApp1.</description>
<property name="src.dir" value="src"/>
<property name="test.dir" value="test"/>
<property name="lib.dir" value="lib"/>
<property name="build.dir" value="build"/>
<property name="build.prod.dir" value="${build.dir}/prod"/>
<property name="build.test.dir" value="${build.dir}/test"/>
<path id="project.classpath">
<pathelement location="${build.prod.dir}"/>
<pathelement location="${build.test.dir}"/>
<fileset dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<target name="prepare">
<mkdir dir="${build.dir}"/>
<mkdir dir="${build.prod.dir}"/>
<mkdir dir="${build.test.dir}"/>
</target>
<target name="compile" depends="prepare">
<javac srcdir="${src.dir}" destdir="${build.prod.dir}">
<classpath refid="project.classpath"/>
</javac>
<copy todir="${build.prod.dir}" filtering="on">
<fileset dir="${src.dir}" excludes="**/*.java"/>
</copy>
</target>
<target name="compile-test" depends="compile">
<javac srcdir="${test.dir}" destdir="${build.test.dir}">
<classpath refid="project.classpath"/>
</javac>
</target>
<target name="test" depends="compile-test">
<junit haltonfailure="true">
<classpath refid="project.classpath"/>
<formatter type="brief" usefile="false"/>
<batchtest>
<fileset dir="${build.test.dir}">
<include name="**/*Test.class"/>
</fileset>
</batchtest>
</junit>
</target>
<target name="clean">
<delete dir="${build.dir}"/>
</target>
</project>
用到的类库
mysql-connector-java-5.0.4-bin.jar
toplink-esstential.jar
toplink-esstential-agent.jar
1 实体类(Book)
/*
* Book.java
*
* Created on 2007年6月2日, 下午9:24
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.jceun.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 实体类 Book
*
* @author ceun
*/
@Entity
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String bookName;
private String description;
private int price;
/** Creates a new instance of Book */
public Book() {
}
/**
* 获取此 Book 的 id。
* @return id
*/
public Long getId() {
return this.id;
}
/**
* 将此 Book 的 id 设置为指定的值。
* @param id,新建 id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 返回对象的散列代码值。该实现根据此对象
* 中 id 字段计算散列代码值。
* @return 此对象的散列代码值。
*/
@Override
public int hashCode() {
int hash = 0;
hash += (this.getId() != null ? this.getId().hashCode() : 0);
return hash;
}
/**
* 确定其他对象是否等于此 Book。当且仅当
* 参数不为 null 且该参数是具有与此对象相同 id 字段值的 Book 对象时,
* 结果才为 <code>true</code>。
* @param 对象,要比较的引用对象
* 如果此对象与参数相同,则 @return <code>true</code>;
* 否则为 <code>false</code>。
*/
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Book)) {
return false;
}
Book other = (Book)object;
if (this.getId() != other.getId() && (this.getId() == null || !this.getId().equals(other.getId()))) return false;
return true;
}
/**
* 返回对象的字符串表示法。该实现根据 id 字段
* 构造此表示法。
* @return 对象的字符串表示法。
*/
@Override
public String toString() {
return "org.jceun.model.Book[id=" + getId() + "]";
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
2 配置文件--persistence.xml(保存于META-INF目录下)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="JpaApp1PU" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<class>org.jceun.model.Book</class>
<properties>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.password" value="ceun619"/>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost/jpademo"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.logging.level" value="WARNING"/>
<property name="toplink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
3 测试类
/*
* BookTest.java
* JUnit based test
*
* Created on 2007年6月2日, 下午9:26
*/
package org.jceun.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import junit.framework.TestCase;
import org.jceun.model.Book;
/**
*
* @author ceun
*/
public class BookTest extends TestCase {
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
}
public void testAddBook(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("JpaApp1PU");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
Book book=new Book();
book.setBookName("Hello JPA");
book.setDescription("Good Book!");
book.setPrice(25);
em.persist(book);
em.getTransaction().commit();
}
public void testUpdateBook(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("JpaApp1PU");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
Book book=em.find(Book.class,new Long(51));//第二个参数为实体主键,要修改下
book.setPrice(65);
em.merge(book);
em.getTransaction().commit();
}
public void testRemoveBook(){
EntityManagerFactory emf=Persistence.createEntityManagerFactory("JpaApp1PU");
EntityManager em=emf.createEntityManager();
em.getTransaction().begin();
Book book=em.find(Book.class,new Long(101));//第二个参数为实体主键,要修改下
em.remove(book);
em.getTransaction().commit();
}
}
从命令行进入应用目录,运行 ant test 运行测试