当前位置: 首页 > 知识库问答 >
问题:

Spring通用Hibernate刀

林哲茂
2023-03-14
@Repository
public class HibernateDaoImpl <T>  implements Dao<T>{
    @Autowired
    private SessionFactory sessionFactory;
    @Autowired
    private Class<T> clazz;

     //setter & getter

    public HibernateDaoImpl (Class<T> clazz)
    {
      this.clazz = clazz;
    }
    public Session getCurrentSession ()
    {
        return sessionFactory.getCurrentSession();
    }

    public void save(T t) 
    {
        getCurrentSession().save(t);
    }

    public void update(T t) 
    {
        getCurrentSession().update(t);
    }


    @SuppressWarnings("unchecked")
    public T findById(Object object)
    {
        return (T) getCurrentSession().get(clazz, (Serializable)object);
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll(int page, int maxResult) 
    {
        return getCurrentSession().createQuery(String.format("FROM %s", clazz.getSimpleName())).list();
    }
public class SubscriberHibernateDao extends HibernateDaoImpl<Subscriber> implements SubscriberDao {

    public SubscriberHibernateDao ()
    {
        super(Subscriber.class);
    }
}
<bean id="subscriber" class="com.example.model.Subscriber" autowire="byName">
    <property name="email" value="mdennis10"></property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/kyro"/>
    <property name="username" value="root"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="packagesToScan" value="com.kyrogaming.model"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
    </property>
</bean>

<bean id="subcriberDao" class="com.example.dao.SubscriberHibernateDao">
 <property name="clazz" value="com.example.model.Subscriber"></property>
</bean>

当我运行它时,我会得到以下堆栈跟踪:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.Class com.example.dao.HibernateDaoImpl.clazz; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.kyrogaming.test.BeanTest.test(BeanTest.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

原因:org.springframework.beans.factory.BeanCreationException:无法自动连接字段:private java.lang.class com.example.dao.hibernateDaoImpl.clazz;嵌套异常为org.springframework.beans.factory.noSuchBeanDefinitionException:未找到依赖项的[java.lang.class]类型的合格bean:至少需要一个合格的bean作为此依赖项的自动候选项。依赖项批注:{@org.springframework.beans.factor.annotation.AutoWired(required=true)}(位于org.springframework.beans.factor.annotation.AutoWiredanNotationbeanpostprocessor.java:514)(位于org.springframework.beans.factor.annotation.injectionmetadata.inject(injectionmetadata.java:87)(位于依赖关系批注:{@org.springframework.beans.factory.annotation.AutoWired(required=true)}(位于org.springframework.beans.factory.support.defaultlistablebeanfactory.raisenosuchbeandefinitionexception(defaultlistablebeanfactory.986)(位于org.springframework.beans.factory.support.defaultlistablebeanfactory.doResolveDependency

我该怎么解决这个。

共有1个答案

关飞翔
2023-03-14
@Autowired 
private Class<T> clazz;

代码中的这一行永远不会起作用,因为spring不知道要自动连接什么。你只能按类型或工作类自动连接,最好是类型。

您需要将这个类包装在包装器对象中,这样您就可以按类型进行自动连接,然后将该类型注入到DAO中。

示例

@Autowired
private Entity<T> entity;
 类似资料:
  • 我的项目使用的是Spring MVC4、Hibernate5。我已经用通知拦截器配置了hibernate事务,但它没有像我希望的那样回滚。请帮帮我,我的配置有什么问题? @aspect@配置公共类TxAdviceInterceptor{ } 道: } 正如上面的代码,我想如果postdao.save是error,tagDao也是rollback。

  • 我正在与spring boot、hibernate和MySQL合作。在运行应用程序时,它按照预期运行得很好。但是在制作docker-compose文件并使用mysql docker映像运行app docker映像时,它会出现这个错误。 错误com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:通信链接失败java.net.ConnectEx

  • 问题内容: 如何使用Java配置创建SessionFactory? 由于某些原因,此方法不起作用…它总是返回null。 问题答案: 这里值得一提的是Spring 3.1引入了LocalSessionFactoryBuilder,它专门设计用于@Bean方法中。 http://static.springsource.org/spring/docs/3.1.0.RC1/javadoc- api/org

  • 我的maven依赖有什么问题。当我包含JPA时,我会列出pf例外情况 和我的源代码 所以我没有任何IDE(不幸的是,还有示例)如何运行Spring boot和hibernate。

  • 问题内容: 在使用hibernate时,我们将遵循Hibernate Doc中提到的通用Hibernate DAO模式。 因此,据此,我们目前为接口2)维护两个并行的层次结构1)以实现 因此,即使我们在标准持久性方法之外没有提出任何新方法的情况下以这种方式进行工作,我们也需要为该对象及其实现创建标记界面。 尽管这种方法及其明确的分隔似乎没有问题。 我的问题是是否有更好的方法/替代方法来实现这一目标

  • 问题内容: 我使用我的uuid如下: 但是我收到了一个聪明的Hibernate警告: 使用org.hibernate.id.UUIDHexGenerator不会生成符合IETF RFC 4122的UUID值;考虑改用org.hibernate.id.UUIDGenerator 所以我想切换到,现在我的问题是如何将其告知Hibernate的生成器。我看到有人用它作为“hibernateuuid”-这