persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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="OneToOnePU" transaction-type="JTA">
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties><property name="hibernate.hbm2ddl.auto" value="create-drop"/></properties>
</persistence-unit>
</persistence>
以下是Java代码:
Order.java:
package com.cecltd.domain; import java.io.Serializable; import java.util.HashSet; import java.util.Date; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @SuppressWarnings("serial") @Entity @Table(name = "Orders") public class Order implements Serializable { private Integer orderid; private Float amount; private Set orderItems = new HashSet (); private Date createdate; @Id @GeneratedValue public Integer getOrderid() { return orderid; } public void setOrderid(Integer orderid) { this.orderid = orderid; } public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @OrderBy(value = "id ASC") public Set getOrderItems() { return orderItems; } public void setOrderItems(Set orderItems) { this.orderItems = orderItems; } @Temporal(value = TemporalType.TIMESTAMP) public Date getCreatedate() { return createdate; } public void setCreatedate(Date createdate) { this.createdate = createdate; } public void addOrderItem(OrderItem orderitem) { if (!this.orderItems.contains(orderitem)) { this.orderItems.add(orderitem); orderitem.setOrder(this); } } public void removeOrderItem(OrderItem orderitem) { orderitem.setOrder(null); this.orderItems.remove(orderitem); } }
OrderItem.java:
package com.cecltd.domain; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @SuppressWarnings("serial") @Entity @Table(name = "OrderItems") public class OrderItem implements Serializable { private Integer id; private String productname; private Float price; private Order order; public OrderItem() { } public OrderItem(String productname, Float price) { this.productname = productname; this.price = price; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProductname() { return productname; } public void setProductname(String productname) { this.productname = productname; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } @ManyToOne(cascade=CascadeType.REFRESH,optional=false) @JoinColumn(name = "order_id") public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
OrderDAO.java:
package com.cecltd.ejb3; import java.util.List; import com.cecltd.domain.Order; public interface OrderDAO { public void insertOrder(); public Order getOrderByID(Integer orderid); public List getAllOrder(); }
OrderDAOBean.java:
package com.cecltd.ejb3.impl; import java.util.Date; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.cecltd.domain.Order; import com.cecltd.domain.OrderItem; import com.cecltd.ejb3.OrderDAO; @Stateless @Remote ({OrderDAO.class}) public class OrderDAOBean implements OrderDAO { @PersistenceContext protected EntityManager em; public void insertOrder(){ Order order = new Order(); order.setCreatedate(new Date()); order.addOrderItem(new OrderItem("笔记本电脑", new Float(13200.5))); order.addOrderItem(new OrderItem("U盘", new Float(620))); order.setAmount(new Float(13200.5+620)); em.persist(order); } public Order getOrderByID(Integer orderid) { Order order = em.find(Order.class, orderid); order.getOrderItems().size(); //因为是延迟加载,通过执行size()这种方式获取订单下的所有订单项 return order; } public List getAllOrder() { Query query = em.createQuery("select DISTINCT o from Order o inner join fetch o.orderItems order by o.orderid"); List result = query.getResultList(); return result; } }
测试代码:
OneToManyClient.java:
package test;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.cecltd.domain.Order;
import com.cecltd.domain.OrderItem;
import com.cecltd.ejb3.OrderDAO;
public class OneToManyClient {
public static void main(String[] args) throws NamingException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "127.0.0.1:1099");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
InitialContext ctx = new InitialContext(props);
try {
OrderDAO orderdao = (OrderDAO) ctx.lookup("OrderDAOBean/remote");
orderdao.insertOrder();
List list = orderdao.getAllOrder();
if (list!=null){
for(int k=0; k<list.size();k++){
Order od = (Order) list.get(k);
if (od!=null){
System.out.println("==============订单号:"+ od.getOrderid() +"=================");
Iterator iterator = od.getOrderItems().iterator();
while (iterator.hasNext()){
OrderItem SubOrder = (OrderItem) iterator.next();
System.out.println("订购产品:"+ SubOrder.getProductname());
}
}
}
}else{
System.out.println("获取不到订单列表");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}