<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>