public class BusinessService{
public static SessionFactory sessionFactory;
static{
try{
Configuration config = new Configuration();
config.addClass(Company.class)
.addClass(HourlyEmployee.class)
.addClass(SalariedEmployee.class);
sessionFactory = config.buildSessionFactory();
}catch(Exception e){e.printStackTrace();}
}
public void saveEmployee(Employee employee) throws Exception{……}
public List findAllEmployees() throws Exception{……}
public Company loadCompany(long id) throws Exception{……}
public void test() throws Exception{
List employees=findAllEmployees();
printAllEmployees(employees.iterator());
Company company=loadCompany(1);
printAllEmployees(company.getEmployees().iterator());
Employee employee=new HourlyEmployee("Mary",300,company);
saveEmployee(employee);
}
private void printAllEmployees(Iterator it){
while(it.hasNext()){
Employee e=(Employee)it.next();
if(e instanceof HourlyEmployee){
System.out.println(((HourlyEmployee)e).getRate());
}else
System.out.println(((SalariedEmployee)e).getSalary());
}
}
public static void main(String args[]) throws Exception {
new BusinessService().test();
sessionFactory.close();
}
}
BusinessService的main()方法调用test()方法,test()方法依次调用以下方法。
findAllEmployees():检索数据库中所有的Employee对象。
loadCompany():加载一个Company对象。
saveEmployee():保存一个Employee对象。
|