Hibernate实现增删改查

package com.atlas.DAOFactory.role;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.atlas.hibernate.HibernateSessionFactory;
import com.atlas.util.Logs;

public class RoleDAO {

Session session;
List list=null;
Transaction tx;
Query query;
Logger logger=Logs.logs(this.getClass());

/*
* 插入一个role角色对象,根据结果返回true或 false
*/
public boolean insertRole(Role role) {
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();//创建事务
boolean flag=false;
try {
session.save(role);
tx.commit();//事务提交
flag=true;
} catch (HibernateException e) {
Logs.writeError(logger,"添加角色失败");
// TODO: handle exception
}finally{
try {
session.close();
} catch (HibernateException e) {
// TODO: handle exception
Logs.writeWarn(logger, "关闭session失败");
}
}
return flag;
}

/*
* 跟据action传递得记录id,删除一条记录信息
*/
public void deleteRole(Long id){
try {
session=HibernateSessionFactory.getSession();
tx=session.beginTransaction();
Role role=new Role();
role.setId(id);
session.delete(role);
tx.commit();
} catch (HibernateException e) {
// TODO: handle exception
e.printStackTrace();
Logs.writeError(logger, "删除角色失败");

}finally{
try {
session.close();
} catch (Exception e) {
// TODO: handle exception
Logs.writeWarn(logger, "session关闭失败");
}
}
}
/*
* 根据updateRole.jsp传入得id执行更新操作
*/
public boolean updateRole(Role role){
session=HibernateSessionFactory.getSession();
tx=session.beginTransaction();
boolean flag=false;
try {

session.update(role);
tx.commit();
flag=true;
} catch (HibernateException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
session.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return flag;
}

/*
* 从数据库中查询出所有的角色,并返回结果集list
*/
public List selectRole(){
session=HibernateSessionFactory.getSession();
tx=session.beginTransaction();
List list=null;
try {
String hql="from Role";
query=session.createQuery(hql);
list=query.list();

} catch (HibernateException e) {
// TODO: handle exception
Logs.writeError(logger, "查询出所有角色失败");
}finally{
try {
session.close();
} catch (HibernateException e) {
Logs.writeWarn(logger, "session关闭失败");
// TODO: handle exception
}
}
return list;
}
/*
* 根据modifyOrgan.jsp传入得id,查询出一条信息
*/
public List findby(Long id){

session=HibernateSessionFactory.getSession();
tx=session.beginTransaction();
try {
String hql="from Role where id="+id;
query=session.createQuery(hql);
list=query.list();
} catch (HibernateException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
session.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

return list;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值