Hibernate(HQL) 增、删、查、改 方法
import java.util.List;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class BaseDao {
//创建工程 sessionFactory
private static SessionFactory factory;
//初始化获取 hibernate 框架配置
static{
//获取配置信息
Configuration cfg=new Configuration().configure();
//获取工厂类对象
factory = cfg.buildSessionFactory();
}
/**
*
* @Title: queryWay01
* @Description: TODO( hql查询方式1 )
*/
@Test
public void queryWay01(){
String hql="from UserTable ut where ut.userId=:uid and ut.userName=:une";
Session session=factory.openSession();
Query query=session.createQuery(hql);
query.setInteger("uid", 1001);
query.setString("une", "修改");
List<UserTable> list=query.list();
for (UserTable userTable : list) {
System.out.println(userTable.toString());
}
}
/**
*
* @Title: queryWay02
* @Description: TODO( hql查询方式2 )
*/
@Test
public void queryWay02(){
String hql="from UserTable ut where ut.userId=? and ut.userName=?";
Session session=factory.openSession();
Query query=session.createQuery(hql);
query.setInteger(0, 1001);
query.setString(1, "修改");
List<UserTable> list=query.list();
for (UserTable userTable : list) {
System.out.println(userTable.toString());
}
}
/**
*
* @Title: queryWay02
* @Description: TODO( hql查询方式3 )
*/
@Test
public void queryWay03(){
UserTable user=new UserTable(null, "修改", "女", 1, null);
user.setUserId(1001);
String hql="from UserTable ut where ut.userId=:userId and ut.userName=:userName";
Session session=factory.openSession();
Query query=session.createQuery(hql);
query.setProperties(user);
List<UserTable> list=query.list();
for (UserTable userTable : list) {
System.out.println(userTable.toString());
}
}
@Test
public void queryWay04(){
/*String hql="from UserTable ut "+
"left join ut.depTable dt "+
"where ut.depTable.depId=dt.depId ";*/
String hql="from DepTable dt where dt.depId=:did";
Session session=factory.openSession();
Query query=session.createQuery(hql);
query.setInteger("did", 1001);
List<DepTable> list=query.list();
for (DepTable obj : list) {
System.out.println("部门:===》》》\n"+obj.toString()+"\n成员:===》》》");
//部门下的员工
Set<UserTable> emp=obj.getUserTables();
for (UserTable user : emp) {
System.out.println(user.toString());
}
}
}
/**
*
* @Title: queryWay05
* @Description: TODO(HQL分页)
*/
@Test
public void queryWay05(){
String hql="from UserTable ut ";
Session session=factory.openSession();
//写法1
/*Query query=session.createQuery(hql);
query.setFirstResult(0); //开始页数
query.setMaxResults(3); //每页多少数据
*/
//写法2 (方法链编程风格)
List<UserTable> list=session.createQuery(hql)
.setFirstResult(0) //开始页数
.setMaxResults(3) //每页多少数据
.list();
for (UserTable userTable : list) {
System.out.println(userTable.toString());
}
}
/**
* @Title: commonAdd
* @Description: TODO(添加方法)
*/
public boolean commonAdd(Object obj){
//创建session
Session session=factory.openSession();
//开启事物
Transaction ts=session.beginTransaction();
try {
session.save(obj);
//提交数据
ts.commit();
return true;
} catch (Exception e) {
ts.rollback();
}finally {
session.close();
}
return false;
}
/**
*
* @Title: commonUpdate
* @Description: TODO( 修改方法)
*/
public boolean commonUpdate(Object obj){
//创建session
Session session=factory.openSession();
//开启事物
Transaction ts=session.beginTransaction();
try {
session.update(obj);
ts.commit();
return true;
} catch (Exception e) {
ts.rollback();
}finally {
session.close();
}
return false;
}
/**
* @Title: commonDelete
* @Description: TODO(删除方法)
*/
public boolean commonDelete(Object obj){
//创建session
Session session=factory.openSession();
//开启事物
Transaction ts=session.beginTransaction();
try {
session.delete(obj);
ts.commit();
return true;
} catch (Exception e) {
ts.rollback();
}finally {
session.close();
}
return false;
}
/**
*
* @Title: commonQuery
* @Description: TODO(列表查询方法)
*/
public List commonQuery(String hql,Object ...parms){
//创建session
Session session=factory.openSession();
Query query=session.createQuery(hql);
//判断是否有参数赋值
if(parms.length>0){
for (int i = 0; i < parms.length; i++) {
query.setParameter(i, parms[i]);
}
}
//返回集合
return query.list();
}
/**
* @Title: getObj
* @Description: TODO(get()查询获取数据)
*/
public Object getObj(Class cls,int id){
Session session=factory.openSession();
Object obj=session.get(cls, id);
session.close();
return obj;
}
/**
* @Title: loadObj
* @Description: TODO(load()查询获取数据)
*/
public Object loadObj(Class cls,int id){
Session session=factory.openSession();
Object obj=session.load(cls, id);
/*session.close();*/
return obj;
}
/**
* @Title: commonQueryPage
* @Description: TODO(分页查询)
*/
public List commonQueryPage(String hql,int pageSize,int pageNo,Object ...parms){
//创建session
Session session=factory.openSession();
Query query=session.createQuery(hql);
//赋值
if(parms.length>0){
for (int i = 0; i < parms.length; i++) {
query.setParameter(i, parms[i]);
}
}
//设置分页参数
query.setFirstResult((pageNo-1)*pageSize);
query.setMaxResults(pageSize);
List list=query.list();
return list;
}
}
=》》》方法调用实现=============================================================
/**
* @Title: addUser
* @Description: TODO(添加部门会员)
*/
public boolean addUser(){
//创建功能类对象
BaseDao bd=new BaseDao();
//获取保存对象
DepTable dt=new DepTable();
dt.setDepName("技术");
dt.setDepAdmin("技术管理");
//存放部门对应的会员
/**
* SimpleDateFormat sdf=new SimpleDateFormat("yyy:MM:dd HH:mm:ss");
* String now=sdf.format(new Date());
*/
UserTable user1=new UserTable(dt, "李四1","女",20,Timestamp.valueOf("2019-11-11 11:34:28"));
UserTable user2=new UserTable(dt, "李四2","女",22,Timestamp.valueOf("2019-11-11 11:34:28"));
UserTable user3=new UserTable(dt, "李四3","女",26,Timestamp.valueOf("2019-11-11 11:34:28"));
Set<UserTable> set=new HashSet<UserTable>();
set.add(user1);
set.add(user2);
set.add(user3);
dt.setUserTables(set);
return bd.commonAdd(dt);
}
/**
* @Title: queryDept
* @Description: TODO( 查询返回数据集合)
*/
public void queryDept(){
BaseDao bd=new BaseDao();
List<DepTable> list=bd.commonQuery("from DepTable ", new Object[]{});
for (DepTable dep : list) {
System.out.println("部门==》\n"+dep.toString()+"\n部门下的员工:===》");
//部门下的员工
Set<UserTable> emp=dep.getUserTables();
for (UserTable user : emp) {
System.out.println(user.toString());
}
System.out.println("==============结束======================");
}
}
/**
* @Title: queryUser
* @Description: TODO( 用 get() 方法以ID查询单数据 )
*/
public void queryGetUser(){
BaseDao bd=new BaseDao();
UserTable user=(UserTable)bd.getObj(UserTable.class,1001);
System.out.println(user.toString());
}
/**
*
* @Title: queryLoadUser
* @Description: TODO(用 load() 方法以ID查询单数据 )
*/
public void queryLoadUser(){
BaseDao bd=new BaseDao();
UserTable user=(UserTable)bd.loadObj(UserTable.class,1001);
System.out.println(user.toString());
}
/**
*
* @Title: queryDeptandUser
* @Description: TODO(级联关联表格查询通过ID+分页 )
*/
public void queryDeptandUser(){
BaseDao bd=new BaseDao();
String hql="from UserTable ut "+
"left join ut.depTable dt "+
"where ut.depTable.depId=dt.depId and ut.userId=?";
List<Object> list=bd.commonQueryPage(hql, 3, 1,new Object[]{1001});
for (Object obj : list) {
Object[] objEnt=(Object[])obj;
for (Object object : objEnt) {
System.out.println(object.toString());
}
}
}
/**
*
* @Title: updateDept
* @Description: TODO( 修改)
*/
public boolean updateDept(){
BaseDao bd=new BaseDao();
DepTable dt=new DepTable();
dt.setDepName("修改技术");
dt.setDepAdmin("修改技术管理");
dt.setDepId(1001);
UserTable user1=new UserTable(dt, "修改","女",1,Timestamp.valueOf("2019-11-11 11:34:28"));
user1.setUserId(1001);
Set<UserTable> set=new HashSet<UserTable>();
set.add(user1);
dt.setUserTables(set);
return bd.commonUpdate(dt);
}
/**
* @Title: deleteUser
* @Description: TODO(删除会员)
*/
public boolean deleteUser(){
BaseDao bd=new BaseDao();
UserTable user=new UserTable();
user.setUserId(1004);
return bd.commonDelete(user);
}
/**
* @Title: deleteUser
* @Description: TODO(删除部门和会员)
*/
public boolean deleteDep(){
BaseDao bd=new BaseDao();
DepTable dt=new DepTable();
dt.setDepId(1002);
return bd.commonDelete(dt);
}