1、jsp 清除session的方法(引自新浪博客/先知)
“就是关于如何清除当前页面的session 退出到首页,使用户再次登陆必须提供正确的用户名和密码
我的三个页面是 index.jsp logon.jsp logout.jsp
index.jsp中输入正确的用户名和密码会跳转到logon.jsp中
在logon.jsp中我加了以下内容防止在浏览器中输入logon.jsp非法登录
<%
String admin_name=(String) session.getValue("name");
if(admin_name==null)
out.print("<script>alert('请先登陆。');window.location.href='index.jsp';</script>");
%>
我在logon.jsp中有个链接"退出登陆"指向logout.jsp页面
logout.jsp的内容如下:
<%
session.invalidate();
out.print("<script>alert('用户即将退出,确定后退出该页面。');window.location.href='index.jsp'</script>");
%>
……“
然后自己测试时发现将 <%session.invalidate();%> 放在body的顶部会将需要得到的session也清除掉,而放在body尾部可以只清除当前旧的session并且不会清除将要得到的session。
2、hibernate 执行sql ,select 返回string long (引自CSDN博主/arui_email)
1.执行sql,返回一个结果集,适用查询一个字段并返回一条记录
public Long findSeqTbTest() {
String sql = "select SEQ_TB_TEST.nextval from dual";
SQLQuery query = this.getSession().createSQLQuery(sql);
String str = query.uniqueResult().toString();
return Long.valueOf(str);
}
//获取表中最小的id
String sql = "select min(a.employeeid) from Emplyees a";
Long id = (Long) session.createQuery(sql).uniqueResult();
//获取数据库时间mysql
String sql = "select now() from dual";
String time = session.createSQLQuery(sql).uniqueResult().toString();
2.删除、更新等操作,这里参数是从0开始的
public void deleteTbTest(Long id) {
String hql = "DELETE FROM TbTest WHERE ID = ?";
this.getSession().createQuery(hql).setLong(0, id).executeUpdate();
}
public void updateTbTest(Date date, boolean flag) {
String sql = "update tb_test set t_name=? where t_status!=1 and t_date" + (flag ? "<?" : "=?");
SQLQuery query = this.getSession().createSQLQuery(sql);
query.setString(0,flag ? "hello": "hi").setDate(1, date).executeUpdate();
}
3.执行sql,查询单表中多条数据
//尽量避免适用"*"
String sql = "select * from employee e where e.valid=1 and not exists (select employeeid from attendance a where a.employeeid=e.employeeid and a.date = ?)";
SQLQuery query = getSession().createSQLQuery(sql);
query.addEntity(Employee.class).setDate(0, day);
List<Employee> retList = query.list();
4.查询多表
String hql = "select new map(dept.deptID as deptID,dept.depNo as deptNo,dept.deptName as deptName,emp.empName as empName,emp.empID as empID,emp.empAge as age,emp.empNo as empNo) from Department dept ,Employee emp where dept.depID = emp.depID and emp.empName = ? and emp.sex = ?";
return getHibernateTemplate().find(hql, new Object[] { name, sex });
每个字段都保存在map中(key是字段名,value是此字段的值如:[{empID=1,empName=leona,…},…])
5.查询多表
String sql = "select dept.deptID as deptID,dept.depNo as deptNo,dept.deptName as deptName,emp.empName as empName,emp.empID as empID,emp.empAge as age,emp.empNo as empNo,emp.birthday as birthday from Employee emp LEFT JOIN Department dept on dept.depID = emp.depID where empName = ?";
return (List<EmpBean>) this.getSession()
.createSQLQuery(sql)
.addScalar("deptID", Hibernate.STRING)
.addScalar("deptNo", Hibernate.STRING)
.addScalar("deptName", Hibernate.STRING)
.addScalar("empName", Hibernate.STRING)
.addScalar("empID", Hibernate.STRING)
.addScalar("age", Hibernate.LONG)
.addScalar("birthday", Hibernate.DATE)
.addScalar("empNo", Hibernate.STRING)
.setString(0, empName)
// 将结果集映射为EmpBean对象
.setResultTransformer(Transformers.aliasToBean(EmpBean.class)).list();
String hql = "from Attendance att where att.employeeid = ? and att.date =? ";
List<Attendance> list = this.getHibernateTemplate().find(hql,
new Object[] { employeeid, workDay });
if (null != list && !list.isEmpty()) {
return list.get(0);
}
String queryString = "FROM Attendance a WHERE a.employeeid=? AND DATE_FORMAT(a.date,'%Y-%m')=DATE_FORMAT(?,'%Y-%m') ORDER BY a.teamname";
Query queryObject = getSession(). createQuery(queryString);
queryObject.setParameter(0, id);
queryObject.setParameter(1, date);
return queryObject.list();
Session session = getSession();
session.clear();
getSession().saveOrUpdate(transientInstance);
startBatch()的用法
public class LocalDaoImpl extends SqlMapClientDaoSupport implements LocalDao {
public void insertBuNaTaxBatLst(final PaginatedList list)
{
getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
public Object doInSqlMapClient(SqlMapExecutor executor)
throws SQLException {
executor.startBatch();
// do some iBatis operations here
for(int i=0,count=list.size();i<count;i++)
{
executor.insert("insertBuNaTaxBatLst", list.get(i));
if (i % 50 == 0) {
System.out.println("----" + i);//没有意义只为测试
}
}
executor.executeBatch();
return null;
}
});
}
3.删除某条记录(有其他表的外键)时报错Cannot delete or update a parent row: a foreign key constraint fails
删除(one端)某条记录(有其他表的外键)时页面报错“……Cannot delete or update a parent row: a foreign key constraint fails……”
查了一下原因发现是数据库中另一个表(many或one)的删除时选项默认是“SET NULL",在外键约束下需要改为CASCADE,即级联删除。这样当删除one端的数据时many端也会同时删除。
![数据库——设计表,改外键删除时的策略为CASCADE](https://img-blog.csdn.net/20160406003826078)
HQL:from Project o where 1=1 and PRJ_NAME like '%strCond%';//这里PRJ_NAME 应该是数据库表中的实际字段名
HQL:from Project o where 1=1 and o.PRJ_NAME like '%strCond%';//这里PRJ_NAME 应该是实体类的属性名
HQL:from Project o where 1=1 and PRJ_NAME like '?';//这里的?不视为占位参数
HQL:from Project o where 1=1 and PRJ_NAME like ?;//设置参数值时会自动在参数值两边加上单引号。
4.正在等待localhost的响应
发现每次查询数据连续查询的次数多了网页就会失去响应,准确地说是失去了localhost的响应,一开始我以为是tomcat的性能问题,用了几次就不能用了,所以以前每次都去tomcat上重新部署项目,但后来还是觉得太诡异了,发现是session没有被关闭的问题,注意是关闭(close),我之前的代码是在使用了hibernate查询的hql语句后session.clear( ),然而这只是清空了session对象的所有键值对,而之前被声明的session并没有被关闭,所以我试了一下大概连续查了9次之后,localhost便不再响应,所以必须使用session.close( )将声明的session完全关闭,这样改了之后就不会再因为这个出现localhost无响应的情况啦,连续试了100次查询都没出现,而且查询速度比之前快了。必须说明的是,我的session是用的Hibernate中的Session session = getSession();
得到的,需要自己close,而导入Spring相应包import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
使用Spring(hibernate3版本,hibernate4不能用)封装的getHibernateTemplate( ).xxx( )方法做CRUD则不用自己关闭,Spring会自己管理相应连接。不过,用这个有一些局限性,封装好的总是不够灵活嘛,看自己取舍吧,hibernate4就不支持getHibernateTemplate( )这个了。另外多聊一句,hibernate获取数据时使用对象查询会查询数据库表中的所有字段,所以当业务很多时Mybatis会更加合适,速度更快,对于SQL可以做更多优化,还没学Mybatis,准备暑假学一下,公司里mybatis用的多。