日期:2014-05-18 浏览次数:20788 次
/**
*实体类
*/
public class Account{
private Integer userId;//用户ID
private Double Balance;//账户余额
....//get set方法
}
/**
*DAO接口
*/
public Interface AccountDAO{
public boolean update(Account a);
}
/**
*实现类
*/
public class AccountDAOImpl implements AccountDAO{
public void update(Account a){
//HibernateSessionFactory是myeclipse自动生成的一个获取Hibernate Session的类,
//它将session保存在一个静态ThreadLocal变量中,这这样对于每个线程,DAO实现类的方法
//都能取得同一个session
Session session = HibernateSessionFactory.getSession();
session.update(a);
}
}
//就不写接口了
public class BankServices{
AccountDAO ad = new AccountDAOImpl();
//转账业务方法
//from 出账账户, to 进账账户
public boolean Transfer(Account from, Account to){
session = HibernateSessionFactory.getSession();
Transaction ts = null;
try{
ts = session.beginTransaction();
ad.update(from);
ad.update(to);
ts.commit();
}catch(Exception e){
ts.rollback();
}finally{
session.close();
}
}
}
public class AccountDAOImpl implements AccountDAO{
Session session = null;
Transaction ts = null;
public AccountDAOImpl(){
}
public AccountDAOImpl(Session session){
this.session = session;
}
public void Transfer(Account from, Account to){
try{
ts = session.beginTransaction();
session.update(from);
session.update(to);
ts.commit();
}catch(Exception e){
ts.rollback();
}
}
}
/**
*代理类
*/
public class AccountDAOProxy implements AccountDAO{
AccountDAOImpl adi = null;
public AccountDAOProxy(){
Session session = HibernateSessionFactory.getSession();
&nbs