我有一个带有 Entity @Transient 字段的实体,当我运行查询时出现错误。
查询与实体瞬态字段有连接
@Entity
@Table(name = "OTHER")
public class OtherEntity implements Serializable {
@Id
private Long id
@Column( name = "code" )
private String code;
}
@Entity
@Table(name = "MARKER")
public class MarkerEntity implements Serializable {
@Id
private Long id
@Column(name = "OTHER_FIELD")
private Long otherId;
@Transient
private OtherEntity other;
public MarkerEntity(Long otherId, OtherEntity other) {
this.otherId = otherId;
this.other = other;
}
}
这是 jpa 查询
@Query("SELECT " +
"new MarkerEntity(" +
" o.id, " +
" new OtherEntity(o.id, o.code)" +
") m " +
"JOIN OtherEntity o")
public List<MarkerEntity> entities(@Param("id") Long id)
当您尝试将 OtherEntity 与 MarkerEntity 中的瞬态 other 字段连接时,JPA 会抛出错误,因为它不知道如何处理此瞬态关联。您可以使用 @ 定义 MarkerEntity 和 OtherEntity 之间的关系,而不是使用 @Transient 字段多对一。这允许 JPA 自然地处理连接,而不需要瞬态字段。
@Entity @Table(name = "OTHER") public class OtherEntity Implements Serialized { @Id private Long id; @Column(name = "code") 私有字符串代码; // 为 JPA 添加默认构造函数 public OtherEntity() {} public OtherEntity(Long id, String code) { this.id = id; this.code = 代码; } // Getter 和 Setter }
@Entity @Table(name = "MARKER") public class MarkerEntity Implements Serialized { @Id private Long id; @Column(name = "OTHER_FIELD", insertable = false, updateable = false) private Long otherId; @ManyToOne @JoinColumn(name = "OTHER_FIELD",referencedColumnName = "id") private OtherEntity other;公共 MarkerEntity() {} 公共 MarkerEntity(Long otherId, OtherEntity other) { this.otherId = otherId; this.other = 其他; } // Getters 和 Setters } 设置好这种关系后,您的查询可以简化如下
@Query("从 MarkerEntity m 中选择新的 MarkerEntity(m.other.id, m.other),在此处输入代码em.id = :id")?公共列表实体(@Param(“id”)长id);