SSH 复合主键crud重点

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的第一条数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值