hibernate关于多对多映射和多对一的hql查询

时间:2022-07-01 14:56:21
public void queryCustomerbymerchantId(){
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		Transaction ts = session.beginTransaction();
		try {
	   Query query=session.createQuery("select c from Customer c join c.merchant m where m.mid=1");
	   List customer = query.list();
	   for(int i=0;i<customer.size();i++)
	   {
	   	Customer customers =(Customer)customer.get(i);
	   		System.out.println(i+"--"+customers);
	   }

		ts.commit();	
		
	} catch (HibernateException e) {
		// TODO Auto-generated catch block
		if(ts != null)
		{
			ts.rollback();
		}
		e.printStackTrace();
	}
}

运行结果:

hibernate关于多对多映射和多对一的hql查询

由关系表可以看出运行结果是正确的

hibernate关于多对多映射和多对一的hql查询

最容易出现错误的就是hql语句,大家可能会习惯性直接select c from Customer c where .......;

再写一个例子,customer与order是一对多的关系,通过order找customer

public void queryCustomerbyOrderId(){
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.getCurrentSession();
		Transaction ts = session.beginTransaction();
//		int n;
//		Scanner sc=new Scanner(System.in);
//		n=sc.nextInt();
		try {
	   Query query=session.createQuery("select customer from Order o where  o.id=1" );
	   System.out.println(query);
	   List customer = query.list();   
	   for(int i=0;i<customer.size();i++)
	   {
	   	Customer customers =(Customer)customer.get(i);
	   		System.out.println(i+"--"+customers);
	   }

		ts.commit();	
		
	} catch (HibernateException e) {
		// TODO Auto-generated catch block
		if(ts != null)
		{
			ts.rollback();
		}
		e.printStackTrace();
	}
}
hibernate关于多对多映射和多对一的hql查询