- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试在我的 DAO 类中使用 spring 5 Autowiring hibernate 5 session 工厂 bean。也许有人可以在这里看到我的错误?尝试使用 Hibernate 4、EntityManagerFactory 但每次都毫无希望。配置类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"webApp"})
@EnableTransactionManagement
@PropertySource("classpath:props.dbProps.properties")
public class WebConfig implements WebMvcConfigurer {
private static final String DRIVER = "driver";
private static final String URL = "url";
private static final String USER_NAME = "name";
private static final String PASSWORD = "pass";
private static final String SCAN = "packages";
private static final String DIALECT = "dialect";
private static final String SHOW_SQL = "showSql";
private static final String HBM2DLL = "hbm2dll";
@Resource
private Environment env;
@Bean
public ViewResolver viewResolver(SpringTemplateEngine engine){
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(engine);
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver){
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
return engine;
}
@Bean
public SpringResourceTemplateResolver templateResolver(){
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
@Bean
public MultipartResolver multipartResolver(){
return new StandardServletMultipartResolver();
}
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(DRIVER));
dataSource.setUrl(env.getRequiredProperty(URL));
dataSource.setUsername(env.getRequiredProperty(USER_NAME));
dataSource.setPassword(env.getRequiredProperty(PASSWORD));
return dataSource;
}
@Bean
public LocalSessionFactoryBean getSessionFactory(){
final LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setDataSource(dataSource());
lsfb.setPackagesToScan(env.getRequiredProperty(SCAN));
lsfb.setHibernateProperties(hibProps());
return lsfb;
}
@Bean
public PlatformTransactionManager transactionManager(){
HibernateTransactionManager tx = new HibernateTransactionManager();
tx.setSessionFactory(getSessionFactory().getObject());
return tx;
}
private Properties hibProps(){
Properties p = new Properties();
p.put(DIALECT, env.getRequiredProperty(DIALECT));
p.put(SHOW_SQL, env.getRequiredProperty(SHOW_SQL));
p.put(HBM2DLL, env.getRequiredProperty(HBM2DLL));
return p;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(!registry.hasMappingForPattern("/static/**")){
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
}
尝试通过构造函数和 setter Autowiring - 没有任何帮助。DAO 类:
package webApp.data;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import webApp.model.Human;
import java.util.List;
@org.springframework.stereotype.Repository
public class HumanRepositoryImpl implements Repository<Human> {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public Human get(long id) {
Human result = (Human)getSession().get(Human.class, id);
return result;
}
@Override
public Human getByName(String name) {
Human result = (Human) getSession().createQuery("from human where name = '" + name + "'");
return result;
}
@Override
public void set(Human value) {
getSession().save(value);
}
@Override
public void update(Human value) {
Human forUpdate = get(value.getId());
forUpdate.setFirstName(value.getFirstName());
forUpdate.setLastName(value.getLastName());
forUpdate.setUsername(value.getUsername());
forUpdate.setEmail(value.getEmail());
forUpdate.setPassword(value.getPassword());
getSession().update(forUpdate);
}
@Override
public void delete(Human value) {
Human forDelete = get(value.getId());
if(forDelete != null)
getSession().delete(forDelete);
}
@Override
@SuppressWarnings("unchecked")
public List<Human> list() {
return getSession().createQuery("from human").list();
}
}
依赖项:Spring 5.0.2.Release、Hibernate 5.2.12.Final
Exception Stack Trace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'humanRepositoryImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:890)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:532)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:853)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:344)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1514)
at org.eclipse.jetty.maven.plugin.JettyWebAppContext.startWebapp(JettyWebAppContext.java:359)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1476)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:785)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:261)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
at org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:434)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:113)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:167)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:113)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
at org.eclipse.jetty.server.Server.start(Server.java:449)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:105)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.server.Server.doStart(Server.java:416)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:467)
at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:333)
at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:180)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1504)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
... 68 more
最佳答案
我认为将 @EnableWebMvc 与 @EnableTransactionManagement 混合在一起不是一个好的设计。您应该在 WebConfig 类的同一包中为 Hibernate 配置清除一个单独的类。删除以下代码。
@EnableTransactionManagement
@PropertySource("classpath:props.dbProps.properties")
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(DRIVER));
dataSource.setUrl(env.getRequiredProperty(URL));
dataSource.setUsername(env.getRequiredProperty(USER_NAME));
dataSource.setPassword(env.getRequiredProperty(PASSWORD));
return dataSource;
}
@Bean
public LocalSessionFactoryBean getSessionFactory(){
final LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
lsfb.setDataSource(dataSource());
lsfb.setPackagesToScan(env.getRequiredProperty(SCAN));
lsfb.setHibernateProperties(hibProps());
return lsfb;
}
@Bean
public PlatformTransactionManager transactionManager(){
HibernateTransactionManager tx = new HibernateTransactionManager();
tx.setSessionFactory(getSessionFactory().getObject());
return tx;
}
private Properties hibProps(){
Properties p = new Properties();
p.put(DIALECT, env.getRequiredProperty(DIALECT));
p.put(SHOW_SQL, env.getRequiredProperty(SHOW_SQL));
p.put(HBM2DLL, env.getRequiredProperty(HBM2DLL));
return p;
}
清除一个单独的类,如下所示。我已经为 Hibernate xml 配置编写了代码,您也可以配置属性文件。另外,您还没有在 LocalSessionFactoryBean 的 setAnnotatedClasses 方法中提到任何类,请添加它们。建议 Spring 5 和 Hibernate 5 使用此配置。
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
@Autowired
private ApplicationContext context;
@Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setConfigLocation(context.getResource("classpath:hibernate.cfg.xml"));
factoryBean.setAnnotatedClasses(User.class);
return factoryBean;
}
@Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
}
关于java - 无法使用 spring 5 Autowiring hibernate 5 sessionfactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50490253/
我使用 hibernate 作为持久层来与数据库通信。我使用 maven 插件 hbm2java 来生成 dao、java、*hbm.xml 和 hibernate.cfg.xml。直到那个时候插件工
我想知道上面提到的 hibernates sessionfactory 类的两种方法之间的概念差异,如果可以通过简单的例子。 最佳答案 前者打开一个正常(有状态) session ,而后者(可能不足为
我正在关注 spring doc entry关于在独立应用程序中以编程方式设置我的应用程序上下文。 主要内容: public class Reporter { public static vo
如果我在结束时用 Session.getCurrentTransaction().commit() 关闭 session 或用 session.close() 关闭 session 会发生什么方法?
我正在尝试在我的 Spring 应用程序中使用 Hibernate 进行 Db 访问。但是现在,我收到以下错误: Could not locate SessionFactory in JNDI jav
我在基于 Java 的配置中使用 Hibernate 和 Spring。我的配置文件是这个: @Bean @Autowired public HibernateTransactionManager t
下面的代码不起作用。问题是事务没有在数据库中提交 案例1: @Transactional public void save(Person p) {
我对这两者有点困惑。据我所知,两者都返回 hibernate session ,SessionFactory.getCurrentSession()返回基于属性 的上下文 session 这是在 h
Image 错误: 1) AdminModel.java - 模型类。 2) HibernateUtil.java 促进 Hibernate DB 连接。 3) AdminDAO.java - 你们知
我遇到此错误,我找不到解决方案 我在Grails中使用postgres 这是不断发生的错误 org.springframework.beans.factory.BeanCreationExceptio
我需要 Hibernate 的一个特定功能,即 StatelessSession,为此我需要 Hibernate 的 SessionFactory。问题是我只有entityManagerFactory
我正在开发 jsf 应用程序并使用 hibernate 作为后端。我想创建 session 工厂并在整个应用程序中关闭它一次。我正在使用 util 类创建 session 工厂。 import org
我正在通过读取项目外部的属性文件来创建 session 工厂。我的属性文件如下, hibernate.connection.driver_class=com.mysql.jdbc.Driver hib
我们有一种情况,我们有多个具有相同模式的数据库,但每个数据库中的数据不同。我们正在创建一个 session 工厂来处理这个问题。 问题是我们不知道我们将连接到哪个数据库,直到运行时我们可以提供它。但是
在我的应用程序中,当我需要在这些方法中访问我的数据库时,我一直在我的方法参数中传递我的 SessionFatory。它在我的 Controller 中实例化,使用: @Autowired privat
我对 DataSource 和 SessionFactory 之间的区别感到困惑。 我认为SessionFactory是一个用于检索 session 的管理器(我猜这实际上是与数据库的连接)。 Dat
我正在尝试学习 spring 3 和 DAO 和 BO 类以及如何使用它进行 Autowiring ,我想知道这是连接 sessionFactory 的正确方法,因为我已经读到它更好地使用 publi
我正在将旧应用程序移植到 Hibernate 5,但在登录阶段遇到了问题。这是它的工作原理(我无法更改): 用户最初使用通用登录名/密码(所有用户相同)连接到 oracle DB 然后用户运行“登录”
根据文档,SessionFactory 应该是线程安全的: An ISessionFactory is threadsafe, many threads can access it concurren
如何使用 java 配置创建 SessionFactory? @Bean public SessionFactory sessionFactory(){ AnnotationSessionFa
我是一名优秀的程序员,十分优秀!