我在内存数据库中使用H2进行测试,我的配置如下:
1- SpringTestingConfig:
@Configuration @ComponentScan(basePackages = "com.myapp.data",excludeFilters = { @Filter(Configuration.class) }) @PropertySource("classpath:/test.properties") @Profile("test") public class SpringTestingConfig { @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:mem:test;MODE=MysqL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS MYAPP"); dataSource.setUsername("sa"); dataSource.setPassword(""); return dataSource; } }
@H_502_10@2- MyTestClass:
@RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({ WebContextTestExecutionListener.class,DependencyInjectionTestExecutionListener.class,DirtiesContextTestExecutionListener.class,TransactionalTestExecutionListener.class }) @ActiveProfiles("test") @DirtiesContext @ContextConfiguration(loader = AnnotationConfigContextLoader.class,classes = { SpringConfig.class,SpringTestingConfig.class,SpringLocalContainerJPAConfig.class,CustomConfiguration.class }) @PrepareForTest({ FacesContext.class }) @PowerMockIgnore({ "javax.management.*","javax.xml.parsers.*","com.sun.org.apache.xerces.internal.jaxp.*","ch.qos.logback.*","org.slf4j.*" }) public class MyTestClass{ private Company company; private User user; @Test public void signup(){ User user = new User(); Company company = new Company(); company.setName("Test"); company = usService.saveCompany(company); user.setFirstName("Test"); user.setLastName("User"); user.setEmail("test@test.com"); user.setPassword("verySecret"); user.setCompany(company); user = usService.saveUser(user); // gives exception } }
@H_502_10@3-保存方法:
@Transactional(propagation = Propagation.required) public User saveUser(User user) { return userRepository.saveAndFlush(user); //JpaRepository } @Transactional(propagation = Propagation.required) public Company saveCompany(Company company) { return companyRepository.saveAndFlush(company); //JpaRepository }
@H_502_10@4- JPA配置
@Configuration @EnableSpringConfigured public class SpringJNDIJPAConfig { protected static final Logger logger = LoggerFactory.getLogger(SpringConfig.class); protected static final String HIBERNATE_TRANSACTION_JTA_PLATFORM = "hibernate.transaction.jta.platform"; @Value("${hibernate.naming_strategy:org.hibernate.cfg.DefaultNamingStrategy}") private String namingStrategy; @Value("${hibernate.packages_to_scan:com.myapp.data.domain}") private String packagesToScan; @Value("${spring_config.project_name}") private String projectName; @Value("${hibernate.show_sql:false}") private String showsql; @Value("${hibernate.hbm2ddl.auto:update}") private String hbm2ddlAuto; @Value("${hibernate.format_sql:false}") private String formatsql; @Value("${hibernate.dialect:org.hibernate.dialect.MysqL5InnoDBDialect}") private String hibernateDialect; @Value("${hibernate.connection.useUnicode:true}") private String useUnicode; @Value("${hibernate.connection.characterEncoding:UTF-8}") private String characterEncoding; @Value("${hibernate.charSet:UTF-8}") private String charSet; @Value("${hibernate.default_schema}") private String defaultSchema; @Value("${hibernate.use_default_schema:true}") private boolean useDefaultSchema; @Value("${hibernate.use_sql_comments:true}") private String usesqlComments; @Autowired private ApplicationContext applicationContext; @Autowired private DataSource dataSource; @Bean public HibernateExceptionTranslator hibernateExceptionTranslator() { return new HibernateExceptionTranslator(); } @Bean protected EntityManagerFactory entityManagerFactory() { LocalContainerEntityManagerfactorybean bean = new LocalContainerEntityManagerfactorybean(); JtaPersistenceUnitManager puManager = new JtaPersistenceUnitManager(); Map
@H_502_10@sql() { return formatsql; } protected String getHbm2ddlAuto() { return hbm2ddlAuto; } protected String getHibernateDialect() { return hibernateDialect; } protected Properties getHibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect",getHibernateDialect()); properties.put("hibernate.hbm2ddl.auto",getHbm2ddlAuto()); properties.put("hibernate.show_sql",getShowsql()); properties.put("hibernate.use_sql_comments",getUsesqlComments()); properties.put("hibernate.format_sql",getFormatsql()); if(useDefaultSchema) { properties.put("hibernate.default_schema",getDefaultSchema()); } //properties.put("hibernate.ejb.naming_strategy",namingStrategy); properties.put("hibernate.hbm2ddl.import_files","/import.sql"); //properties.put("hibernate.connection.characterEncoding",getCharacterEncoding()); //properties.put("hibernate.connection.charSet",getCharSet()); //properties.put("hibernate.connection.useUnicode",getUseUnicode()); if(logger.isInfoEnabled()) { logger.info(MessageFormat.format("SET HIBERNATE PROPERTIES: {0}",properties.toString())); } return properties; } protected String getProjectName() { return projectName; } protected String getShowsql() { return showsql; } protected String getUsesqlComments() { return usesqlComments; } protected String packagesToScan() { return packagesToScan; } @Bean protected JtaTransactionManager transactionManager() { Springbeanfactory.setApplicationContext(applicationContext); JtaTransactionManager manager = new JtaTransactionManager(); manager.setTransactionManagerName("java:jboss/TransactionManager"); manager.setUserTransactionName("java:jboss/UserTransaction"); manager.afterPropertiesSet(); return manager; } } 5-用户实体:
@Entity @Table(name = "User",uniqueConstraints = { @UniqueConstraint(columnNames = { "CompanyGID","MPath" }) }) public class User extends PersistableEntity implements UserDetails { /** * */ private static final long serialVersionUID = -6520416613985790209L; @ManyToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL) @JoinColumn(name = "CompanyGID") private Company company;
@H_502_10@问题:测试方法中的代码在Jboss上运行应用程序(本地数据库)并从支持bean方法调用代码时工作得非常好,但是当从test(在内存数据库中)运行它时,它可以节省公司并在尝试保存用户时给出例外:
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.myapp.data.domain.Company; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.myapp.data.domain.Company at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:668) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:106) at org.springframework.orm.jpa.AbstractEntityManagerfactorybean.translateExceptionIfPossible(AbstractEntityManagerfactorybean.java:403) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:91) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at com.myapp.service.UserService.saveUser_aroundBody6(UserService.java:98) at com.myapp.service.UserService$AjcClosure7.run(UserService.java:1) at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96cproceed(AbstractTransactionAspect.aj:59) at org.springframework.transaction.aspectj.AbstractTransactionAspect$AbstractTransactionAspect$1.proceedWithInvocation(AbstractTransactionAspect.aj:65) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:63) at com.myapp.service.UserService.saveUser(UserService.java:93) at com.myapp.service.UserService$$FastClassByCGLIB$$697e2a1b.invoke(
@H_502_10@
最佳答案
我认为这个问题在这里:
原文链接:https://www.f2er.com/spring/431655.html@Test public void signup(){ User user = new User(); Company company = new Company(); company.setName("Test"); company = usService.saveCompany(company); //object is saved and transaction is closed,so company is detached here. user.setFirstName("Test"); user.setLastName("User"); user.setEmail("test@test.com"); user.setPassword("verySecret"); user.setCompany(company); //u are setting this detached object to user,NOTE user object's company attr is cascade.all which means this company will be saved as well when you save user. user = usService.saveUser(user); // gives exception,because you are saving new user object with detached company object. }
@H_502_10@那么我们如何解决呢?
您可以让用户保存公司对象,因此您不会显式保存公司,因为cascade.all用于用户的公司对象,公司也应该在保存用户时保存:@Test public void signup(){ User user = new User(); Company company = new Company(); company.setName("Test"); user.setFirstName("Test"); user.setLastName("User"); user.setEmail("test@test.com"); user.setPassword("verySecret"); user.setCompany(company); user = usService.saveUser(user); // gives exception }
@H_502_10@