hibernate通过hibernateSessionFactory类(myeclipse自动生成的类,我拿到eclipse中使用)获取session
在junit中可以得到session 为什么通过struts的Action调用不可以得到session?
错误状况:不报错,在UserAction.java中,通过Session session = HibernateSessionFactory.getSession();得到的sessin是不执行,不报错,悄悄给我吞了。
运行环境:eclipse+struts2.3.4+hibernate4.1.7+mysql 代码结构:
com.xxl.action(包)
UserAction.java(包下的java文件)com.xxl.dao.i
IUserDAO.javacom.xxl.dao.impl
UserDAOImpl.javacom.xxl.model
User.javacom.xxl.util
HibernateSessionFactory.java
testLogin.javahibernate.cfg.xml
struts.xml引入对应的jar包
JUnit测试代码:测试代码运行正常,可以正常存入数据库。
@Test
public void loginTest() {
try{
User u = new User();
u.setUsername("user03");
u.setPassword("123456");
u.setState(1);
u.setState_explain("无"); Session session = com.xxl.util.HibernateSessionFactory.getSession();
Transaction ts=session.beginTransaction();
session.save(u);
ts.commit();
com.xxl.util.HibernateSessionFactory.closeSession(); }catch(Exception e){
e.printStackTrace();
}
}UserAction.java代码:这是struts的Action代码,可以正常接收参数,不调用dao的方法的时候可以正常进行逻辑,调用dao,通过HibernateSessionFactory.java类获取session的时候出错。
package com.xxl.action;import java.util.Map;import org.hibernate.Session;
import org.hibernate.Transaction;import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xxl.dao.i.IUserDAO;
import com.xxl.dao.impl.UserDAOImpl;
import com.xxl.model.User;public class UserAction extends ActionSupport{
private User user;
public String test(){
if("user".equals(user.getUsername())){
return SUCCESS;
}else{
return ERROR;
}
}
public String login(){
IUserDAO dao = new UserDAOImpl();
System.out.println("接收参数:"+user.getUsername()+user.getPassword());
User s_user = null;
try {
s_user = dao.login(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(s_user!=null){
//如果不为空,保存到Session中
//Map session=(Map)ActionContext.getContext().getSession();
//session.put("user1", user);
System.out.println("登陆完成:"+user.getState_explain());
return SUCCESS;
}else{
return ERROR;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
UserDAOImpl.java:dao实现类[color=#FF0000][/color]
package com.xxl.dao.impl;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;import com.xxl.dao.i.IUserDAO;
import com.xxl.model.User;
import com.xxl.util.HibernateSessionFactory;public class UserDAOImpl implements IUserDAO{
public boolean add(){
System.out.println("add success !");
return true;
}
public User login(User user) {
try{
Session session = HibernateSessionFactory.getSession();
Transaction ts=session.beginTransaction();
Query query=session.createQuery("from User u where u.username=? and u.password=?");
query.setParameter(0, user.getUsername());
query.setParameter(1, user.getPassword());
query.setMaxResults(1);
User s_user=(User) query.uniqueResult();
ts.commit();
HibernateSessionFactory.closeSession();
System.out.println("查询数据库结束:"+s_user.getState_explain());
return s_user;
}catch(Exception e){
return null;
}
}
}
HibernateSessionFactory.java:获取session的类,myeclipse自动生成。package com.xxl.util;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
} /**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}}
在junit中可以得到session 为什么通过struts的Action调用不可以得到session?
错误状况:不报错,在UserAction.java中,通过Session session = HibernateSessionFactory.getSession();得到的sessin是不执行,不报错,悄悄给我吞了。
运行环境:eclipse+struts2.3.4+hibernate4.1.7+mysql 代码结构:
com.xxl.action(包)
UserAction.java(包下的java文件)com.xxl.dao.i
IUserDAO.javacom.xxl.dao.impl
UserDAOImpl.javacom.xxl.model
User.javacom.xxl.util
HibernateSessionFactory.java
testLogin.javahibernate.cfg.xml
struts.xml引入对应的jar包
JUnit测试代码:测试代码运行正常,可以正常存入数据库。
@Test
public void loginTest() {
try{
User u = new User();
u.setUsername("user03");
u.setPassword("123456");
u.setState(1);
u.setState_explain("无"); Session session = com.xxl.util.HibernateSessionFactory.getSession();
Transaction ts=session.beginTransaction();
session.save(u);
ts.commit();
com.xxl.util.HibernateSessionFactory.closeSession(); }catch(Exception e){
e.printStackTrace();
}
}UserAction.java代码:这是struts的Action代码,可以正常接收参数,不调用dao的方法的时候可以正常进行逻辑,调用dao,通过HibernateSessionFactory.java类获取session的时候出错。
package com.xxl.action;import java.util.Map;import org.hibernate.Session;
import org.hibernate.Transaction;import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xxl.dao.i.IUserDAO;
import com.xxl.dao.impl.UserDAOImpl;
import com.xxl.model.User;public class UserAction extends ActionSupport{
private User user;
public String test(){
if("user".equals(user.getUsername())){
return SUCCESS;
}else{
return ERROR;
}
}
public String login(){
IUserDAO dao = new UserDAOImpl();
System.out.println("接收参数:"+user.getUsername()+user.getPassword());
User s_user = null;
try {
s_user = dao.login(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(s_user!=null){
//如果不为空,保存到Session中
//Map session=(Map)ActionContext.getContext().getSession();
//session.put("user1", user);
System.out.println("登陆完成:"+user.getState_explain());
return SUCCESS;
}else{
return ERROR;
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
UserDAOImpl.java:dao实现类[color=#FF0000][/color]
package com.xxl.dao.impl;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;import com.xxl.dao.i.IUserDAO;
import com.xxl.model.User;
import com.xxl.util.HibernateSessionFactory;public class UserDAOImpl implements IUserDAO{
public boolean add(){
System.out.println("add success !");
return true;
}
public User login(User user) {
try{
Session session = HibernateSessionFactory.getSession();
Transaction ts=session.beginTransaction();
Query query=session.createQuery("from User u where u.username=? and u.password=?");
query.setParameter(0, user.getUsername());
query.setParameter(1, user.getPassword());
query.setMaxResults(1);
User s_user=(User) query.uniqueResult();
ts.commit();
HibernateSessionFactory.closeSession();
System.out.println("查询数据库结束:"+s_user.getState_explain());
return s_user;
}catch(Exception e){
return null;
}
}
}
HibernateSessionFactory.java:获取session的类,myeclipse自动生成。package com.xxl.util;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal threadLocal = new ThreadLocal();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
} /**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}}
解决方案 »
- 消息表 和 消息类型表 用一对多的关系在多的一方(消息表)中修改type_id(消息表type_id外键) 结果会出现hibernate去修改类型表的主键的问题
- 急!!!如何让浏览器访问某个ip地址?
- 为什么我在一个模块中慢
- 单一用户单点登录
- ssh整合的问题!!
- 求助:关于用struts的标签上产生的问题,希望高手给于回答!
- 如何读出数据库中的数据并写到一个文本文件中(java社区)
- 大家好,本人想从C改用Java,有什么精典的书吗?谢谢
- 高分:jb8产生ejb的路径怎么设置???????
- 本人现由C++转为java,准备快速上手做一网管程序,给点意见,介绍一下经验心得.(集思广益)
- 大侠们 谁可不可以发一个比较新的ssh整合的jar包给我啊
- 求助:如何实现在线用户查询功能?
编译有错么