hibernate获取session报空指针

Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); 报空指针,是获取CurrentSession的时候报的,我该怎么办啊

3个回答

你可以先使用opensession()方法试一下可以不

yanghang888888
yanghang888888 回复yanghang888888:简直要疯了
接近 3 年之前 回复
yanghang888888
yanghang888888 回复fcfwang_net: 配置文件没问题 ,,我调别的方法好使,调我这个就不好使 ,就报空指针
接近 3 年之前 回复
fcfwang_net
fcfwang_net 回复yanghang888888: 那你需要检查一下你的配置文件,如果session拿不到,可能是你的sessionfactory没有session,建议你使用debug看一下
接近 3 年之前 回复
yanghang888888
yanghang888888 这个我试过了 不好使 在网上查的 然后实验的 不好使 还有别的办法吗
接近 3 年之前 回复

getHibernateTemplate().getSessionFactory().getCurrentSession();

题主这句要好分开写,,,写得多了,,错误不好定位,,分开写,,看是getHibernateTemplate(),,,没获取到,,还是getSessionFactory()这个没获取到

yanghang888888
yanghang888888 我项目里面是分来着写 的 ,,,是getSessionFactory()没有获取到 然后再调用的时候就报空指针了
接近 3 年之前 回复

调用的方法没有事务,getCurrentSession();这个方法是从事务中获取session的。你配置文件没有配置事务,或者事务没有覆盖到该调用方法。如果支持注解,试着在方法上加@transactional。然后在试试

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

hibernate数据库操作,总是报空指针异常

if (user.getUsername().length() > 0) { String hql = "select * from user where username = : username "; query = ses.createQuery(hql); //这一行总是报错,是不是查不到数据库有东西 query.setParameter("username",username); List User rt = query.list(); if(rt!=null){ req.setAttribute("register_error", "用户已经注册了!"); return "error"; } }

hibernate多对一提示空指针的问题

创建了product和factory两个实体类,字段什么的和数据库的都是一样的,配置文件如下:product.hbm.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "com.pansoft.entity.Product" table = "product"> <id name="id" type = "int" column="id" > <generator class="native"></generator> </id> <property name="name" type = "string" length="255"> <column name="name"></column> </property> <property name="price" type = "double"> <column name="price"></column> </property> <many-to-one name="factory" class="com.pansoft.entity.Factory"> <column name="factoryid"></column> </many-to-one> </class> </hibernate-mapping> factory.hbm.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name = "com.pansoft.entity.Factory" table="factory"> <id name = "factoryid" type = "int" column="factoryid"> <generator class="native"> </generator> </id> <property name="name" type = "string"> <column name="name"></column> </property> </class> </hibernate-mapping> 操作查询: try { Session session = Hibernateutils.getSession(); session.beginTransaction(); Product product = (Product)session.get(Product.class, new Integer(1)); if(product == null) { System.out.println("111"); } else { System.out.println(product.getName()); session.getTransaction().commit(); } } catch (Exception e) { // TODO 自动生成的 catch 块 System.out.println("错误"); e.printStackTrace(); } 之后控制台就输出: log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Hibernate: select product0_.id as id0_0_, product0_.name as name0_0_, product0_.price as price0_0_, product0_.factoryid as factoryid0_0_ from product product0_ where product0_.id=? 111

getSession出现空指针异常

ActionContext.getContext().getSession();直接报空指针异常 查资料好像是说session必须在Action里使用,因为我是做串口监听,查到数据准备保存到session里,所以报错了(ActionContext.getContext().getSession().put("screwObj",screwObj);报错),screwObj对象有值。 有大神知道具体是什么原因吗?要怎样弄才能存到session? 我是想把获取到的数据显示到页面上,准备用轮询读取session的值,有其它方法传值也行啊!!!

Hibernate获取session问题

今天无意中发现用hibernate整合struts2,当app启动的时候session无法获取,报出了org.hibernate.HibernateException: JDBC Driver class not found: oracle.jdbc.driver.OracleDriver 这个错误,但是我的WEBINF中的lib目录里面确实存在oracle的classes12的工具包,而且当我在dao里面写一个测试方法单独运行java程序的时候,可以获取到session,为什么通过web启动的时候是空指针啊??高手大大们麻烦解析下

空指针的异常没有找出来,求解

1. package com.bjsxt.utils; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.metamodel.source.annotations.entity.ConfiguredClass; import org.omg.CORBA.PRIVATE_MEMBER; import oracle.net.aso.f; public class HibernateUtil { private static String HIBERNATE_CONFIG_FILE = "hibernate.cfg.xml"; private static SessionFactory sessionFactory = null; private static ThreadLocal<Session> tl = new ThreadLocal<>(); private static Configuration configure = null; static{ try { configure = new Configuration().configure("HIBERNATE_CONFIG_FILE"); } catch (Exception e) { e.printStackTrace(); System.out.println("核心装置安装失败"); } try { sessionFactory = configure.buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); System.out.println("C区以安放!"); } } private HibernateUtil(){ } /** * 获取session * @return */ public static Session getsession(){ Session session = tl.get(); if(session == null){ session = sessionFactory.openSession();----这块是报异常的地方 tl.set(session); } return session; } /** * 关闭session */ public static void closeSession(){ Session session = tl.get(); tl.set(null); if(session != null){ session.close(); } } } 2.![图片说明](https://img-ask.csdn.net/upload/201708/24/1503555931_523098.png) 3.![图片说明](https://img-ask.csdn.net/upload/201708/24/1503555952_89058.png) 不知道哪里来的空指针异常求解 发现问题了,就是sessionFactory是null,说是hibernate.cfg.xml没有用到,这是怎么回事? The value of the field HibernateUtil.HIBERNATE_CONFIG_FILE is not used。。怎么改?

SpringContextUtil.getBean获取的类,没有hibernate的session

背景 一个任务, 需要开启多个线程,同时跑, 我开启的线程中, 用SpringContextUtil.getBean("")获取了一个service类, 这个service中, 有许多的service和dao 用来处理任务 在这个处理方法中, Transaction trans = this.creditchanneldao.getCSession().getTransaction(); 通过提取出事务控制,来进行每个线程的独立事务控制 但是,抛异常 No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

Action类ActionContext.getContext().getSession()报空指针

其他的Action类用ActionContext.getContext().getSession()都没错,为什么在这个Action类里总报空指针?一去掉这句就正常。 严重: Servlet.service() for servlet jsp threw exception java.lang.NullPointerException at com.accp.oa.actions.TreeAction$3.nodeSelected(TreeAction.java:94) at com.jenkov.prizetags.tree.impl.Tree.notifySelectListeners(Tree.java:668) at com.jenkov.prizetags.tree.impl.Tree.select(Tree.java:340) at com.jenkov.prizetags.tree.impl.Tree.select(Tree.java:351) at com.jenkov.prizetags.tree.impl.TreeUpdater.selectUnselectNodes(TreeUpdater.java:280) at com.jenkov.prizetags.tree.impl.TreeUpdater.update(TreeUpdater.java:122) at com.jenkov.prizetags.tree.impl.TreeTag.doStartTag(TreeTag.java:242) 这个Action报错:public class TreeAction extends ActionSupport implements java.io.Serializable {} [img]http://dl.iteye.com/upload/attachment/578092/ea3f3109-f090-341c-931f-d66bb4cbe6fa.png[/img]

hibernate进行分页时,sessionFactory为null报空指针异常

从网上查了许都,都没能解决,不知道是配置文件有问题,还是方法写的有问题

用Hibernate映射mysql问题(Timestamp)

我知道这个是个常见问题,我已经看了论坛帖子和查阅相关资料,始终没找到好的解决方法,如果有空的帮解答下吧。 SessionInfo.hbm.xml [code="java"]<hibernate-mapping package="domaininvestment.model"> <class name="SessionInfo" table="SessionInfo"> <id name="id"> <generator class="native" /> </id> <property name="email" type="string" length="500" not-null="true" /> <property name="sessionID" type="string" length="200" /> <property name="clientIP" type="string" length="200" not-null="true" /> <property name="creationTime" type="timestamp" not-null="true" /> </class> </hibernate-mapping>[/code] SessionInfoDao.java [code="java"]public boolean sessionInfoExists(SessionInfo info) throws RuntimeException { if (info == null) { return false; } Session sess = DaoBase.currentSession(); try { String infoEmail = info.getEmail(); String infoClientIP = info.getClientIP(); Date infoCreationTime = info.getCreationTime(); if (infoEmail == null || infoClientIP == null || infoCreationTime == null) { return false; } int diff = Util.diffDays(new Date(), infoCreationTime); if (diff < 0 || diff > SessionInfo.COOKIE_MAX_DAYS) { return false; } Query q = sess.createQuery("from SessionInfo where email = :email and clientIP = :clientIP and creationTime =:creationTime") .setString("email", infoEmail) .setString("clientIP", infoClientIP) .setStrng("creationTime", infoCreationTime); Iterator itr = q.iterate(); if (itr.hasNext()) { return true; } else { return false; } } finally { DaoBase.closeSession(); }[/code] SessionInfoDaoTest.java [code="java"]@Test public void testSessionInfoExists() { SessionInfo info = null; assertFalse(dao.sessionInfoExists(info)); info = new SessionInfo(); assertFalse(dao.sessionInfoExists(info)); info.setEmail("test@dc.com"); assertFalse(dao.sessionInfoExists(info)); info.setSessionID("123456"); assertFalse(dao.sessionInfoExists(info)); info.setClientIP("192.168.1.1"); assertFalse(dao.sessionInfoExists(info)); info.setCreationTime(new Date()); assertFalse(dao.sessionInfoExists(info)); info = new SessionInfo(); info.setEmail("test@dc.com"); info.setClientIP("192.168.1.1"); info.setCreationTime(new Date()); Session sess = reopenSession(); sess.save(info); sess.flush(); closeSession(); assertTrue(dao.sessionInfoExists(info)); }[/code] 这里主要是timeStamp的问题,如果我把hql里面的creationTime去掉,即:"from SessionInfo where email = :email and clientIP = :clientIP " 我的测试就没问题,我把它加上后即使转成sqlDate也没用,不知道问题出在哪里?

Struts2中的HttpServletRequest request=ServletActionContext.getRequest()报空指针异常

Struts2中的HttpServletRequest request=ServletActionContext.getRequest()报空指针异常 ![图片说明](https://img-ask.csdn.net/upload/201901/07/1546854089_111821.jpg) ![图片说明](https://img-ask.csdn.net/upload/201901/07/1546854095_238267.jpg)

Hibernate4 获取sessionFactory出错

利用 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()) .buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); 空指针异常 hibernate.cfg.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置连接数据库的基本信息 --> <property name="connection.username">zy</property> <property name="connection.password">123456</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property> <!-- 配置 hibernate 的基本信息 --> <!-- hibernate 所使用的数据库方言 --> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <!-- 执行操作时是否在控制台打印 SQL --> <property name="show_sql">true</property> <!-- 是否对 SQL 进行格式化 --> <property name="format_sql">true</property> <!-- 指定自动生成数据表的策略 --> <property name="hbm2ddl.auto">update</property> <!-- 指定关联的 .hbm.xml 文件 --> <mapping resource="com/zy/hibernate/News.hbm.xml"/> </session-factory> </hibernate-configuration> ``` News.hbm.xml ``` <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.zy.hibernate"> <class name="News" table="NEWS2"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <!-- 指定主键的生成方式, native: 使用数据库本地方式 --> <generator class="sequence"> <param name="sequence">news2_seq</param> </generator> </id> <property name="title" type="java.lang.String"> <column name="TITLE" /> </property> <property name="author" type="java.lang.String"> <column name="AUTHOR" /> </property> <property name="date" type="java.util.Date"> <column name="DATE" /> </property> </class> </hibernate-mapping> ```

关于hibernate 事务提交的问题

近期做项目,遇到了一个问题,用hibernate做数据持久化,可是有的业务逻辑要求是这样的,三张表是独立的。 如何将三张表的增删改放到一个事务里面? 比如:我先保存一个新的人员信息。然后再查询出保存完之后的人员信息同时要update另外一张表里面。 问题就是:session.save(obj) 之后再查询的话。这个对象还是游离状态。会查询不到。 所以就不能后面的update操作

仅仅只用mybatis框架操作数据库 设置懒加载后报错:创建延时代理出错,空指针异常

如果不设置懒加载,数据能读出来, 设置懒加载后,报错 Cause: org.apache.ibatis.executor.ExecutorException: Error creating lazy proxy. Cause: java.lang.NullPointerException mybatis版本3.46 配置文件 Order <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.gyf.mapper.OrderMapper"> <!-- ============= 懒加载 ==================--> <resultMap id="orderLazyloadingRslMap" type="orders"> <id column="id" property="id"/> <id column="user_id" property="user_id"></id> <result column="note" property="note"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <!--配置查询--> <association property="user" javaType="com.gyf.model.User" select="com.gyf.mapper.UserMapper.findUserById" column="user_id"/> </resultMap> <select id="findOrderAndUserByLazyloading" resultMap="orderLazyloadingRslMap"> SELECT * FROM orders </select> </mapper> 配置文件 User <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.gyf.mapper.UserMapper"> <select id="findUserById" parameterType="int" resultType="user"> SELECT * FROM user WHERE id = #{id} </select> </mapper> sqlMapConfig: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.properties"/> <!--配置允许懒加载--> <settings> <setting name="lazyLoadingEnabled" value="true"/> </settings> <!--配置别名--> <typeAliases> <!--指定包名,别名就是类名,第一个小写 User 别名就是user--> <package name="com.gyf.model"></package> <package name="com.gyf.vo"></package> </typeAliases> <!-- 配置mybatis的环境信息 --> <environments default="development"> <environment id="development"> <!-- 配置JDBC事务控制,由mybatis进行管理 --> <transactionManager type="JDBC"></transactionManager> <!-- 配置数据源,采用dbcp连接池 --> <dataSource type="POOLED"> <property name="driver" value="${driverClass}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!--mybatis加载映射文件--> <mappers> <package name="com.gyf.mapper"></package> </mappers> </configuration> 模型: public class Orders { private Integer id; private Integer user_id; private String note;//备注 private String number; private Date createtime;//写意的创建时间 private User user;//定单所属的用户 public User getUser() { return user; } public void setUser(User user) { this.user = user; } ....get 和 set 方法 } public class User implements Serializable { private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 ....get 和 set 方法 } 测试 public class Demo01 { SqlSession session; @Before public void before() throws IOException { System.out.println("before.....获取session"); // a)读取配置文件; InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml"); //b)通过SqlSessionFactoryBuilder创建SqlSessionFactory会话工厂。 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); session = sessionFactory.openSession(); } @After public void after(){ session.close(); } /** * 懒加载 * @throws IOException */ @Test public void test10() throws IOException { OrderMapper mapper = session.getMapper(OrderMapper.class); List<Orders> list = mapper.findOrderAndUserByLazyloading(); for (Orders order : list){ System.out.println("订单信息:"); System.out.println(order); System.out.println("订单所属的客户:"); System.out.println(order.getUser()); } } }

运行getHibernateTemplate().save(xxx)时报错等问题 两天了坐等

2015-7-25 18:29:33 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [RegisterServlet] in context with path [/FirstHRD1] threw exception java.lang.NullPointerException at com.reitgn.dao.impl.AdvancedRegistrationDaoImpl.addAdvancedRegistration(AdvancedRegistrationDaoImpl.java:34) at com.reitgn.service.impl.AdvanceRegistrationServiceImpl.addAdvancedRegistration(AdvanceRegistrationServiceImpl.java:34) at com.reitgn.servlet.RegisterServlet.doPost(RegisterServlet.java:71) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:662) 我的想法: Hibernate:DaoImpl类继承HibernateDaoSupport,使用getHibernateTemplate()或者Session操作数据。 Spring:加进去什么都不干,就是使用C3P0。 Servlet:控制等等。 帮忙看看我的applicationContext.xml对不对: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="jdbc:mysql://localhost:3306/firsthrd"> </property> <property name="username" value="root"></property> <property name="password" value="518wsgtc"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> <property name="mappingResources"> <list> <value>com/reitgn/entity/AdvancedRegistration.hbm.xml</value> <value>com/reitgn/entity/CurrentWorkUnit.hbm.xml</value> <value>com/reitgn/entity/ChinaQualification.hbm.xml</value> <value>com/reitgn/entity/InternationalQualification.hbm.xml</value> <value>com/reitgn/entity/Recommended.hbm.xml</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <!-- 支持当前事务,如果执行到save开头的任何方法时没有事务则开启一个事务 这是最常见的方式 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="revise*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <!-- 支持当前事务,如果当前没有事务,就以非事务方式执行。只读 --> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="productServiceMethods" expression="execution(* com.reitgn.service.impl.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods" /> </aop:config> </beans> 目录结构: ![图片说明](https://img-ask.csdn.net/upload/201507/25/1437820498_272835.png)

急,高手请进,有关Spring的问题!

我的项目是S2SH整合的,有两配置文件hibernate.reveng.xml和applicationContext.xml(Spring管理的配置,数据库在这个文件里部署的),但是我需要写一个工具类,需要获取到SessionFactory和Session;问题来了,在工具类中不能简单的获取到spring实例化的SessionFactory,不在其管理的范围内,于是我通过获取<bean>的方式 WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); wac.getBean("sessionFactory"); 这样出来还是空指针;于是我又 Configuration config=new Configuration().configure(); SessionFactory factory=config.buildSessionFactory(); 这样因为不是hibernate.cfg.xml配置的方式,所以还是不成功获取到。 请问各位高手是不是我的做法或写法有错,还有其他方式可以获取到session吗? !!!!!!!!!!!!!!!

使用Criteria.list( )赋值给list,list值为空,这是什么原因?

``` public List search(User condition) { List list=null; Session session=sessionFactory.getCurrentSession(); Transaction tx=session.beginTransaction(); try { Criteria c=session.createCriteria(User.class); Example example=Example.create(condition); c.add(example); list=c.list(); tx.commit(); } catch (Exception e) { tx.rollback(); } return list; } ``` 以上的几个步都没问题,就到了list=c.list(); , c.list是有值得,然后赋值给list,list值还是为空,这是原因啊?

ssh注解,获取不到server。

web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>sshTest1</display-name> <!-- 配置Spring的监听器,用于初始化ApplicationContext对象 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <!-- 自动扫描action --> <init-param> <param-name>actionPackages</param-name> <param-value>com.lovo</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!--建立数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <!-- SQL Server数据驱动 --> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property> <!-- 数据库地址 --> <property name="url" value="jdbc:sqlserver://localhost:1433; DatabaseName=sshTest"> </property> <property name="username" value="sa"></property> <property name="password" value="123"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <!--配置Hibernate的方言--> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <!--格式化输出sql语句--> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_sql_comments">false</prop> </props> </property> <!--自动扫描实体 --> <property name="packagesToScan" value="com.lovo.*" /> </bean> <!-- 使用 annotation --> <context:annotation-config /> <!-- 自动扫描与装配bean --> <context:component-scan base-package="com.lovo"></context:component-scan> <!-- 采用注释的方式配置 aop --> <aop:aspectj-autoproxy /> <!-- 用注解来实现事务管理 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager"/> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" read-only="true"/> <tx:method name="get*" read-only="true"/> <tx:method name="load*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="query*" read-only="true"/> <tx:method name="read*" read-only="true"/> <tx:method name="sync*"/> <tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/> </tx:attributes> </tx:advice> </beans> struts.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 开启使用开发模式,详细错误提示 --> <constant name="struts.devMode" value="true" /> <!-- 将对象交给spring管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- 指定资源编码类型 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 指定每次请求到达,重新加载资源文件 --> <constant name="struts.i18n.reload" value="false" /> <!-- 指定每次配置文件更改后,自动重新加载 --> <constant name="struts.configuration.xml.reload" value="false" /> <!-- 默认后缀名 --> <constant name="struts.action.extension" value="action," /> </struts> action package com.lovo.action; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.springframework.stereotype.Controller; import com.lovo.bean.Emp; import com.lovo.service.EmpService; import com.opensymphony.xwork2.ActionSupport; @Namespace("/") @ParentPackage("struts-default") @Controller public class EmpAction extends ActionSupport { @Resource() public Emp emp ; private EmpService empService ; @ Action(value = "empAction", results = { @Result(name = "success", location = "/index.jsp"), @Result(name = "index", location = "/login.jsp")}) public String add() { try { empService.add(emp); } catch (Exception e) { e.printStackTrace(); return "index"; } return "success"; } public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } public EmpService getEmpService() { return empService; } public void setEmpService(EmpService empService) { this.empService = empService; } } bean package com.lovo.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name="t_emp") public class Emp implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = "pk_name") private String name; @Column(name = "fk_age") private int age; public Emp(){} public Emp(int id, String name, int age) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } dao package com.lovo.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import com.lovo.bean.Emp; @Repository("empDao") public class EmpDao { @Resource(name="sessionFactory") private SessionFactory sessionFactory; public void add(Emp emp){ Session session = sessionFactory.getCurrentSession(); session.save(emp); } public List findAll(){ return null; } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } } package com.lovo.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.lovo.bean.Emp; import com.lovo.dao.EmpDao; @Service("empService") @Transactional public class EmpService { @Resource(name="empDao") private EmpDao empDao; public EmpService(){} public void add(Emp emp) { empDao.add(emp); } public EmpDao getEmpDao() { return empDao; } public void setEmpDao(EmpDao empDao) { this.empDao = empDao; } } action 访问server的时候,没有访问到server获取数据报空指针异常。 高手帮我看看哪里错了。 。。

Spring注入失败,但是getBean();却可以使用

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:jboss/PostgresDS"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="packagesToScan" value="com.cn.Jpa"> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <!-- 依赖注入上面定义的sessionFactory --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <!-- 依赖注入上面定义的事务管理器transactionManager --> <property name="transactionManager" ref="transactionManager" /> <!-- 定义需要进行事务拦截的方法及所采用的事务控制类型 --> <property name="transactionAttributes"> <props> <!-- 以browse、list、load、get及is开头的所有方法采用只读型事务控制类型 --> <prop key="browse*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="is*">PROPAGATION_REQUIRED,readOnly</prop> <!-- 所有方法均进行事务控制,如果当前没有事务,则新建一个事务 --> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <!-- 定义BeanNameAutoProxyCreatorf进行Spring的事务处理 --> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <!-- 针对指定的bean自动生成业务代理 --> <property name="beanNames"> <list> <value>HibernateManDao</value> <value>LoginResource</value> </list> </property> <!-- 这个属性为true时,表示被代理的是目标类本身而不是目标类的接口 --> <property name="proxyTargetClass"> <value>true</value> </property> <!-- 依赖注入上面定义的事务拦截器transactionInterceptor --> <property name="interceptorNames"> <list> <value>transactionInterceptor</value> </list> </property> </bean> <bean id="dao" class="com.cn.persistent.HibernateManDao"> <!-- <constructor-arg index="0" ref="sessionFactory" /> --> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> <property name="session"><null/></property> </bean> <bean id="servlet" class="com.cn.servlet.LoginResource" scope="prototype"> <property name="md"> <ref bean="dao"/> </property> <!-- <constructor-arg index="0" ref= "dao"/> --> </bean> </beans>

c3p0 连接不释放 请路过的大神过来看看

配置文件如下 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <!-- 打开Spring的Annotation支持 --> <!-- 设定Spring 去哪些包中找Annotation --> <context:component-scan base-package="com.myd" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${jdbcUrl}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <!-- 配置连接池的初始值 --> <property name="acquireIncrement" value="${acquireIncrement}" /> <property name="maxPoolSize" value="${maxPoolSize}" /> <property name="minPoolSize" value="${minPoolSize}" /> <property name="initialPoolSize" value="${initialPoolSize}" /> <property name="maxIdleTime" value="${maxIdleTime}" /> <property name="checkoutTimeout" value="${checkoutTimeout}" /> <property name="autoCommitOnClose" value="${autoCommitOnClose}"></property> <property name="acquireRetryDelay" value="${acquireRetryDelay}" /> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"></property> <property name="maxStatements" value="${maxStatements}"></property> <property name="numHelperThreads" value="${numHelperThreads}"></property> </bean> <!-- 导入src目录下的c3p0.properties文件 --> <context:property-placeholder location="classpath:c3p0.properties" /> <!--创建Spring的SessionFactory工厂 --> <!-- 如果使用的是Annotation的方式,不能使用LocalSessionFactoryBean,而应该使用 org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 设置Spring取那个包中查找相应的实体类 --> <property name="packagesToScan"> <value>com.myd.entity</value> </property> <property name="hibernateProperties"> <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="jdbc.use_scrollable_resultset">false</prop> <prop key="hibernate.connection.release_mode">after_statement</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.c3p0.idle_test_period">30</prop> <prop key="hibernate.c3p0.timeout">30</prop> <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop> </props> </property> </bean> <!-- 开启HibernateTemplate,并且为其注入SessionFactory 使用HibernateTemplate不太方便的就是要获取session得通过getSessionFactory()方法获取 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置Spring的事务处理 --> <!-- 创建事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 设置pointCut表示哪些方法要加入事务处理 --> <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 --> <aop:pointcut id="allMethods" expression="execution(* com.myd.service.*.*(..))" /> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> </aop:config> <!-- 配置哪些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:method name="*" propagation="REQUIRED" read-only="true" /> <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="5" /> <property name="maxPoolSize" value="50" /> <property name="queueCapacity" value="1000" /> <property name="keepAliveSeconds" value="60" /> </bean> </beans> 这是事务 package com.myd.dao.impl; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.myd.dao.BaseDao; /** * 可以考虑把所有公共的方法都写在baseDAo中,让所有的DAO都继承BaseDao * 这样基本上就实现了大量的基础方法,如果DAO中有逻辑处理特殊的方法,再在具体的实现类中的DAO中创建 * * @author Administrator * * @param <T> */ @Repository("baseDaoImpl") public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> { /** * 此处不能使用setSessionFactory注入,因为setSessionFactory在HibernateDaoSupport * 中已经定义了而且还是final的,不能被覆盖 * * @param sessionFactory */ @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } /** * 创建Class的对象来获取泛型的class */ private Class<Object> clz; @SuppressWarnings("unchecked") public Class<Object> getClz() { if (clz == null) { // 获取泛型的Class对象 clz = (Class<Object>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } return clz; } public void add(T t) { getHibernateTemplate().getSessionFactory().openSession(); getHibernateTemplate().save(t); getHibernateTemplate().getSessionFactory().close(); } public void delete(int id) { getHibernateTemplate().getSessionFactory().openSession(); getHibernateTemplate().delete(load(id)); getHibernateTemplate().getSessionFactory().close(); } @SuppressWarnings("deprecation") public void update(T t) { try { getHibernateTemplate().getSessionFactory().openSession() .connection().prepareStatement("SET SQL_SAFE_UPDATES=0") .execute(); } catch (DataAccessResourceFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } getHibernateTemplate().update(t); getHibernateTemplate().getSessionFactory().close(); } 现在的问题是 运行一段时间后,就卡起, 不是报连接数据库关闭 就是 返回空指针 查了以下是连接未释放导致的,我想请教下各位大神 我这样连接没关闭并回到连接池吗?

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c#跨线程停止timer c#批量写入sql数据库 c# 自动安装浏览器 c#语言基础考试题 c# 偏移量打印是什么 c# 绘制曲线图 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行
立即提问