ClassCastException:尝试迭代实体ID时,无法将Integer强制转换为Long
我的服务中有以下方法:
public Set moveHoldedCardsToNewBoard(Board newBoard, Board prevBoard) { Set boardCards = new HashSet(); if (prevBoard != null) { List holdedCardIds = getExcludedCardIds(prevBoard); for (Long item: holdedCardIds) { } }
当我想循环holdedCardIds
列表时,我收到: java.lang.ClassCastException:java.lang.Integer不能在这个地方for (Long item: holdedCardIds) {
为java.lang.Long – > for (Long item: holdedCardIds) {
我的getExcludedCardIds()看起来像:
@Override public List getExcludedCardIds(Board board) { return boardCardRepository.getExcludedCardIds(board.getId()); }
库:
@Repository public interface BoardCardRepository extends JpaRepository, QueryDslPredicateExecutor { @Query(value = "SELECT bc.card_id FROM boards_cards bc WHERE bc.board_id =:boardId AND bc.on_hold=true", nativeQuery = true) List getExcludedCardIds(@Param("boardId") Long boardId); }
entites的:
@Entity @NamedEntityGraph(name = "graph.BoardCard", attributeNodes = {}) @Table(name = "boards_cards") public class BoardCard implements Serializable { private static final long serialVersionUID = -9019060375256960701L; @EmbeddedId private BoardCardId id = new BoardCardId(); } @Embeddable public class BoardCardId implements Serializable { private static final long serialVersionUID = -3630484760647866357L; @ManyToOne private Board board; @ManyToOne private Card card; } @Entity @Table(name = "boards") public class Board extends BaseEntity implements Serializable { @Id @SequenceGenerator(name = "boards_id_seq", sequenceName = "boards_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "boards_id_seq") private Long id; } @Entity @Table(name = "cards") public class Card extends BaseEntity implements Serializable { @Id @SequenceGenerator(name = "cards_id_seq", sequenceName = "cards_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.AUTO, generator = "cards_id_seq") private Long id; }
在我的POSTGRES schema.sql中,BoardCard实体定义如下:
CREATE TABLE IF NOT EXISTS boards_cards( board_id INTEGER, card_id INTEGER, on_hold BOOLEAN DEFAULT FALSE, CONSTRAINT pk_user_card PRIMARY KEY (board_id, card_id), FOREIGN KEY(board_id) REFERENCES boards(id), FOREIGN KEY(card_id) REFERENCES cards(id) );
我在这里发现,postgresql中等效的LONG类型是bigint
。 但是,如果我尝试使用它,它将如何影响我的应用程序的性能方面?
那么,告诉我该如何解决这个问题呢?
我在这里找到了解决方案。 解决方案是使用JPQL查询而不是SQL查询。
重构存储库:
@Repository public interface BoardCardRepository extends JpaRepository, QueryDslPredicateExecutor { @Query(value = "SELECT id.card.id FROM BoardCard WHERE id.board.id = :boardId AND onHold = true") List getExcludedCardIds(@Param("boardId") Long boardId); }
(long) can be casted into (int), and (int) can be casted to (long)
然而,
(Long) **cannot** be casted into (Integer)
反之亦然,因为它们不是原始的。 bigint
这是你的根本问题,虽然我不确定你的程序在哪里引起了演员。
如果你正在使用java-8 ,只需将你的Integer
对象列表转换为包含相同值的一个对象就可以解决这个问题,只需要用java自动进行自动装箱。
getExcludedCardIds(prevBoard).stream .mapToLong(x -> x).collect(Collectors.toList);