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
最满意答案
什么是例外,它是一个“空集”异常还是类似的东西?
尝试
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.
相关问答
更多-
EF Core Linq加入多个列会引发NullReference异常(EF Core Linq join on multiple columns throws NullReference Exception)[2021-08-10]
感谢评论,我能够发现真正的问题与我的查询。 我之前并没有意识到,库存(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到LIN的数据集子集是EF还是这两个是独立的?(Is LINQ to Dataset subset of LINQ to EF or these two are independent?)[2022-06-14]
Linq使用queryProviders的概念。 查询提供程序负责将lamba表达式转换为底层数据存储上的查询。 正如Obalix在我之前所说,Linq to Entities查询提供程序将linq与lambdas转换为使用底层ado.net对象执行的真实sql。 看看这里的规范函数,它们被翻译成sql(并注意哪些不是)。 另一方面,linq to数据集针对DAtaSet基础结构工作。 正如你可能记得数据集有一些与之相关的查询。 (获取器,更新,删除,插入)与DataAdapters对象的用法。 Linq查 ... -
EF Linq将数组加入表(EF Linq Join an Array to Table)[2023-05-05]
您正在查询中使用centers类。 这不是像System.String , System.Int32或System.Boolean这样的原始类型。 您必须从IEnumberable类收集lat和lng属性到数组或其他IEnumberable 实现。 就像是: var centerLatitudes=(from center in centers select center.lat).toList(); var centerLongitu ... -
LINQ to EF中的“First”操作出现意外异常(Unexpected exception with the 'First' operation in LINQ to EF)[2022-10-14]
什么是例外,它是一个“空集”异常还是类似的东西? 尝试 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 EF查询中使用SQRT(Using SQRT in a Linq EF Query)[2021-10-17]
我正在使用Linq实体,并能够做到这一点: testEntities entities = new testEntities (); ObjectQueryfees = entities.Fees; return from f in fees let s = Math.Sqrt((double)f.FeeAmount) where s > 1.0 s ... -
复杂的LINQ或EF查询(Complex LINQ or EF query)[2024-02-07]
我想这就是你想要的: ListGetBrandsForExistingWorkflowType(string worfklowtype) { var result = db.WorkflowConfigurations .Where(x => x.WorkflowType.Name == worfklowtype) .Select(x => x.Brand); return result; } List< ... -
使用EF的常见LINQ方法(Common LINQ method using EF)[2023-09-30]
在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 ... -
Linq和EF on .Any()(Linq and EF on .Any())[2023-03-22]
Any()根本不返回值 - 它返回一个布尔值,表示集合中是否有值。 它只显示两个值,因为您只查询CmsContents,它有两行,并且两行至少有一个类别,所以两行都在结果中。 看起来你真的喜欢: var contents = from cnt in context.CmsContents from category in cnt.CmsCategories select cnt; Any() doesn't return values at al ...