hbm.xml配置重点
复合主键标签如下:
<composite-id name="primaryKey" class="com.sinopharm.zcps.entity.PrimaryKey">
<key-property name="emplid" column="emplid"></key-property>
<key-property name="emplrcd" column="emplrcd"></key-property>
</composite-id>
注意:这里name一定要小写
创建一个PrimaryKey
注意:一定要实现Serializable,重写equals和hashCode方法
实体类中直接注入
private String sex;
private Date birthday;
private String comment;
private PrimaryKey primaryKey;
以Id查询为例
Action
public void find(){
Prud find = prudService.find(prud.getPrimaryKey().getEmplid());
String json = JSON.toJSONStringWithDateFormat(find, "yyyy-MM-dd-?", SerializerFeature.WriteDateUseDateFormat);
PageUtil.write(PageUtil.mapJson(json,"prud"));
}
这里只需注入prud,两个get方法就能得到 Id
DaoImpl
public Prud find(String emplid) {
try {
System.out.println("find!");
HibernateTemplate hibernateTemplate = getHibernateTemplate();
if(emplid!=null&&!emplid.trim().equals("")){
System.out.println("查找ID:"+emplid);
List<Prud> list = hibernateTemplate.find(
"from Prud a where a.primaryKey.emplid = ? ",
emplid);
if(list!=null&&list.size()>0&&list.get(0)!=null){
System.out.println("find成功");
return list.get(0);
}else{
System.out.println("find结果为空");
return null;
}
}else{
System.out.println("find失败,搜索条件为空!");
return null;
}
} catch (Exception e) {
System.out.println("find方法异常");
e.printStackTrace();
return null;
}
}
如果数据不回显,但是后端接口没有问题,有可能hbm.xml配置错误
DELETE
直接用delete方法不能直接删除prud
public String delete(Prud prud) {
try {
System.out.println("delete");
HibernateTemplate hibernateTemplate = getHibernateTemplate();
System.out.println("删除ID?"+prud.getPrimaryKey().getEmplid());
List<Prud> list = hibernateTemplate.find("from Prud z where z.primaryKey.emplid=?",prud.getPrimaryKey().getEmplid());
hibernateTemplate.delete(list.get(0));
System.out.println("delete成功");
return "success";
} catch (Exception e) {
System.out.println("delete方法异常");
e.printStackTrace();
return "error";
}
}
可以把数据封装到list中,再删除list的第一条数据