java.util.HashSet无法强制转换为org.hibernate.collection.PersistentCollection

时间:2013-09-11 15:25:34

标签: java hibernate jpa

我已经将几个模型类中的代码从字段访问器更改为属性访问器,并且还从List更改为Set,因为顺序并不重要。以下是我的实体类。

@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(); 
}
 }
     }

1 个答案:

答案 0 :(得分:1)

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

也许setGameCodes应该

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

而不是

this.gameCodes = gameCodes;