首页 \ 问答 \ Hibernate Spring集成,表正在创建,但SessionFactory不是自动装配的(Hibernate Spring Integration, Tables Are Being Created, But SessionFactory is not Autowired)

Hibernate Spring集成,表正在创建,但SessionFactory不是自动装配的(Hibernate Spring Integration, Tables Are Being Created, But SessionFactory is not Autowired)

我已经集成了Spring和Hibernate,当我使用jetty插件为maven运行我的应用程序时,Hibernate创建表但我的sessionFactory对象为null,

web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>
<!-- The definition of the Root Spring Container shared by all Servlets 
    and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value></param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,
            /WEB-INF/spring/security-context.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

servlet的context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing 
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    in the /WEB-INF/views directory -->
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.fyp.ptma" />



<beans:bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.properties" />

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />


<beans:bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"></beans:property>
    <beans:qualifier value="sessionFactory"></beans:qualifier>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.fyp.ptma.model.Application</beans:value>
            <beans:value>com.fyp.ptma.model.ApplicationVersion</beans:value>
            <beans:value>com.fyp.ptma.model.Defect</beans:value>
            <beans:value>com.fyp.ptma.model.DefectDetail</beans:value>
            <beans:value>com.fyp.ptma.model.Group</beans:value>
            <beans:value>com.fyp.ptma.model.Downloader</beans:value>
            <beans:value>com.fyp.ptma.model.Notification</beans:value>
            <beans:value>com.fyp.ptma.model.RegisterStatus</beans:value>
            <beans:value>com.fyp.ptma.model.User</beans:value>
            <beans:value>com.fyp.ptma.model.Invitation</beans:value>
            <beans:value>com.fyp.ptma.model.Installation</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>



<beans:bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>

UserDao.java

@Repository
public class UserDao implements IUserDao {

@Autowired
@Qualifier(value="sessionFactory")
private SessionFactory sessionFactory;

public Session openSession() {
    return sessionFactory.getCurrentSession();
}

public Long save(Object objToSave) throws PersistenceException,
        ConstraintViolationException {
    Session session = null;
    try {
        session = this.openSession();
        session.beginTransaction();
        session.save(objToSave);
        session.getTransaction().commit();

    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    } finally {
        // session.close();
    }

    return null;
}

public Long update(Object objToUpdate) throws PersistenceException {
    // TODO Auto-generated method stub
    return null;
}

public boolean delete(Object objToDelete) throws PersistenceException,
        ConstraintViolationException {
    // TODO Auto-generated method stub
    return false;
}

public List<Application> getAllApplications(User user)
        throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

public Application getApplication(User user) throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

public boolean authenticateLogin(User user) throws AuthenticationException,
        HibernateException {

    Session session = this.openSession();

    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", user.getEmail()));

    User userDB = (User) criteria.uniqueResult();

    return userDB.getPassword().equals(user.getPassword());

}

public User getUserByEmail(String email) throws HibernateException {
    Session session = this.openSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", email));

    User userDB = (User) criteria.uniqueResult();
    // session.close();
    return userDB;
}

}

我的控制器

@ResponseBody
@RequestMapping(value = "/processRegistration.html", method = RequestMethod.POST)
public String processRegistration(@ModelAttribute("user") User user,
        Model model, BindingResult result) {

    UserDao uDao = DaoFactory.getUserDao();
    uDao.save(user);

    return "ok";
}

当我在我的控制器中调用uDao.save时,UserDao的sessionFactory对象为null,但在初始化期间,当我尝试使用下面的线控制器时,我没有得到任何接线错误,

ApplicationContext context = new AnnotationConfigApplicationContext(“com.fyp.ptma.dao”);

它在提交表格时抛出异常:

: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I have integrated Spring and Hibernate, when i run my application using jetty plugin for maven, Hibernate creates tables but i my sessionFactory object is null,

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>
<!-- The definition of the Root Spring Container shared by all Servlets 
    and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value></param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,
            /WEB-INF/spring/security-context.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing 
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    in the /WEB-INF/views directory -->
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.fyp.ptma" />



<beans:bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.properties" />

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />


<beans:bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"></beans:property>
    <beans:qualifier value="sessionFactory"></beans:qualifier>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.fyp.ptma.model.Application</beans:value>
            <beans:value>com.fyp.ptma.model.ApplicationVersion</beans:value>
            <beans:value>com.fyp.ptma.model.Defect</beans:value>
            <beans:value>com.fyp.ptma.model.DefectDetail</beans:value>
            <beans:value>com.fyp.ptma.model.Group</beans:value>
            <beans:value>com.fyp.ptma.model.Downloader</beans:value>
            <beans:value>com.fyp.ptma.model.Notification</beans:value>
            <beans:value>com.fyp.ptma.model.RegisterStatus</beans:value>
            <beans:value>com.fyp.ptma.model.User</beans:value>
            <beans:value>com.fyp.ptma.model.Invitation</beans:value>
            <beans:value>com.fyp.ptma.model.Installation</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>



<beans:bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>

UserDao.java

@Repository
public class UserDao implements IUserDao {

@Autowired
@Qualifier(value="sessionFactory")
private SessionFactory sessionFactory;

public Session openSession() {
    return sessionFactory.getCurrentSession();
}

public Long save(Object objToSave) throws PersistenceException,
        ConstraintViolationException {
    Session session = null;
    try {
        session = this.openSession();
        session.beginTransaction();
        session.save(objToSave);
        session.getTransaction().commit();

    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    } finally {
        // session.close();
    }

    return null;
}

public Long update(Object objToUpdate) throws PersistenceException {
    // TODO Auto-generated method stub
    return null;
}

public boolean delete(Object objToDelete) throws PersistenceException,
        ConstraintViolationException {
    // TODO Auto-generated method stub
    return false;
}

public List<Application> getAllApplications(User user)
        throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

public Application getApplication(User user) throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

public boolean authenticateLogin(User user) throws AuthenticationException,
        HibernateException {

    Session session = this.openSession();

    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", user.getEmail()));

    User userDB = (User) criteria.uniqueResult();

    return userDB.getPassword().equals(user.getPassword());

}

public User getUserByEmail(String email) throws HibernateException {
    Session session = this.openSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", email));

    User userDB = (User) criteria.uniqueResult();
    // session.close();
    return userDB;
}

}

My Controller

@ResponseBody
@RequestMapping(value = "/processRegistration.html", method = RequestMethod.POST)
public String processRegistration(@ModelAttribute("user") User user,
        Model model, BindingResult result) {

    UserDao uDao = DaoFactory.getUserDao();
    uDao.save(user);

    return "ok";
}

when i call uDao.save in my controller , sessionFactory object of UserDao is null, but during initialisation i dont get any wiring error when i try my controller with below line,

ApplicationContext context = new AnnotationConfigApplicationContext("com.fyp.ptma.dao");

it throw exception while submitting form:

: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

原文:https://stackoverflow.com/questions/16861113
更新时间:2023-06-22 11:06

最满意答案

什么是例外,它是一个“空集”异常还是类似的东西?

尝试

FirstOrDefault()

代替

First()

看看会发生什么。 如果没有可用的记录,First()将抛出异常。 如果没有可用的记录,FirstOrDefault()将为您提供空的User对象。


It turns out the issue was with SQLite's handing of GUID types. If you set

BinaryGuids=True

then they are saved as 16 byte binaries and cannot be 'matched' against string based guids. You can also set that to be false and they match as strings, but you need to watch the case for the alpha chars.

相关问答

更多
  • 感谢评论,我能够发现真正的问题与我的查询。 我之前并没有意识到,库存(i)也可能为null,因此我必须检查MarketItems加入的是(不仅是ms)是否为空。 不知道这是否对任何人都有帮助,但在我遇到一些EF7 / EF6差异后,错误信息会产生误导。 var inventory = (from it in _ctx.Items join i in _ctx.Inventories on it.Id equals i.ItemId into iit ...
  • Linq使用queryProviders的概念。 查询提供程序负责将lamba表达式转换为底层数据存储上的查询。 正如Obalix在我之前所说,Linq to Entities查询提供程序将linq与lambdas转换为使用底层ado.net对象执行的真实sql。 看看这里的规范函数,它们被翻译成sql(并注意哪些不是)。 另一方面,linq to数据集针对DAtaSet基础结构工作。 正如你可能记得数据集有一些与之相关的查询。 (获取器,更新,删除,插入)与DataAdapters对象的用法。 Linq查 ...
  • 您正在查询中使用centers类。 这不是像System.String , System.Int32或System.Boolean这样的原始类型。 您必须从IEnumberable类收集lat和lng属性到数组或其他IEnumberable实现。 就像是: var centerLatitudes=(from center in centers select center.lat).toList(); var centerLongitu ...
  • 什么是例外,它是一个“空集”异常还是类似的东西? 尝试 FirstOrDefault() 代替 First() 看看会发生什么。 如果没有可用的记录,First()将抛出异常。 如果没有可用的记录,FirstOrDefault()将为您提供空的User对象。 It turns out the issue was with SQLite's handing of GUID types. If you set BinaryGuids=True then they are saved as 16 byte ...
  • LINQ to SQL将不再有未来的发展。 所以EF是未来的发展方向。 实体框架与LINQ to SQL (这应该解释你想知道什么) LINQ to SQL will have no more future development. So EF is the way to go in the future. Entity Framework vs LINQ to SQL (this should explain what you want to know)
  • 我猜MyNamespace.Widget是一个自定义类 - 而不是EDM的一部分? 如果是这样,则无法将LINQ-Entities查询投影到自定义类型中。 如果您使用POCO,无关紧要。 你有一个正确的想法投射到匿名类型。 在服务器上实现查询后,您可以在客户端上调整查询的形状: var widgets = entities .Widgets .ToList() // materialize query .Select( ...
  • 我正在使用Linq实体,并能够做到这一点: testEntities entities = new testEntities (); ObjectQuery fees = entities.Fees; return from f in fees let s = Math.Sqrt((double)f.FeeAmount) where s > 1.0 s ...
  • 我想这就是你想要的: List GetBrandsForExistingWorkflowType(string worfklowtype) { var result = db.WorkflowConfigurations .Where(x => x.WorkflowType.Name == worfklowtype) .Select(x => x.Brand); return result; } List< ...
  • 在MVC应用程序中, ObjectContext应限定为请求范围。 大多数DI容器都可以自动执行此操作 所以你不希望在方法中using块。 而是通过构造函数注入上下文或将其作为方法参数传递。 In an MVC application the ObjectContext should be scoped to the request. Most DI containers can do this automatically. So you would prefer not using a using blo ...
  • Any()根本不返回值 - 它返回一个布尔值,表示集合中是否有值。 它只显示两个值,因为您只查询CmsContents,它有两行,并且两行至少有一个类别,所以两行都在结果中。 看起来你真的喜欢: var contents = from cnt in context.CmsContents from category in cnt.CmsCategories select cnt; Any() doesn't return values at al ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)