我遇到以下问题。我把我的例子推到了GitHub。
如果我想要保留我的类router.route('/appointment')
.post(function(req, res) {
var appointmentData = req.body;
var appointments = new Appointment(appointmentData);
console.log(appointments);
appointments.save(function(err, appointment) {
if (err)
throw err;
res.json(appointment);
})
})
的实例,那么Hibernate会尝试创建一个我不想要的PlayerStatistics
(指定为Matchday
)的现有实体,但我似乎没有绕过它。
我坚持使用@ManyToOne
的{{1}}方法。
init
如果我像上面那样,那么我得到以下异常。
DemoApplicationTests
如果我调试HQL,我可以清楚地看到Hibernate想要在表@Before
public void init() {
final Matchday matchday = matchdayRepository.save(new Matchday(1));
final Club club1 = clubRepository.save(new Club("Klub1"));
final Club club2 = clubRepository.save(new Club("Klub2"));
final Match match = matchRepository.save(new Match(matchday, club1, club2));
final Player player = playerRepository.save(new Player(1, "Jan", "Kowalski", club1));
playerStatisticsRepository.save(new PlayerStatistics(matchday, player, match));
}
中插入一个新行,即使它已经存在。
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [SYS_PK_10114]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy102.save(Unknown Source)
at com.example.DemoApplicationTests.init(DemoApplicationTests.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2934)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3434)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:582)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:456)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1407)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:477)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3170)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2384)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 44 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: unique constraint or index violation; SYS_PK_10114 table: MATCHDAY
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
... 62 more
Caused by: org.hsqldb.HsqlException: integrity constraint violation: unique constraint or index violation; SYS_PK_10114 table: MATCHDAY
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.Constraint.getException(Unknown Source)
at org.hsqldb.index.IndexAVLMemory.insert(Unknown Source)
at org.hsqldb.persist.RowStoreAVL.indexRow(Unknown Source)
at org.hsqldb.TransactionManager2PL.addInsertAction(Unknown Source)
at org.hsqldb.Session.addInsertAction(Unknown Source)
at org.hsqldb.Table.insertSingleRow(Unknown Source)
at org.hsqldb.StatementDML.insertSingleRow(Unknown Source)
at org.hsqldb.StatementInsert.getResult(Unknown Source)
at org.hsqldb.StatementDMQL.execute(Unknown Source)
at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 65 more
如果我评论Matchday
方法的最后一行,那么它就可以了,所以问题必须出在这一部分:Hibernate:
insert
into
Matchday
(matchdayNumber)
values
(?)
init()
我在这里做错了什么?
playerStatisticsRepository.save(new PlayerStatistics(matchday, player, match))
课程就是这样。
@Before
public void init() {
final Matchday matchday = matchdayRepository.save(new Matchday(1));
final Club club1 = clubRepository.save(new Club("Klub1"));
final Club club2 = clubRepository.save(new Club("Klub2"));
final Match match = matchRepository.save(new Match(matchday, club1, club2));
final Player player = playerRepository.save(new Player(1, "Jan", "Kowalski", club1));
//playerStatisticsRepository.save(new PlayerStatistics(matchday, player, match));
}
如果我想直接从PlayerStatistics
实体管理它。然后我收到一个例外,即该实体已经与会话相关联,而它似乎不是。
@Entity
@IdClass(PlayerStatisticsId.class)
public class PlayerStatistics implements Serializable {
//...
@Id
@ManyToOne(optional = false)
@PrimaryKeyJoinColumn
private Player player;
@Id
@ManyToOne(optional = false)
@PrimaryKeyJoinColumn
private Matchday matchday;
@ManyToOne(optional = false)
@JoinColumns({ @JoinColumn(name = "matchday_matchdaynumber", referencedColumnName = "matchday_matchdaynumber"),
@JoinColumn(name = "hometeam_name", referencedColumnName = "hometeam_name") })
private Match match;
@Column(nullable = false)
private boolean playedFromTheFirstWhistleblow;
@Min(0)
@Column(nullable = false)
private int enteredTheFieldAtInSeconds;
@Min(0)
@Column(nullable = false)
private int leftTheFieldAtInSeconds;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable
@MapKeyEnumerated(EnumType.STRING)
private Map<ScoreType, Integer> statistics = new HashMap<>();
//...
}
Player
答案 0 :(得分:0)
这里的问题出在PlayerStatisticsId
以及它的定义方式。
最初它看起来像这样。
public class PlayerStatisticsId implements Serializable {
//..
private long player;
private int matchday;
public long getPlayer() {
return player;
}
public int getMatchday() {
return matchday;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof PlayerStatisticsId) {
final PlayerStatisticsId o = (PlayerStatisticsId) obj;
return o.matchday == matchday && o.player == player;
} else {
return false;
}
}
}
我本可以发誓,我在某处读到只有基元/基本类型可以用在@ClassId
的类中。但情况似乎并非如此。
将其更改为
public class PlayerStatisticsId implements Serializable {
//...
private Player player;
private Matchday matchday;
public Player getPlayer() {
return player;
}
public Matchday getMatchday() {
return matchday;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof PlayerStatisticsId) {
final PlayerStatisticsId o = (PlayerStatisticsId) obj;
return o.matchday.equals(matchday) && o.player.equals(player);
} else {
return false;
}
}
}
它确实有效。我现在收到一个完全不同的例外,但这是一个单独的问题。