- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在内存数据库中使用 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;
}
}
@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
}
}
@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
}
@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<String, DataSource> dataSources = new HashMap<String, DataSource>();
dataSources.put("dataSource", dataSource);
puManager.setDataSourceLookup(new MapDataSourceLookup(dataSources));
puManager.setDefaultDataSource(dataSource);
puManager.setPackagesToScan(packagesToScan());
bean.setPersistenceUnitManager(puManager);
bean.setPersistenceProviderClass(HibernatePersistence.class);
bean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = getHibernateProperties();
jpaProperties.put(HIBERNATE_TRANSACTION_JTA_PLATFORM, SpringJtaPlatform.class.getName().toString());
bean.setJpaProperties(jpaProperties);
puManager.afterPropertiesSet();
bean.afterPropertiesSet();
return bean.getObject();
}
protected String getDefaultSchema() {
String ds = ConfigurationUtil.config().getString("db.schema.name");
if (ds != null) defaultSchema = ds;
return defaultSchema;
}
protected String getUseUnicode() {
return useUnicode;
}
protected String getCharacterEncoding() {
return characterEncoding;
}
protected String getCharSet() {
return charSet;
}
protected String getFormatSql() {
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;
}
}
@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;
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(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.myapp.service.UserService$$EnhancerByCGLIB$$abc2864a.saveUser(<generated>)
at test.myapp.web.controllers.SignUpBeanTest.testSignUp(SignUpBeanTest.java:126)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
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.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
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)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.myapp.data.domain.Company
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:141)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:842)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:835)
at org.hibernate.ejb.engine.spi.EJB3CascadingAction$1.cascade(EJB3CascadingAction.java:53)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:387)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:330)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:424)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:263)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:135)
at org.hibernate.ejb.event.EJB3PersistEventListener.saveWithGeneratedId(EJB3PersistEventListener.java:78)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:208)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:151)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:852)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:826)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:830)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:875)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:354)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.saveAndFlush(SimpleJpaRepository.java:368)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:333)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 38 more
最佳答案
我认为问题出在这里:
@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.
}
@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
}
关于spring - org.hibernate.PersistentObjectException : detached entity passed to persist with H2 in memory database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17887055/
或者存在像 这样的指针和引用C ? 我正在尝试开始使用 vala,但很高兴知道 vala 是“按引用传递”还是“按值传递” 最佳答案 首先你应该明白默认的vala编译器valac编译为 C(作为一种中
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我确实对 crypt() PHP 函数感到困惑。 当第二个 crypt 显然使用不同的第二个参数时,以下两个 crypt 函数如何给出相同的输出?差异盐意味着差异哈希对吗? echo crypt("p
我正在尝试在方案中模拟堆栈。我正在使用 DrScheme 并选择语言 R5RS。我需要创建 pop、push 和 peek 的函数。但我无法弄清楚如何通过引用传递。我已经阅读了一些关于盒子的信息,但是
我已经查过维基百科并用 google 搜索过,但我仍然无法理解 ALGOL 60 中的按名称传递的工作原理。 最佳答案 我在 Pass-By-Name Parameter Passing 找到了很好的
问题:我想知道在 Excel 2003 VBA 中处理数组的最佳解决方案是什么 背景:我在 Excel 2003 中有一个超过 5000 行的宏。我在过去 2 年中构建了它,将新功能添加为新过程,这有
我正在尝试反转位图数组,而不修改源数组。但问题是源数组也被颠倒了。我做错了什么还是我应该以其他方式做?感谢您的帮助。 private GalleryAdapter galleryAdapter; pr
因此,关于按引用传递/按值传递,方法如何处理参数传递已有详细记录,但是变量赋值又如何呢? 例如,我刚刚编写了一些如下所示的代码: TreeNode parent = null; TreeNode cu
我正在编写一个脚本,它将从我们的星号系统中回填调用详细记录到我们的 MySQL 日志数据库中。在下面的代码中,我试图忽略重复键并继续到下一行,但是当这段代码执行时,我所看到的只是第一行欺骗警告,然后脚
我从一个 Action (executeProcess)重定向到另一个(executeIndex)。我希望能够不使用GET传递参数/变量(例如$this->redirect('index', arra
我经常看到方法接口(interface)的两种相互冲突的策略,大致概括如下: // Form 1: Pass in an object. double calculateTaxesOwed(TaxFo
目前正在学习回调在 JavaScript 中的含义,我正在努力理解回调是如何工作的,以及术语“passing this”或“passing that”的来源以及它如何与回调一起工作?我想展示一些示例代
我通过 URL 传递参数并且页面被正确重定向。如何访问下一个(重定向的)页面上(从上一页)传递并在 URL 中可用的参数?谁能告诉我该怎么做? 或者有没有其他的方式在页面之间传递参数? 是否有类似 A
我通过 URL 传递参数并且页面被正确重定向。如何访问下一个(重定向的)页面上(从上一页)传递并在 URL 中可用的参数?谁能告诉我该怎么做? 或者有没有其他的方式在页面之间传递参数? 是否有类似 A
按引用传递和按名称传递的参数传递模式有什么区别这里是 Python 中的一个示例,但假设我们不使用任何 Python 规则: def P(x,y) global i y=1 prin
我正在编写自己的 LLVM pass,它修改了 LLVM 位码。在生成位码时,我想禁用函数内联,但是当我完成对位码的修改后,我想调用执行函数内联的传递。这个可以吗。如果是,如何? 为了更好地理解我在说
我有一个模板函数,负责将模板值写入流。它看起来像这样: template void Write( T value, std::ostream& stream, endianness_t endian
我一直在使用两个程序 llvm 的 opt 和 clifford wolf 的 yosys两者都有类似的通行证接口(interface)。(他们使用共享库作为优化 passes ) 我想根据我的 ll
在我们使用引用传递的 C++ 中,我们引用了我们从参数传递给函数参数的地址,它本质上是一个指针,对吗?因此,虽然它们本质上是相同的东西,别名和所有,但指针不也需要内存空间吗?因此,无论我们在参数函数中
这是一个关于 64 位整数的效率问题。假设我不需要修改“int”参数的值,我应该通过值还是引用传递它。 假设是 32 位机: 1) 32 位 int:我猜答案是“按值传递”,因为“按引用传递”会产生额
我是一名优秀的程序员,十分优秀!