日期:2014-05-17  浏览次数:20761 次

Hibernate很不能让人理解的问题
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.ifacewall.model.UserGradeBean;
import com.ifacewall.model.UserInfoBean;

public class UserInfoServiceTest {

private static final SessionFactory sesstionFactory = (new Configuration()
.configure().buildSessionFactory());

public interface IUserinfo {
void saveUserGrade(Session session, UserInfoBean userbean);

void getUserLit(Session session);
}


@SuppressWarnings("unchecked")
@Test
public void HookFnk() {
// 模仿的是钩子函数
transctionTemplemnt(new IUserinfo() {
// manyt-to-one保存
public void saveUserGrade(Session session, UserInfoBean userbean) {

if(1==1)return;
// TODO Auto-generated method stub
UserGradeBean userGradeBean = new UserGradeBean();

userGradeBean.setCreateTime(java.util.Calendar.getInstance()
.getTime());
userGradeBean.setGradeName("2班");

// cascade:all,级联,如果userinfo加了那么就可以不先保存
// session.save(userGradeBean);

System.out.println("-----------" + userGradeBean.getId());

userbean = new UserInfoBean();

userbean.setUserGradeBean(userGradeBean);
userbean.setBirthDate(java.util.Calendar.getInstance()
.getTime());
userbean.setUserName("Gt." + System.currentTimeMillis());

session.save(userbean);

}

  //就这里为什么报错了
public void getUserLit(Session session) {
// TODO Auto-generated method stub

UserInfoBean userInfoBean = null;
Set students = new HashSet();
UserGradeBean userGradeBean = new UserGradeBean();

userGradeBean.setGradeName("grad:" + System.currentTimeMillis());
userGradeBean.setCreateTime(java.util.Calendar.getInstance().getTime());

userInfoBean = new UserInfoBean();

userInfoBean.setBirthDate(java.util.Calendar.getInstance().getTime());
userInfoBean.setUserName("XXXX");
userInfoBean.setUserGradeBean(userGradeBean);

students.add(userInfoBean);

userInfoBean = new UserInfoBean();

userInfoBean.setBirthDate(java.util.Calendar.getInstance().getTime());
userInfoBean.setUserName("XXXX");
userInfoBean.setUserGradeBean(userGradeBean);

students.add(userInfoBean);

userInfoBean = new UserInfoBean();

userInfoBean.setBirthDate(java.util.Calendar.getInstance().getTime());
userInfoBean.setUserName("XXXX");
userInfoBean.setUserGradeBean(userGradeBean);

students.add(userInfoBean);

userGradeBean.setUserInfoList(students);
session.save(userGradeBean);
   
  //上面我出现了2个问题,一个是报错,另外一个是:userinfo没有insert语句?
}

});
}

/*-----------------------------------------*/
private void transctionTemplemnt(IUserinfo iinfo) {

System.out.println(sesstionFactory == null ? "null" : "");
Session session = sesstionFactory.openSession();
session.beginTransaction();

iinfo.saveUserGrade(session, null);

iinfo.getUserLit(session);

session.getTransaction().commit();

session.close();
}

}
---------------------------
<?xml version="1.0" encoding="