我将几个模型类中的代码从字段访问器更改为属性访问器,并将代码从列表更改为集合,因为顺序并不重要。以下是我的实体课程。

@Entity
@Table(name = "TPYP_GAME")
public class Game extends AbstractGeneratedIdEntity{
    private static final long serialVersionUID = -1390767030654384142L;

    private static final String GAME_FIELD = "GAME";

    private GameypeEnum gameTypeEnum;
    private Set<GameCode> gameCodes;

    @Transient
    public GameTypeEnum getGameTypeEnum() {
        return gameTypeEnum;
    }

    @OneToMany(cascade = CascadeType.ALL, mappedBy = GAME_FIELD, fetch = FetchType.LAZY)
    public Set<GameCode> getGameCodes() {
        return gameCodes;
    }

    public void setGameTypeEnum(GameTypeEnum gameTypeEnum) {
        this.gameTypeEnum = gameTypeEnum;
    }

    public void setGameCodes(Set<GameCode> gameCodes) {
        this.gameCodes = gameCodes;
    }


我调试了源代码,发现从存储库获取数据后提交事务时,它引发以下异常。

 org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction;
 nested exception is javax.persistence.RollbackException: Error while committing the transaction
 javax.persistence.RollbackException: Error while committing the transaction java.util.HashSet
 cannot be cast to org.hibernate.collection.PersistentCollection


我不确定如何解决。我想念什么?



客户代码:

    @Transactional(readOnly = true)
    public List<Game> getGames(String nameContains, Long pageSize){
    if(!nameContains.isEmpty() && pageSize !=null){
    return repository.findAll(nameIsLike(nameContains), constructPageSpecification(pageSize)).getContent(); }
    else{ if(pageSize != null){
    return repository.findAll(null, constructPageSpecification(pageSize)).getContent(); }
    else if(!nameContains.isEmpty()){
    return repository.findAll(nameIsLike(nameContains)); }else{ return repository.findAll();
}
 }
     }

最佳答案

看起来setGameCodes用新创建的Set替换了从数据库中读取的HashSet,而不是添加到现有的CC中或从中删除了,这会在您尝试将更改提交回数据库时引起问题。

也许setGameCodes应该做

this.gameCodes.clear();
this.gameCodes.addAll(gameCodes);


代替

this.gameCodes = gameCodes;

09-12 17:55