【问题标题】:JPA Query with Joins and a Custom Obj that is not Table具有联接的 JPA 查询和不是表的自定义 Obj
【发布时间】:2018-01-03 19:30:10
【问题描述】:

我正在使用本机查询进行连接。返回的对象是一个包含查询中所有属性的新对象。但它会抛出一个错误,说它无法将 object[] 绑定到 CombinedObj。我该怎么办?

public interface SettingsRepository extends JpaRepository<Setting, Long> {

    @Query(value = "select s.some_value, o.other_value from settings s inner join other_table o on o.id = s.other_table_id where user_id = :user_id", nativeQuery = true)
    List<CombinedObj> find(@Param("user_id") int userId);

}

【问题讨论】:

    标签: java mysql jpa


    【解决方案1】:

    您不能简单地投影列并期望 jpa 将这些列推断为结果对象。

    可以使用命名本地查询来解决此问题。像这样:

    @Entity
    @Table(name = "settings")
    @SqlResultSetMapping(
            name = "yourResultSetMapping",
            classes = {
                    @ConstructorResult(
                            targetClass = CombinedObj.class,
                            columns = {
                                @ColumnResult(name = "some_value"), @ColumnResult(name = "other_value")
                            }
                    )
            }
    )
    @NamedNativeQuery(
            name = "Settings.getNativeQuery",
            query = "select s.some_value, o.other_value from settings s inner join other_table o on o.id = s.other_table_id where user_id = :user_id",
            resultSetMapping = "yourResultSetMapping"
    )
    public class Settings{...}
    

    【讨论】:

      猜你喜欢
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2021-10-23
      • 2018-07-07
      • 2019-03-10
      • 2017-09-01
      相关资源
      最近更新 更多