过程域对象BusinessService的程序,它提供了customer对象的持久化方法。
saveCustomer() 把customer域对象永久的保存到数据库中。
updateCustomer() 更新数据库中Customer域对象的状态。
deleteCustomer() 从数据库中删除Customer域对象。
loadCustomer() 根据特定的OID,把一个Customer域对象从数据库中加载到内存中。
findCustomerByName() 根据特定的顾客名字,把符合条件的customer域对象从数据库中加载到内存中。
public class BusinessService{
private String url ="jdbc:mysql://localhost:3306/SAMPLEDB";
private String user ="test";
private String password ="test";
public BusinessService() throws Exception{
//加载mysql数据库驱动程序
Class.forName("com.mysql.jdbc.Driver");
}
public Connection getConnection()throws Excepiton{
return java.sql.DriverManager.getConnection(url,user,password);
}
/**保存参数制定的Customer对象,并且级联保存与它相关的order对象。
*如果customer,或者order为空,则抛出异常。
*/
public void saveCustomer(Customer customer) throws Exception{
Connection conn = null ;
PreparedStatement stmt = null ;
try{
conn = getConnection();
conn.setAutoCommit(false);
if (customer.getName() == null){
throw new BusinessExcepiton("客户姓名不能为空!");
}
long customerId = getNextId(conn,"CUSTOMERS");
stmt = conn.preparedStatement("insert into CUSTOMERS(id,name,age) values(?,?,?)");
stmt.setLong(1,customerId);
stmt.setString(2,customer.getName());
stmt.setInt(3,customer.getAge());
stmt.execute();
Iterator it = customer.getOrders().iterator();
while(it.hasNext()){
Order order = (order)it.next();
if(order.getOrderName == null){
throw new BusinessException("订单编号不允许为空!");
}
Long orderId = getNextId(conn,"ORDERS");
stmt = conn.preparedStatement("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();
}
conn.commit();
}catch(Excepiton e){
try{
conn.rollback();
}catch(SQLExcepiton e){
e.printStackTrace(System.out);
}
throw e ;
}finally{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
*更新指定参数的customer对象
*/
public void updateCustomer(Customer customer)throws Exception{
Connection conn = null ;
PreparedStatement stmt = null ;
try{
conn = getConnection();//获得数据库连接
conn.setAutoCommit(false);
stmt = conn.prepareStatement("update customer set name=?,age=? where id =?");
stmt.setString(1,customer.getName());
stmt.setInt(2,customer.getAge());
stmt.setLong(3,customer.getId().LongValue());
stmt.execute();
stmt.commit();
}catch(Exception e){
try{
conn.rollback();
}catch(SQLException sqlex){
sqlex.printStackTrace(System.out);
}
throw e ;
}finally{
stmt.close();
conn.close();
}
}
/**删除指定的customer对象,并且删除与它关联的order对象。
*
*/
public void deleteCustomer(Customer customer) throws Exception{
Connection conn = null ;
PreparedStatement stmt = null ;
try{
conn = getConnection();
conn.setAutoCommit(false);
stmt = conn.prepareStatement("delete from Orders where customer_id =?");
stmt.setLong(1,customer.getID().LongValue());
stmt.executeUpdate();
stmt = conn.prepareStatement("delete from Customers where id =?");
stmt.setLong(1,customer.getID().LongValue());
stmt.executeUpdate();
stmt.commit ;
}catch(Exception e){
try{
conn.rollback();
}catch(SQLException sqlex){
sqlex.printStackTrace(System.out);
}
throw e ;
}finally{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**根据OID加载一个Customer对象
*
*/
public Customer LoadCustomer(long customerId)throws Exception{
Connection conn = null ;
PreparedStatement stmt = null ;
ResultSet rs = null ;
try{
conn = getConnection();
stmt = conn.prepareStatement("select id,name,age from customers where id=?");
stmt.setLong(1,customerId);
rs = stmt.executeQuery();
if(rs.next()){
Customer customer = new Customer();
customer.setId(new long(rs.getLong(1)));
customer.setName(rs.getString(2));
customer.setAge(rs.getInt(3));
return customer ;
}else{
throw new BusinessException("OID为"+customerId+"的Customer对象不存在!");
}
}finally{
try{
rs.close();
conn.close();
stmt.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
/**
*根据姓名查询满足条件的客户
*/
public List findCustomerByName(String name)throws Exception{
HashMap map = new HashMap();
List result = new ArrayList();
Connection conn = null;
PreparedStatement stmt = null ;
ResultSet rs = null ;
try{
conn = getConnection();
String sqlString =" select c.id customer_id,c.name,c.age,o.id order_id,o.order_number,o.price "
+" from customers c ,orders o where c.id = o.id(+) and c.name=? " ;
stmt = conn.prepareStatement(sqlString);
stmt.setString(1,name);
rs = stmt.executeQuery();
while(rs.next()){
//遍历jdbc resutlset结果
Long customerId = new Long(rs.getLong(1));
String customerName = rs.getString(2);
int customerAge = rs.getInt(3);
Long orderId = new Long(rs.getLong(4));
String orderNumber = rs.getString(5);
double price = rs.getDouble(6);
Customer customer = null ;
if(map.containsKey(customerId)){
//如果在map中已经存在OID匹配的Customer对象,就获得此对象的引用,这样就避免创建重复的对象
customer = (Customer)map.get(customerId);
}else{
customer =new Customer();
customer.setId(customerId);
customer.setName(customerName);
customer.setAge(customerAge);
map.put(customerId,customer);
}
//映射order对象
Order order = new Order();
order.setId(orderId);
order.setOrderName(orderName);
order.setPrice(price);
//建立customer与order关系
customer.getOrders().add(order);
order.setCustomer(customer);
//把map中所有的customer对象加入到result中
Iterator iter = map.values().iterator();
while(iter.hasnext()){
result.add(iter.next());
}
return result ;
}finally{
try{
rs.close();
stmt.close();
conn.close();
}catch(Exception ex){
e.printStackTrace();
}
}
}
}
/**
*生成一个新的主键值,为表的最大主键值+1,如果不存在,则为1
*/
private long getNextId(Connection conn,String tablename)throws Exception{
long nextId ;
PreparedStatement stmt = null ;
ResultSet rs = null ;
try{
stmt = conn.prepareStatement("select max(id) from "+tablename);
rs = stmt.executeQuery();
if(rs.next()){
nextId = rs.getLong(1)+1;
if(rs.wasNull()) nextId = 1;
}else{
nextId = 1;
}
return nextId ;
}finally{
try{
rs.close();
stmt.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}