一.查询
Session s=HibernateSessionFactory.getSession();
Transaction tra=s.beginTransaction();
Query q=s.createQuery("from Company where name=:name");
q.setParameter("name","baobao");
1.HQL查询
from Company c //Company是映射类而不是表表名,c:是别名。查找对应表所有的记录
//不能写成from * from Company c
2.传统SQL方式查询 from Company c where c.name='baobao' //SQL方式查询
3.占位符(?)式查询 参数索引以0开始,而Jdbc的PrepareStatement是以1开始
Query q=session.createQuery("from Company c where c.name=? and c.id=?");
q.setParameter(0,"baobao");
q.setParameter(1,5);
List l=q.list(); //查询条件name=baobao and id=5的记录
4.命名参数赋值(推荐) 如 :name
Query q=s.createQuery("from Company c where c.name = :name and c.id = :id");
q.setParameter("name","baobao");
q.setParameter("id",5);
List l=q.list(); //查询条件name=baobao and id=5的记录
5.命名查询方式:主要是将HQL放在相应类的映射文件中
如:在Company.hbm.xml文件中在<class></class>外面加入
<query name="Company.byname">
<![CDATA[FROM Company c WHERE c.name= :name and c.id= :id]]>
</query>
然后在JAVA文件中
Query q=s.getNamedQuery("Company.byname");
q.setParameter("name","baobao");
q.setParameter("id",5);
List l=q.list();
6.连接查询(多表查询)
from Company c join c.departments d where c.id=5 and d.name=''[=c.departments.name] order by time desc
//==select * from company inner join departments on company.departmetns_id=departmetns.id
//[inner] join 不满足条件的对象被过滤
//left join 返回连接左边的对象,右边即使没有匹配的对象也将返回
//right join 返回连接右边的对象,左边即使没有匹配的对象也将返回
7.in查询
String hql="FROM A WHERE A.ID IN (:alist)";
Query query = getSession().createQuery(hql);
query.setParameterList("alist", a);
二.更新
1.更新操作update
Query q=s.createQuery("update CourseMonney set score= :score where studentId= :stuId and courseId= :teaId");
q.setParameter("stuId","20070113");//注意:参数类型必须与字段类型一致
q.setParameter("teaId",12);
q.setParameter("score",addscoreForm.getScore());
q.executeUpdate();
//相当于"update coursemonney set score=12 where studentid='20070113 and courseid=12'"
三.删除
1.Query q=s.createQuery("delete CourseMonney as c where studentId= :stuId and courseId= :teaId");
q.setParameter("stuId","20070113");//注意:参数类型必须与字段类型一致
q.setParameter("teaId",12);
q.executeUpdate();
//相当于"delete from coursemonney where studentid='20070113 and courseid=12'"
2.使用HQL语句,动态参数
List<String> list = Arrays.asList(ids.split(","));
String hql = "delete from Contract_Site where contract.id in(:cid)";
Query q = super.createQuery(hql);
q.setParameterList("cid", list);// 注意:参数类型必须与字段类型一致
q.executeUpdate();
hibernate会根据list数量生成SQL:delete from table where id in (?,?...);