HIbernate里session的delete()方法

<span style="font-size:18px;"> * 方法一
	 * @author zhupeng
	 * @param username
	 * @param pwd
	 * @return
	 */
	//执行delete操作              
	public boolean delete(String username,String pwd){
		System.out.println("执行删除操作");
		// 取得连接
		Session session = HibernateSessionFactory.getSession();
		// 插入一条数据
		Transaction tran = session.beginTransaction();// 启动事务处理
		Customer customer = new Customer();
		customer.setCustname(username);//不影响
		customer.setPwd(pwd);//不影响
		customer.setId(2); //session必须根据数据库的主键删除
		session.delete(customer);
		try {
			tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			tran.rollback();
		
		}		
		if(customer!=null){
			System.out.println("执行删除");
			return true;
			
		}
		else
		{
			System.out.println("执行false");
			return false;
		}
	</span>
<span style="font-size:18px;"> * 方法二
	 * @author zhupeng
	 * @param username
	 * @param pwd
	 * @return
	 */
	//执行delete操作              
	public boolean delete(){
		System.out.println("执行删除操作");
		// 取得连接
		Session session = HibernateSessionFactory.getSession();
		// 插入一条数据
		Transaction tran = session.beginTransaction();// 启动事务处理
		Customer customer =(Customer)session.get(Customer.class, 1);//这里是主键id
		 //session必须根据数据库的主键删除
		session.delete(customer);
		try {
			tran.commit();
		} catch (Exception e) {
			// TODO: handle exception
			tran.rollback();
		
		}		
		if(customer!=null){
			System.out.println("执行删除");
			return true;
			
		}
		else
		{
			System.out.println("执行false");
			return false;
		}
	}</span>


总结:


  session的delete方法删除的时候是通过主键进行删除的,所以在方法1中即使设置了不对应的其它字段也是可以正常删除数据的,如果数据库没有存在对应的主键值,会出现下面的异常 ---Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1



最后记住:



  1) session的delete方法是通过主键进行删除的,主键不存在则异常


  2) 持久状态对象被delete后变成瞬时状态对象</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值