EJB3.0里实体bean的复合主键

阅读更多

EJB3.0里实体bean的复合主键需要定义一个主键类。

 

部分代码如下:

 

// 主键类

@SuppressWarnings("serial")
public class OrderItemKey implements Serializable {

	private Integer orderId;
	private int itemId;
	
	public Integer getOrderId() {
		return orderId;
	}
	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}
	public int getItemId() {
		return itemId;
	}
	public void setItemId(int itemId) {
		this.itemId = 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 OrderItemKey)) {
	            return false;
	        }

	        OrderItemKey other = (OrderItemKey) otherOb;

	        return (((this.getOrderId() == null) ? (other.getOrderId() == null)
	                                             : this.getOrderId()
	                                                   .equals(other.getOrderId()))
	        && (this.getItemId() == other.getItemId()));
	    }

	    public String toString() {
	        return "" + getOrderId() + "-" + getItemId();
	    }
	
}

 

// 实体类

@SuppressWarnings("serial")
@Entity
@Table(name="orderitem")
@IdClass(OrderItemKey.class) // 声明主键类
public class OrderItem implements Serializable {
	
	private Integer orderId;
	private int itemId;
	private int quantity;
	
	private VendorPart vendorPart;
	private MyOrder order;
	
	@Id
	@Column(name="orderid",nullable=false,insertable=false,updatable=false)
	public Integer getOrderId() {
		return orderId;
	}

	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}

	@Id
	@Column(name="itemid")
	public int getItemId() {
		return itemId;
	}

	public void setItemId(int itemId) {
		this.itemId = itemId;
	}
}

 

利用 find() 等查询该实体时也需要用主键类对象作为参数

如:

		OrderItemKey itemKey = new OrderItemKey();
		itemKey.setOrderId(1);
		itemKey.setItemId(1);
		OrderItem oi2 = em.find(OrderItem.class, itemKey);
 

 

 

 

 

你可能感兴趣的:(Bean)