- 浏览: 191586 次
- 性别:
- 来自: 深圳
最新评论
-
shis_y:
那是你的localhost或者web服务器的80端口被占用或者 ...
通过虚拟地址解决fckeditor错误的加载/fckeditor/fckstyles.xml -
forcer521:
com.gemt.dataswap.util.Constant ...
使用DES算法进行加密和解密 -
ngn9999:
dTree确实不错,这是我的使用经验: http://www. ...
javascript树型菜单(Dtree和Xtree) -
yueliangwolf:
这个dhtmlxtree.js里面有enableSmartXM ...
使用xml或者json方式生成dhtmlxtree -
yanMouse:
谢谢,能否有个联系方式,我现在也在看这方面的东西
dhtmlxtree的一个实用demo
JPA
JPA是JAVA EE的重要组成部分, 它不再是EJB里面的一种BEAN, 可以在一般的Servlet容器中使用, 并不一定要应用服务器的支持, 可以看
成实体BEAN的替代品. 相比实体BEAN(CMP), JPA开发开发起来更加简化, 也更加轻量级, 使用了Annotation代替了原来繁琐的XML文件的配
置, 在API方面倒是跟Hibernate非常相似.
一. persistence.xml(此文件位于MATE-INF下, 是JPA的主配置文件)
格式如下:
三. 实体管理
1. 容器管理(使用@PersistenceContext对EntityManager实行注射, 完成初始化)
@javax.persistence.PersistenceContext(unitName="persistence_sample")
private EntityManager em ;
.......................................................................
2. 应用管理的实体管理(Application-Managed Entity Managers)
此时, 由于取不到上下文的信息, 我们只能采用这种方式实现得到EntityManager
@PersistenceUnit
EntityManagerFactory emf;
然后, 从EntityManagerFactory获取一个EntityManager实例:
EntityManager em = emf.createEntityManager();
四. 实体的生命周期(四种状态)
1. new 创建
2. managed 管理
3. detached 托管
4. removed 删除
五. 实体操作
1. 实体的查找
2. 持久化实体实例(Persisting Entity Instances)
调用persist方法, 使新的实体类成为被管理的持久对象
3. 实体类中的实体关系(@OneToMany, @ManyToMany, @OneToOne, @ManytoOne)
4. 删除实体
public void removeOrder(Integer orderId) {
try {
Order order = em.find(Order.class, orderId);
em.remove(order);
}...
5. 实体的查询
1.) createQuery
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name)
.setMaxResults(10)
.getResultList();
}
2.) createNamedQuery
使用Annotation定义NamedQuery
@NamedQuery(
name="findAllCustomersWithName",
query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
@PersistenceContext
public EntityManager em;
...
customers = em.createNamedQuery("findAllCustomersWithName")
.setParameter("custName", "Smith")
.getResultList();
指定参数名字
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name)
.getResultList();
}
指定参数位置
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE ?1")
.setParameter(1, name)
.getResultList();
}
6. 用实体更新数据库记录
我们首先找到这个实体对象, 然后对它进行操作
public void buyBooks(ShoppingCart cart) throws OrderException{
Collection items = cart.getItems();
Iterator i = items.iterator();
try {
while (i.hasNext()) {
ShoppingCartItem sci = (ShoppingCartItem)i.next();
Book bd = (Book)sci.getItem();
String id = bd.getBookId();
int quantity = sci.getQuantity();
buyBook(id, quantity);
}
} catch (Exception ex) {
throw new OrderException("Commit failed: "
+ ex.getMessage());
}
}
public void buyBook(String bookId, int quantity)
throws OrderException {
try {
Book requestedBook = em.find(Book.class, bookId);
if (requestedBook != null) {
int inventory = requestedBook.getInventory();
if ((inventory - quantity) >= 0) {
int newInventory = inventory - quantity;
requestedBook.setInventory(newInventory);
} else{
throw new OrderException("Not enough of "
+ bookId + " in stock to complete order.");
}
}
} catch (Exception ex) {
throw new OrderException("Couldn't purchase book: "
+ bookId + ex.getMessage());
}
}
7. JTA事务支持
@Resource
UserTransaction utx;
...
try {
utx.begin();
bookDBAO.buyBooks(cart);
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception exe) {
System.out.println("Rollback failed: "+exe.getMessage());
}
8. 主键产生策略
1.) @Id (含有主键的表, 自己管理主键)
2.) 主键用一个专门的表产生
@TableGenerator(name="ADDRESS_ID_GEN",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="ADDRESS_ID",
allocationSize=1)
@GeneratedValue(strategy=GenerationType.TABLE,generator="ADDRESS_ID_GEN")
@Id
public String getAddressID() {
return addressID;
}
3.) 使用主键类
package order.entity;
public final class LineItemKey implements
java.io.Serializable {
private Integer orderId;
private int itemId;
public int hashCode() {
return ((this.getOrderId()==null
?0:this.getOrderId().hashCode())
^ ((int) this.getItemId()));
}
public boolean equals(Object otherOb) {
if (this == otherOb) {
return true;
}
if (!(otherOb instanceof LineItemKey)) {
return false;
}
LineItemKey other = (LineItemKey) otherOb;
return ((this.getOrderId()==null
?other.orderId==null:this.getOrderId().equals
(other.orderId)) && (this.getItemId ==
other.itemId));
}
public String toString() {
return "" + orderId + "-" + itemId;
}
}
@IdClass(order.entity.LineItemKey.class)
@Entity
...
public class LineItem {
...
}
- @PersistenceContext
- EntityManager em;
- ...
- public LineItem createLineItem(Order order, Product product,
- int quantity) {
- LineItem li = new LineItem(order, product, quantity);
- order.getLineItems().add(li);
- em.persist(li);
- return li;
- }
- <persistence>
- <persistence-unit name="OrderManagement">
- <description>This unit manages orders and customers.
- It does not rely on any vendor-specific features and can
- therefore be deployed to any persistence provider.
- description>
- <jta-data-source>jdbc/MyOrderDBjta-data-source>
- <jar-file>MyOrderApp.jarjar-file>
- <class>com.widgets.Orderclass>
- <class>com.widgets.Customerclass>
- persistence-unit>
- persistence>
- <!---->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="persistence_sample" transaction-type="JTA">
- <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProviderprovider>
- <jta-data-source>jdbc/SamplesDBjta-data-source>
- <properties>
- <property name="toplink.ddl-generation" value="drop-and-create-tables"/>
- properties>
- persistence-unit>
- persistence>
二. 实体类
使用annotation @Entity标识它是实体类
使用@Id 标识它是主键
使用@Table 标识这个实体类对应的数据库表, 如果类名跟表名相同, 则可以省略
- import java.io.Serializable;
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
- @Entity
- @Table(name="WEB_BOOKSTORE_BOOKS")
- public class Book implements Serializable {
- private String bookId;
- private String title;
- public Book() { }
- public Book(String bookId, String title, ...) {
- this.bookId = bookId;
- this.title = title;
- ...
- }
- @Id
- public String getBookId() {
- return this.bookId;
- }
- public String getTitle() {
- return this.title;
- }
- ...
- public void setBookId(String id) {
- this.bookId=id;
- }
- public void setTitle(String title) {
- this.title=title;
- }
- ...
- }
- package enterprise.customer_cmp_ejb.ejb.session;
- import javax.ejb.Stateless;
- import javax.ejb.Stateful;
- import javax.ejb.SessionContext;
- import javax.persistence.*;
- import javax.ejb.*;
- import java.util.List;
- import enterprise.customer_cmp_ejb.persistence.*;
- import enterprise.customer_cmp_ejb.common.*;
- /**
- *
- * @author Rahul Biswas
- *
- * Why a facade?
- * 1. session beans are thread safe, and EMs are not necessarily; so injecting a EM into a SessionBean makes it safe.
- * 2. Tx management is taken care of by container
- * 3. of course, because it's a facade [we can combine operations].
- *
- */
- @Stateless
- @TransactionManagement(value=TransactionManagementType.CONTAINER)
- public class CustomerSession implements CustomerSessionLocal, CustomerSessionRemote{
- @javax.persistence.PersistenceContext(unitName="persistence_sample")
- private EntityManager em ;
- public CustomerSession(){
- }
- public Customer searchForCustomer(String id){
- Customer cust = (Customer)em.find(Customer.class, id);
- return cust;
- }
- public Subscription searchForSubscription(String id){
- Subscription subscription = (Subscription)em.find(Subscription.class, id);
- return subscription;
- }
- public Address searchForAddress(String id){
- Address address = (Address)em.find(Address.class, id);
- return address;
- }
- //This is the default; here as an example of @TransactionAttribute
- @TransactionAttribute(TransactionAttributeType.REQUIRED)
- public void remove(Object obj){
- Object mergedObj = em.merge(obj);
- em.remove(mergedObj);
- }
- public void persist(Object obj){
- em.persist(obj);
- }
- public List findAllSubscriptions(){
- List subscriptions = em.createNamedQuery("findAllSubscriptions").getResultList();
- return subscriptions;
- }
- public List findCustomerByFirstName(String firstName){
- List customers = em.createNamedQuery("findCustomerByFirstName").setParameter("firstName", firstName).getResultList();
- return customers;
- }
- public List findCustomerByLastName(String lastName){
- List customers = em.createNamedQuery("findCustomerByLastName").setParameter("lastName", lastName).getResultList();
- return customers;
- }
- public Customer addCustomerAddress(Customer cust, Address address){
- Customer mergedCust = em.merge(cust);
- mergedCust.getAddresses().add(address);
- return mergedCust;
- }
- public Customer removeCustomerSubscription(String cust, String subs) throws SubscriptionNotFoundException{
- //System.out.println("called remove Customer Subscription.....");
- Customer customer = (Customer)em.find(Customer.class, cust);
- Subscription subscription = (Subscription)em.find(Subscription.class, subs);
- if(!customer.getSubscriptions().contains(subscription)){
- System.out.println("remove: did not find a subscription obj for :"+subscription.getTitle());
- throw new SubscriptionNotFoundException();
- }
- customer.getSubscriptions().remove(subscription);
- subscription.getCustomers().remove(customer);
- return customer;
- }
- public Customer addCustomerSubscription(String cust, String subs) throws DuplicateSubscriptionException{
- //System.out.println("called add Customer Subscription.....");
- Customer customer = (Customer)em.find(Customer.class, cust);
- Subscription subscription = (Subscription)em.find(Subscription.class, subs);
- if(customer.getSubscriptions().contains(subscription)){
- System.out.println("add: found an existing subscription obj for :"+subscription.getTitle());
- throw new DuplicateSubscriptionException();
- }
- customer.getSubscriptions().add(subscription);
- subscription.getCustomers().add(customer);
- return customer;
- }
- }
- @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
- @OneToMany(cascade=ALL, mappedBy="order")
- public Collection <lineitem></lineitem> getLineItems() {
- return lineItems;
- }
- @ManyToMany(fetch=FetchType.EAGER )
- @JoinTable(
- name="CUSTOMERBEANSUBSCRIPTIONBEAN",
- joinColumns=@JoinColumn(name="CUSTOMERBEAN_CUSTOMERID96", referencedColumnName="customerid"),
- inverseJoinColumns=@JoinColumn(name="SUBSCRIPTIONBEAN_TITLE", referencedColumnName="TITLE")
- )
- public Collection<subscription></subscription> getSubscriptions(){
- return subscriptions;
- }
- @OneToOne(optional=false)
- @JoinColumn(
- name="CUSTREC_ID", unique=true, nullable=false, updatable=false)
- public CustomerRecord getCustomerRecord() { return customerRecord; }
- @ManyToOne(optional=false)
- @JoinColumn(name="CUST_ID", nullable=false, updatable=false)
- public Customer getCustomer() { return customer; }
- article-JPA.rar (4.4 KB)
- 描述: text content
- 下载次数: 135
发表评论
-
kdb+/q
2008-11-28 20:13 1907因为一个项目接触了kdb+/q, kdb+/q的执行速度应该 ... -
seam随笔
2008-09-28 20:33 1208前段时间,因为客户的一个项目接触了seam,客户那边在 ... -
richfaces换肤
2008-08-27 23:18 0http://leonardinius.blogspot.co ... -
jfree chart...
2008-08-17 11:38 0see attachment. -
crystal report
2008-08-04 21:57 0crystal report http://oceang-y. ... -
js code example
2008-07-01 16:25 0<html> <body> <s ... -
dhtmlgoodies网站上的一些js,也许在工作中用得到
2008-06-23 16:28 1536到http://www.dhtmlgoodies.com ... -
Hibernate的一个例子
2008-05-31 23:32 1092通过hibernate tools的反向工程从数据库产生ent ... -
使用xml或者json方式生成dhtmlxtree
2008-05-14 18:01 68171. dao private static Paramete ... -
在cxf基础上整的一个框架
2008-04-24 08:48 1101使用cxf作为webservice的服务器,以spring b ... -
S60签名
2008-04-16 17:14 1516前段时间写了一个程序,放到S60第三版的手机系统上面老是报权限 ... -
socket消息超时重发的设想
2008-04-08 17:00 4061我们经常遇到的一个问题就是:发送一条消息,若在T秒内没有 ... -
io,nio和操作系统命令性能比较
2008-03-31 20:50 2267package org.clarance; import j ... -
要开始做一个网络的项目了
2008-03-27 22:38 1318一个在线环境监测的项目, 监控中心用java编写,接受现 ... -
使用jQuery解决portal登陆慢的问题
2007-12-19 16:58 2270因为portal中的好几块地方(portlet)取数据比较慢, ... -
使用javascript遍历XML文件并显示
2007-12-10 17:11 6682以下代码在IE和Firefox上测试通过: <html& ... -
JSON技术实战
2007-12-07 09:23 11051JSON作为一种信息的载体 ... -
使用HttpClient对web应用进行测试
2007-11-29 16:19 2959在几天程序突然报出了数据库连接被管理员销毁的情况! 一时之间也 ... -
判断日期是否有效的正则表达式
2007-09-10 17:59 1244function isValidDate(dateStr, f ... -
取oracle的error code
2007-08-30 15:39 2830有时候需要知道oracle的error code的具体含义, ...
相关推荐
Java持久化API(Java Persistence API,简称JPA)是Java平台上的一个标准,用于管理应用程序中的对象和数据库之间的关系,实现了对象关系映射(ORM)。JPA2.0是JPA的第二个主要版本,相较于1.0,它引入了许多新特性...
**Java Persistence API (JPA)** 是Java平台上的一个核心组件,它定义了应用程序与数据库之间的对象关系映射(ORM)规范。ORM允许开发者使用面向对象的编程语言来操作数据库,而不是直接编写SQL语句,从而简化了数据...
要是你对 Hibernate 或 TopLink 的 Criteria API 不熟悉的话,可以将它想像成一个以 Java 为中心的面向对象,线程安全并可以与 JPQL 划上等号的一组 API .这组 API 适合于编写复杂的动态查询语句,还可避免解析 JPQL...
### Pro JPA 2:精通Java Persistence API #### 核心知识点概览 - **Java Persistence API (JPA) 2.0**:一个用于Java应用程序的对象-关系映射(ORM)工具的标准接口。 - **新特性介绍**:包括额外的对象-关系映射...
Java持久化API(Java Persistence API,简称JPA)是Java平台上的一个标准,用于管理和持久化应用程序中的对象。它是Java Enterprise Edition(Java EE)的一部分,同时也适用于Java Standard Edition(Java SE)环境...
Java Persistence API(JPA)是一种Java持久化API,用于实现Java应用程序中的数据持久化。JPA提供了一个标准的、可移植的、基于对象关系映射(ORM)的持久化机制,允许开发者使用Java对象来操作数据库。 JPA的主要...
### Pro JPA 2: Mastering the Java Persistence API #### 关键知识点概览: 1. **JPA(Java Persistence API)概述与发展历程** 2. **JPA 2.0 新特性介绍** - 对象关系映射增强 - 对象建模灵活性提升 - 类型...
### Java Persistence API (JPA) 知识点详解 #### 一、引言与背景 在深入了解Java Persistence API (简称 JPA)之前,我们先简要回顾一下数据持久化的概念及其在Java领域的演变历程。 ##### **1.1 数据持久化** -...
### JPA(Java Persistence API) 是JavaEE5.0 平台标准的ORM规范 #### 概述 JPA(Java Persistence API)是Java EE 5.0平台中定义的标准对象关系映射(ORM)规范,它允许开发人员将应用程序中的实体对象与数据库中...
### Java Persistence API 2.0 (JPA 2.0) Final Release文档解析 #### 标题:Java Persistence API 2.0 FINAL文档 #### 描述解析:Java Persistence API(JPA)2.0规范概述 Java Persistence API (JPA) 2.0是一个...
《APress Pro EJB 3 Java Persistence API》一书由Mike Keith和Merrick Schincariol共同编写,出版于2006年,是关于Java Persistence API(JPA)与Enterprise JavaBeans(EJB)3的深入研究。本书旨在为读者提供关于...
根据提供的文件信息,我们可以推断出这本书主要关注的是EJB 3中的Java Persistence API(JPA)技术。接下来,我们将详细解析与该书标题、描述、标签及部分内容相关的知识点。 ### 一、EJB 3简介 EJB (Enterprise ...
This document is the specification of the Java API for the management of persistence and object/relational mapping with Java EE and Java SE. The technical objective of this work is to provide an ...