
針對上面的角色人員表如何用hibernate實現(xiàn)映射關系呢,因為此表中的兩個字段是其它兩表中主鍵,在本表中即使是主鍵又是外鍵,下面說明一下操作這張表。
第一步:首先生成員工信息表和角色管理表的javaBean和.hbm.xml文件,這個是單表,這里不多講;
com.insigma.hr.eduj.ygxx.model.Ygxx.java,
com.insigma.hr.eduj.ygxx.model.Ygxx.hbm.xml
com.insigma.hr.eduj.jsgl.model.Jsgl.java,
com.insigma.hr.eduj.jsgl.model.Jsgl.hbm.xml
保證員工信息表和角色管理表能正常操作數(shù)據(jù)庫(增,修,刪,查);
第二步:生成角色人員表對應的映射文件如下:
1).Jsry.hbm.xml文件內容如下:



































3).Jsry.java這個javabean中只有一個屬性,就是我們上面剛才新建的JsryId這個類對象;內容如下:
public class Jsry implements java.io.Serializable {
// Constructors
private JsryId id;
/** default constructor */
public Jsry() {
}
/** full constructor */
public Jsry(JsryId id) {
this.id = id;
}
public JsryId getId() {
return id;
}
public void setId(JsryId id) {
this.id = id;
}
}
public void save(Jsry jsry) {
log.debug("saving Jsry instance");
try {
getHibernateTemplate().saveOrUpdate(jsry);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Jsry jsry) {
log.debug("deleting Jsry instance");
try {
getHibernateTemplate().delete(jsry);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Jsry findById(com.insigma.hr.eduj.jsry.model.JsryId id) {
log.debug("getting Jsry instance with id: " + id);
try {
Jsry instance = (Jsry) getHibernateTemplate().get(
"com.insigma.hr.eduj.jsry.model.Jsry", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List getJsgllist(String sql) {
String sqls = "select t.* from Jsgl t where 1=1 " + sql;
SQLQuery query = getHibernateTemplate().getSessionFactory()
.getCurrentSession().createSQLQuery(sqls);
query.addEntity("t", Jsry.class);
List topList = query.list();
return topList;
}
第四步:測試
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext appContext = new FileSystemXmlApplicationContext("/src/applicationContext.xml");
JsryService jsryService=(JsryService) appContext.getBean("jsryService");
Jsry jsry = new Jsry();
JsryId id = new JsryId();
Jsgl jsgl = new Jsgl();
jsgl.setJsbh(1);
Ygxx ygxx = new Ygxx();
ygxx.setYgbh("1");
id.setYgxx(ygxx);
id.setJsgl(jsgl);
jsry.setId(id);
jsryService.save(jsry);
}