可以直接实例化hibernate session Factory,但不能通过spring实现 [英] Can instantiate hibernate session Factory directly but cannot do it through spring

查看:84
本文介绍了可以直接实例化hibernate session Factory,但不能通过spring实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习hibernate和spring,通过一个赋值,我试图在spring中使用session工厂实例。我了解了hibernate部分,但不能继续与春天。我已经尝试了很多教程和示例,但不能让我的弹簧工作。虽然它工作时,我直接实例化它。
这里是我的项目的问题相关细节...
$ b

applicationContext.xml (在WEB-INF中)

 <?xml version =1.0encoding =UTF-8?> 
< beans xmlns =http://www.springframework.org/schema/beans
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instancexmlns :aop =http://www.springframework.org/schema/aop
xmlns:context =http://www.springframework.org/schema/context
xmlns:jee = http://www.springframework.org/schema/jeexmlns:lang =http://www.springframework.org/schema/lang
xmlns:p =http://www.springframework。 org / schema / pxmlns:tx =http://www.springframework.org/schema/tx
xmlns:util =http://www.springframework.org/schema/util
xsi:schemaLocation =http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework .org / schema / aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework。 org / schema / context / spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframewor k.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema / util http://www.springframework.org/schema/util/spring-util.xsd\">

< context:annotation-config />
< context:component-scan
base-package =com.nagarro.training.assignment6.dao.entity.Student/>



< bean id =sessionFactory
class =org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean>
< property name =configLocationvalue =classpath:hibernate.cfg.xml>< / property>
< property name =hibernateProperties>
<值>
hibernate.dialect = org.hibernate.dialect.HSQLDialect
< / value>
< / property>
< / bean>
< bean id =transactionManager
class =org.springframework.orm.hibernate3.HibernateTransactionManager>
< property name =sessionFactoryref =sessionFactory>< / property>
< / bean>
< tx:annotation-driven />

< bean id =studentDAO
class =com.nagarro.training.assignment6.dao.impl.StudentDAOImplementation>
< property name =sessionFactoryref =sessionFactory/>
< / bean>


< / beans>

修改:包含建议的更改
StudentDAOImplementaion .java (使用它的文件)

  public class StudentDAOImplementation实现StudentDAO {

/ **
*单个hibernate会话实例
* /
@Autowired
私有SessionFactory sessionFactory;

// HibernateUtil.getSessionFactory()。openSession()
$ b $ / **
* @param sessionFactory
* /
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;

$ b $ **
* @return sessionFactory
* /
public SessionFactory getSessionFactory(){
return sessionFactory;
}

private Session getSession(){
return this.sessionFactory.getCurrentSession();
}
/ **
* @返回所有学生的列表
* /
public List< Student> getStudentList(){

System.out.println(this.getSession()。getStatistics());

return(List< Student>)this.getSEssion.createQuery(from Student)
.list();
}

}

这里是我的剪辑lib文件夹中的jar文件:



我认为我不需要包含hibernate文件和bean,因为它在没有弹簧的情况下工作正常。它的春天我不能去工作。我已经尝试了许多不同的实现从网络,但我不能得到它的工作。它只是在** System.out.println(sessionFactory.getStatistics()); **在StudentDAOImplementation中表示空指针异常。


$ b 调用StudentDAO的测试类

p>

  public class Test {

public static void main(String [] args){
StudentDAOImplementation sd = new StudentDAOImplementation();

列表< Student> list = sd.getStudentList();

(Student's:list){
System.out.println(s.getName());
}
}

}



堆栈跟踪

 线程main中的异常java.lang.NullPointerException 
at StudentDAOImplementation.getStudentList(StudentDAOImplementation.java:116)
at Test.main(Test.java:13)

$ b $你的 sessionFactory 变量被错误地命名,因为该类型实际上是 Session 会话!= SessionFactory 。您在 sessionFactory.getStatistics()上获得了NPE,因为Spring无法将Session自动装入到DAO中。如果你在NPE之前没有看到错误,那么你实际上并没有用Spring实例化DAO,否则你会得到一个关于无法找到类型Session依赖的错误。使用基于Hibernate的DAO的适当方法是在你的注入中加入一个 SessionFactory ,然后调用 getCurrentSession()方法,你需要一个 Session 。请参阅基于DAO的实施在简单的Hibernate 3 API和以下关于这种方法以及设置适当的事务管理的详细信息。


$ b 更新:开第二眼,我发现你的组件扫描软件包被设置为 com.nagarro.training.assignment6.dao.entity.Student ,它看起来像一个类,而不是一个包。它甚至不接近你想要组件扫描的任何东西。也许你不明白什么是组件扫描。它涵盖在Annotation - 基于容器配置。参考指南。



更新2:关于您的测试代码:您不是完全可以使用Spring,所以你可以删除XML并为自己节省麻烦。另一方面,如果你想实际使用Spring,你需要根据所述XML文件在你的主要方法中创建一个上下文,例如:

  ApplicationContext context = new FileSystemXmlApplicationContext(locationOfXmlFile); 

然后,如果你想要一个Spring管理的DAO,你不能用。春天不是魔术。它不会控制远离你,只是因为你已经将它加载到了同一个JVM中的某个地方。*你必须向Spring请求 it 创建的DAO,如:

  StudentDAO dao = context.getBean(StudentDAO.class); 

请注意,我使用的是接口类型,而不是具体类型。由于种种原因,这总是一个明智的做法。



这是您的第一个问题。只要你这样做,你就会遇到其他配置问题。你应该发布一个新问题,如果你需要帮助解决其中的一个。



*除非你是使用AspectJ编织来注入任意对象

I have started learning hibernate and spring through an assignment in which i am trying to use session factory instance through spring. I understood the hibernate part but just cant go on with spring. I have tried numerous tutorials and examples but just cant get my spring working. Although it works when i instantiate it directly. Here are the problem related details of my project...

applicationContext.xml (inside WEB-INF)

<?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:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
<context:component-scan
    base-package="com.nagarro.training.assignment6.dao.entity.Student" />



<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.HSQLDialect
        </value>
    </property>
</bean>
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven />

<bean id="studentDAO"
    class="com.nagarro.training.assignment6.dao.impl.StudentDAOImplementation">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>


</beans>

Edit: including changes as suggested StudentDAOImplementaion.java (the file where it is being used )

public class StudentDAOImplementation implements StudentDAO {

    /**
     * single instance of hibernate session
     */
    @Autowired
    private SessionFactory sessionFactory;

    // HibernateUtil.getSessionFactory().openSession()

    /**
     * @param sessionFactory
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * @return the sessionFactory
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }
        /**
     * @return list of all the students
     */
    public List<Student> getStudentList() {

        System.out.println(this.getSession().getStatistics());

        return (List<Student>) this.getSEssion.createQuery("from Student")
                .list();
    }

}

And here is the snip of my jar files in lib folder:

I think that i dont need to include hibernate files and beans as it is working fine without spring. Its the spring i cant get to work.I have tried many different implementation from the web but i just cannot get it working. It just says null pointer exception on ** System.out.println(sessionFactory.getStatistics());** line in StudentDAOImplementation.

Test class that calls StudentDAO

public class Test {

public static void main(String[] args) {
    StudentDAOImplementation sd = new StudentDAOImplementation();

    List<Student> list = sd.getStudentList();

    for(Student s : list) {
        System.out.println(s.getName());
    }
}

}

Stack trace

Exception in thread "main" java.lang.NullPointerException
    at StudentDAOImplementation.getStudentList(StudentDAOImplementation.java:116)
    at Test.main(Test.java:13)

解决方案

Your sessionFactory variable is misleadingly named, since the type is actually Session. Session != SessionFactory. You're getting a NPE on sessionFactory.getStatistics() because there's no way that Spring can autowire a Session into a DAO like that. If you're not seeing an error before the NPE, then you're not actually instantiating the DAO with Spring, or else you'd get an error about not being able to find a dependency of type Session. The appropriate way to use a Hibernate-based DAO is to inject it with a SessionFactory and call getCurrentSession() in your methods where you need a Session. See "Implementing DAOs based on plain Hibernate 3 API" and following for details about this approach and about setting up appropriate transaction management.

Update: On a second glance, I see that the package for your component-scan is set to com.nagarro.training.assignment6.dao.entity.Student, which looks exactly like a class, not a package. It's also not even close to anything you'd actually want to component-scan. Maybe you don't understand what component-scan is for. It's covered under "Annotation-based container configuration" in the reference guide.

Update 2: About your "test" code: you're not using Spring at all, so you might as well remove the XML and save yourself the trouble. On the other hand, if you'd like to actually use Spring, you'd need to create a context in your main method based on said XML file, such as:

ApplicationContext context = new FileSystemXmlApplicationContext(locationOfXmlFile);

Then if you want a Spring-managed DAO, you can't just create one with new. Spring isn't magic. It doesn't grab control away from you just because you have it loaded somewhere in the same JVM.* You have to ask Spring for the DAO that it created, like:

StudentDAO dao = context.getBean(StudentDAO.class);

Note that I used the interface type, not the concrete type. That's always an advisable practice for numerous reasons.

This (not starting Spring) is your first problem. As soon as you do this, you're going to run into other problems with your configuration. You should post a new question if you need help solving one of them.

*Unless you're using AspectJ weaving to inject arbitrary objects.

这篇关于可以直接实例化hibernate session Factory,但不能通过spring实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆