【问题标题】:Spring projections select collection春季投影精选系列
【发布时间】:2018-11-16 15:23:38
【问题描述】:

我正在尝试让车站投影包含相关徽标的列表。以下是我的域名:

@Table(name = "Station")
public class Station implements Serializable {

@Id
@Column(name = "Id")
private int id;

@OneToMany(cascade = CascadeType.ALL,
        fetch = FetchType.LAZY,
        mappedBy = "station")
private Set<Logo> logos;
}

@OneToMany 相关徽标:

@Table(name = "Logo")
public class Logo {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Transient
private String fullUrl; // calculated

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "StationId", nullable = false)
private Station station;
}

我的仓库和查询如下:

@Query(value = "SELECT s.id AS Id, s.logos As Logos FROM Station s JOIN s.users su WHERE su.username = ?1")
Collection<StationListViewProjection> findStationsByUsername(String username);

我的电台投影需要 Id 和 logoProjections 列表

@Projection(name = "StationListViewProjection", types = Station.class)
public interface StationListViewProjection {
   int getId();
   Set<LogoProjection> getLogos();
}

logoProjection 只需要url

@Projection(name = "LogoProjection", types = Logo.class)
public interface LogoProjection {
   String getFullUrl();
}

当我执行查询时,我得到一个奇怪的响应:

MySQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 'as col_5_0_, 附近使用的正确语法。作为 col_6_0_,stationlog3_.id 作为 id1_20_0_'

【问题讨论】:

    标签: spring-data spring-data-jpa spring-projections


    【解决方案1】:

    如果我明白这一点

    @Transient
    private String fullUrl; // calculated
    

    正确,您的 fullUrl 是在您的 java 代码中计算出来的,更重要的是,它在数据库中没有匹配的列。您不能直接在投影中使用此类字段。您也许可以使用Open Projection 并指定计算以使用@Value 注释获得fullUrl

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 2017-10-06
      • 2020-02-04
      • 2016-01-30
      相关资源
      最近更新 更多