Java对象持久化学习二
1. 一对多的对象关系 customer and order
一个customer有多个订单
public class Customer { private Set orders=new HashSet(); public Customer() {} public Set getOrders() { return this.orders; } public void setOrders(Set orders) { this.orders = orders; } }
public class Order { private Customer customer; public Order() {} public Customer getCustomer() { return this.customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
public void saveCustomer(Customer customer) throws Exception { Connection con=null; PreparedStatement stmt=null; try { con=getConnection(); con.setAutoCommit(false); if(customer.getName()==null) throw new BusinessException(""); long customerId=getNextId(con,"CUSTOMERS"); //首先向数据库添加customer对象 stmt=con.prepareStatement("insert into CUSTOMERS(ID,NAME,AGE) values(?,?,?)"); stmt.setLong(1,customerId); stmt.setString(2,customer.getName()); stmt.setInt(3,customer.getAge()); stmt.execute(); //得到customer对象的所有订单,向数据库中添加 Iterator iterator =customer.getOrders().iterator(); while (iterator.hasNext() ) { Order order=(Order)iterator.next(); if(order.getOrderNumber()==null) throw new BusinessException(""); long orderId=getNextId(con,"ORDERS"); stmt=con.prepareStatement("insert into ORDERS(ID,ORDER_NUMBER,PRICE,CUSTOMER_ID)values(?,?,?,?)"); stmt.setLong(1,orderId); stmt.setString(2,order.getOrderNumber()); stmt.setDouble(3,order.getPrice()); stmt.setLong(4,customerId); stmt.execute(); } con.commit(); }catch(Exception e){ e.printStackTrace(); try{ con.rollback(); }catch(SQLException sqlex){ sqlex.printStackTrace(System.out); } throw e; }finally{ try{ stmt.close(); con.close(); }catch(Exception e){ e.printStackTrace(); } } }
public void deleteCustomer(Customer customer) throws Exception { Connection con=null; PreparedStatement stmt=null; try { con=getConnection(); con.setAutoCommit(false); //先删除订单 stmt=con.prepareStatement("delete from ORDERS where " +"CUSTOMER_ID=?" ); stmt.setLong(1,customer.getId().longValue()); stmt.executeUpdate(); //然后删除客户对象 stmt=con.prepareStatement("delete from CUSTOMERS where " +"ID=?" ); stmt.setLong(1,customer.getId().longValue()); stmt.executeUpdate(); con.commit(); }catch(Exception e){ try{ con.rollback(); }catch(SQLException sqlex){ sqlex.printStackTrace(System.out); } throw e; }finally{ try{ stmt.close(); con.close(); }catch(Exception e){ e.printStackTrace(); } } }