- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 JPA 之上使用 Spring 和 Hibernate 实现。我想使用 Spring 至少进行注释、 Autowiring 和事务管理。不过,我一直遇到以下问题。任何帮助将不胜感激!
我的 GenericDAO 实现:
package gov.cms.cicdim.cpc.data.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional
public abstract class GenericDAO<K, T extends Serializable>
implements IGenericDAO<K, T>
{
protected Class<T> entityClass;
@PersistenceContext
protected EntityManager entityManager;
@Autowired
public GenericDAO()
{
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[1];
}
public T findOne(K id)
{
if(isEmpty(id)) { return null; }
return this.entityManager.find(entityClass, id);
}
public List<T> findAll()
{
return this.entityManager.createQuery("from " + entityClass.getName()).getResultList();
}
public void create(T entity)
{
this.entityManager.persist(entity);
this.entityManager.close();
}
public void update(T entity)
{
this.entityManager.merge(entity);
this.entityManager.flush();
this.entityManager.close();
}
public void delete(T entity)
{
this.entityManager.remove(entity);
this.entityManager.close();
}
public void deleteById(K id)
{
T entity = findOne(id);
delete(entity);
}
/**
* Utility method to determine if objects is empty or all elements are null for optimization purposes.
*
* @param objects the objects
* @return true, if is empty
*/
protected boolean isEmpty(Object...objects) {
if(objects.length == 0) {
return true;
}
for(Object o : objects) {
if(o != null) {
return false;
}
}
return true;
}
}
DAO 本身:
package gov.cms.cicdim.cpc.data.dao;
import gov.cms.cicdim.cpc.data.model.Practice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* The Class PracticeDAO for CRUD operations for Practice data.
*/
@Repository
@Transactional
public class PracticeDAO extends GenericDAO<String, Practice>
implements IPracticeDAO
{
public PracticeDAO(){}
/** The Constant logger. */
private static final Log logger = LogFactory.getLog(PracticeDAO.class);
@Override
public Practice findPersonByFullName(String full_Name) {
// TODO Auto-generated method stub
return null;
}
}
测试 DAO:并非所有测试都包含空间(在 src/test/java 中)
package gov.cms.cicdim.cpc.data.dao;
import gov.cms.cicdim.cpc.data.model.Practice;
import java.util.List;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
@Transactional
public class PracticeDAOTest extends TestCase
{
@Autowired
public PracticeDAO testPracticeDAO;
public void setPracticeDAO(PracticeDAO testPracticeDAO) {
this.testPracticeDAO = testPracticeDAO;
}
boolean doit = true;
@Test
public void testCreatePracticeDAO(){
if(doit){
Practice practice = generatePractice();
String porg = practice.getParentOrgName();
String pid = practice.getPracticeId();
//create
try {
testPracticeDAO.create(practice);
String pratice_id = testPracticeDAO.findOne(pid).getPracticeId();
assertEquals("Practice id check", pid, pratice_id);
} catch (Exception e) {
e.printStackTrace();
throw new AssertionFailedError("Practice Save failed");
}
// test update
try{
practice.setSiteName("baltimore");
if(testPracticeDAO.findOne(pid) !=null){
testPracticeDAO.update(practice);
String site_Name = testPracticeDAO.findOne(pid).getSiteName();
assertEquals("Practice Site check", "baltimore", site_Name);
}
} catch(Exception e){
e.printStackTrace();
throw new AssertionFailedError("Practice update failed!");
}
}
持久性.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="ApplicationEntityManager">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="javax.persistence.jdbc.url"
value="xxxxxxxxx"/>
<property name="javax.persistence.jdbc.user" value="xxxxxxx"/>
<property name="javax.persistence.jdbc.password" value="xxxxxxx"/>
</properties>
</persistence-unit>
</persistence>
applicationContext.xml(在 src/main/resources 中)
<?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-3.0.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/>
<tx:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:persistence.xml" />
<property name="persistenceUnitName" value="ApplicationEntityManager" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="xxxxxxx" />
<property name="username" value="xxxxxxx" />
<property name="password" value="xxxxxxx" />
</bean>
<context:component-scan base-package="gov.cms.cicdim.cpc.data.dao"/>
<!-- Add new DAOs here -->
<bean id="practiceDAO" class="gov.cms.cicdim.cpc.data.dao.PracticeDAO"/>
<bean id="testPracticeDAO" class="gov.cms.cicdim.cpc.data.dao.PracticeDAO"/>
<!-- Add new Managers here -->
</beans>
和堆栈跟踪:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'gov.cms.cicdim.cpc.data.dao.PracticeDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 32 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 34 more
Results :
Tests in error:
testCreatePracticeDAO(gov.cms.cicdim.cpc.data.dao.PracticeDAOTest): Error creating bean with name 'gov.cms.cicdim.cpc.data.dao.PracticeDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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)}
testFindAllPractices(gov.cms.cicdim.cpc.data.dao.PracticeDAOTest): Error creating bean with name 'gov.cms.cicdim.cpc.data.dao.PracticeDAOTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public gov.cms.cicdim.cpc.data.dao.PracticeDAO gov.cms.cicdim.cpc.data.dao.PracticeDAOTest.testPracticeDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [gov.cms.cicdim.cpc.data.dao.PracticeDAO] 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)}
最佳答案
Spring declarative transactions are implemented using proxies 。默认情况下,如果被代理类实现一个接口(interface),它将使用 JDK 动态代理,这就是这里使用的代理,因为 PracticeDAO
实现 IPracticeDAO
。
spring创建的代理实现了相同的接口(interface)IPracticeDAO
,并且注册了该代理的bean。由于您在 PracticeDAO
上进行 Autowiring ,因此无法 Autowiring 代理 bean,因为同级类的实例不兼容。这就是为什么您几乎应该始终在接口(interface)类型上使用 @Autowired 注释,而不是实现类类型。
就您而言,尝试在 IPracticeDAO
上 Autowiring ,而不是在 PracticeDAO
上,它会正常工作。
关于java - DAO 测试 - Spring + JPA Autowiring 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28680250/
我有以下情况要解决,但无法正常工作(尝试了Hibernate和EclipseLink): Table_1: Column_A is Primary Key ... some other
我是 JPA 的新手,但必须在该技术中实现我的项目 我想做的是通过 CriteriaQuery 构建一些数据库查询,但不知道如何将参数列表传递给下面的代码: CriteriaBuilder qb =
我是 JPA 新手,注意到可以通过使用 @Version 注释实体中的字段来使用乐观锁定。我只是好奇,如果之前不存在,持久性提供程序是否会创建一个隐式版本字段。例如网站objectdb状态: "Whe
我有一个 JPA 查询 @Query(value = "SELECT SUM(total_price) FROM ... WHERE ...", nativeQuery = true) 当有匹配的记录
JPA 是否会尝试在已经持久(和非分离)的实体上级联持久化? 为了清楚起见,这是我的情况:我想保留一个新用户: public void addUser(){ //User is an enti
显然,OpenJPA。我也看到提到过 EclipseLink 和 Hibernate,但是在功能上有显着差异吗? 最佳答案 大多数差异来自提供者对 OSGi 的感知程度。例如,您可能需要自己将 Hib
我想将 JPA 用于 micronaut。为此,我使用 io.micronaut.data:micronaut-data-hibernate-jpa:1.0.0.M1 库。每当我运行应用程序并点击端点
我正准备为我的应用实现后端,现在我正在投影数据层。我期待着 Spring 。 最佳答案 Spring Data JPA 不是 JPA 实现。它提供了将数据访问层构建到底层 JPA 顶部的方法。您是否应
假设我有一个表 Item,其中包含一个名为 user_id 的列和一个表 User 以及另一个名为 Superuser 的列: CREATE TABLE Item(id int, user_id in
JPA 2.1 规范说: The entity class must not be final. No methods or persistent instance variables of the
我正在从事一个具有一些不寻常实体关系的项目,我在使用 JPA 时遇到了问题。有两个相关对象;用户,让我们称另一个 X。用户与 X 具有一对多和两个一对一的关系。它基本上看起来像这样 [用户实体] @O
我说的是 JavaEE 中的 JPA。在我读过的一本书中谈到: EntityManager em; em.find(Employee.class, id); “这是实体管理器在数据库中查找实例所需的所
我有 JPA 支持的 Vaadin 应用程序。此应用程序中的组件绑定(bind)到 bean 属性(通过独立的 EL 实现)。一些组件绑定(bind)到外部对象(或其字段),由@OneToOne、@O
是否可以使表中的外键唯一?假设我有实体 A 和 B。 答: @Entity class A extends Serializable { @Id private long id; @OneToOne
我在使用 JPA 时遇到了一点问题。考虑这种情况: 表 A (id_a) | 表 B (id_b, id_a) 我需要的是这样的查询: Select a.*, c.quantity from A as
我有一个由 JPA 管理的实体类,我有一个实体需要在其属性中记录更改。 JPA 是否提供任何方法来处理这种需求? 最佳答案 如果您使用 Hibernate 作为 JPA 提供程序,请查看 Hibern
我想实现以下架构: Table A: a_id (other columns) Table B: b_id (other columns) Table C: c_id (other columns)
我有一个愚蠢的问题。如果能做到的话那就太好了,但我并没有屏住呼吸。 我需要链接到我的 JPA 实体的表中的单个列作为所述 JPA 实体中的集合。有什么方法可以让我单独取回与该实体相关的列,而不必取回整
我有一个 Open JPA 实体,它成功连接了多对多关系。现在我成功地获取了整个表,但我实际上只想要该表中的 ID。我计划稍后调用数据库来重建我需要的实体(根据我的程序流程)。我只需要 ID(或该表中
这是我的一个实体的复合主键。 public class GroupMembershipPK implements Serializable{ private static final long
我是一名优秀的程序员,十分优秀!