我正在使用本机查询进行联接。返回的对象是一个新对象,其中包含查询中的所有属性。但是它抛出一个错误,说它不能将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);

}

最佳答案

您不能简单地投影您的列并期望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{...}

09-04 03:49
查看更多