Hibernate連線查詢join

菜雞03號發表於2016-08-25

主表Owner 從表Tea

Owner及Tea的pojo

import java.util.HashSet;
import java.util.Set;

public class Owner {
  private int id;
  private String name;
  private String Address;
  private Set<Tea> set=new HashSet<Tea>();
  ....}
public class Tea {
   private int id;
   private int name;
   private int sales;
   private Owner owener;
......}

1.查詢物件:直接查詢返回一個符合條件的Object[][]的List
<pre class="java" name="code">
@Test
 public void test10(){
  String hql=" from Owner o join o.set where owner_id = :newName";
  Query query=session.createQuery(hql);
  List<Object[]> list=query.setInteger("newName", 103).list();
  tx.commit();
  Iterator it=list.iterator();
  while(it.hasNext()){
   Object[] o=(Object[]) it.next();
   System.out.print(o[0]);
   System.out.println(o[1]);
  }
 }

結果:

Owner [id=103, name=李華_1, Address=合肥_1]Tea [id=205, name=2, sales=2]
Owner [id=103, name=李華_1, Address=合肥_1]Tea [id=206, name=3, sales=3]

2.查詢物件:在查詢物件前加上distinct  這時只返回一個符合條件的主表物件的List
@Test
	public void test10(){
		String hql=" select distinct o from Owner o join o.set where owner_id = :newName";
		Query query=session.createQuery(hql);
		List<Owner> list=query.setInteger("newName", 103).list();
		tx.commit();
		Iterator it=list.iterator();
		while(it.hasNext()){
			System.out.println(it.next().toString());
		}
	}

查詢結果:
</pre></p><pre class="java" name="code">Owner [id=103, name=李華_1, Address=合肥_1]

3.查詢屬性:查詢單個屬性時返回一個Object查詢多個屬性時返回一個Object[][][][]....

distinct可加可不加

@Test
	public void test1(){
		String hql="select  o.name from Owner o inner join o.set teas where teas.name= :a";
				
		Query query=session.createQuery(hql);
		query.setString("a","2");
//		query.setInteger("b", 4);
		List<String> olist=query.list();
		tx.commit();
		for(String s:olist){
			System.out.println(s);
		}
	}



相關文章