hibernate 一对多与多对一

来源:互联网 发布:亲哥哥 知乎 编辑:程序博客网 时间:2024/04/29 06:36
1.Customer的映射
<hibernate-mapping package="mypack">
     <class name="Customer" table="CUSTOMERS" schema="dbo" catalog="Temp" dynamic-insert="true" dynamic-update="true">
         <id name="id"><!-- 主键 -->
             <generator class="identity" /><!-- 自动增长? -->
         </id>
         <property name="name" />
         <property name="sex" access="field"/><!-- access="filed"让Hibernate 直接访问sex 而不是调getSex() -->
      
         <!-- 一对多,一个客户有多个订单 -->
         <set name="orders" inverse="true" cascade="save-update">
         <key column="CUSTOMER_ID"></key>
         <one-to-many class="mypack.Order"/>
         </set>
        
         <!-- totalPrice是派生属性,运行时才能得到 -->
         <property name="totalPrice" formula="(select sum(o.PRICE) from ORDERS o where o.CUSTOMER_ID=ID)"/>
  
   <!-- 如果一个字段中有空格要用''引起来 -->
         <property name="description" type="text" column="[CUSTOMER   DESCRIPTION]"></property>
     </class>
</hibernate-mapping>
2.Order的映射
<hibernate-mapping package="mypack">
     <class name="Order" table="ORDERS" schema="dbo" catalog="Temp" dynamic-insert="true" dynamic-update="true">
     <id name="id">
       <generator class="identity"/>
     </id>
    
     <property name="orderNumber" column="ORDER_NUMBER"/>
         <property name="price"/>
        
         <!-- 多对一,多个订单可以属于同一个人 -->
         <many-to-one
         name="customer"
         column="CUSTOMER_ID"
         class="Customer"
         not-null="true"
         />
     </class>
</hibernate-mapping>
3.Customer.java
public class Customer implements Serializable {
private Long id;
private String firstname;
private String lastname;
private char sex;
private Set orders=new HashSet();
private double avgPirce;
private double totalPrice;
private String description;//描述
public Customer() {
     }
     //在构造方法中就进行初史化
     public Customer(String firstname,String lastname,char sex,Set orders,String description){
       this.firstname=firstname;
       this.lastname=lastname;
       this.sex=sex;
       this.orders=orders;
       this.description=description;
     }
public double getAvgPirce() {
   return avgPirce;
}
public void setAvgPirce(double avgPirce) {
   this.avgPirce = avgPirce;
}
public String getDescription() {
   return description;
}
public void setDescription(String description) {
   this.description = description;
}
public String getFirstname() {
   return firstname;
}
public void setFirstname(String firstname) {
   this.firstname = firstname;
}
public Long getId() {
   return id;
}
public void setId(Long id) {
   this.id = id;
}
public String getLastname() {
   return lastname;
}
public void setLastname(String lastname) {
   this.lastname = lastname;
}
public double getTotalPrice() {
   return totalPrice;
}
public void setTotalPrice(double totalPrice) {
   this.totalPrice = totalPrice;
}
public String getName(){
   return this.firstname+" "+this.lastname;
}
public void setName(String name){
   // 将传进来的名字进行分解
   StringTokenizer st=new   StringTokenizer(name);
   this.firstname=st.nextToken();
   this.lastname=st.nextToken();
}
public Set getOrders() {
   return orders;
}
public void setOrders(Set orders) {
   this.orders = orders;
   calculatePrice();
}
public void calculatePrice(){
   double avgPrice=0.0;
   double totalPrice=0.0;
   int count=0;
  
   if(getOrders()!=null){
   Iterator iter=this.orders.iterator();
   while(iter.hasNext()){
     double orderPrice=((Order)iter.next()).getPrice();
     totalPrice +=orderPrice;
     count++;
   }
   }
   avgPrice=totalPrice/count;
   this.setAvgPirce(avgPrice);  
}
public char getSex() {
   return sex;
}
public void setSex(char sex) {
   if(sex!='男'&&sex!='女'){
   throw new IllegalArgumentException("性别错误!");  
   }
   this.sex = sex;
}
}
4.Order.java
public class Order {
     private Long id;
     private String orderNumber;
     private double price;
     private Customer customer;
    
     public Order(){
    
     }    
     public Order(String orderNumber,double price,Customer customer) {
         this.orderNumber=orderNumber;
         this.price=price;
         this.customer=customer;
     }
    
public Customer getCustomer() {
   return customer;
}
public void setCustomer(Customer customer) {
   this.customer = customer;
}
public Long getId() {
   return id;
}
public void setId(Long id) {
   this.id = id;
}
public String getOrderNumber() {
   return orderNumber;
}
public void setOrderNumber(String orderNumber) {
   this.orderNumber = orderNumber;
}
public double getPrice() {
   return price;
}
public void setPrice(double price) {
   this.price = price;
}
}
5.测试
public class BusServer {
public static SessionFactory sessionFactory;
static{
   try{
   Configuration cfg=new Configuration();  
   sessi.configure().buildSessionFactory();
      
   }catch(Exception ex){
   ex.printStackTrace();  
   }
}
//保存客户信息
public void saveCustomer(Customer customer){
   Session session=sessionFactory.openSession();
   Transaction tr=null;
   try{
   tr=session.beginTransaction();
   session.save(customer);
   tr.commit();
   }catch(Exception ex){
   if(tr!=null){
     tr.rollback();    
   }
   ex.printStackTrace();
   }finally{
   session.close();  
   }
  
}
public static void main(String[]args){
   BusServer bus=new BusServer();
   Customer customer=new Customer("Laosan","Zhang",'M',new HashSet(),"A good citizen!");
   Order order1=new Order("Order001",100,customer);
       Order order2=new Order("Order002",200,customer);
      
       customer.getOrders().add(order1);
       customer.getOrders().add(order2);
      
       bus.saveCustomer(customer);      
     //因为配置了表之间的关系,Hibernate会自动将Order1,Order2保存至表中
原创粉丝点击