【问题标题】:Spring Data Rest one to many JSON Formatting: Use foreign key instead of objectsSpring Data Rest 一对多 JSON 格式:使用外键而不是对象
【发布时间】:2018-09-06 07:34:07
【问题描述】:

我使用带有 2.0.0.M6 的 Spring Boot 和带有 org.springframework.boot:spring-boot-starter-data-rest 的 kotlin 1.1.51 并尝试格式化 json 的输出。

我该如何配置。弹簧休息数据,以便它在多对一关系中输出/接受外键而不是带href的对象?

带有外键 language_id (kotlin) 的示例模型:

@Entity
data class Song (
        @Column
        var title: String,

        @Column
        var songTypeId: Int,

        @OneToMany(mappedBy = "song")
        var mastersheets: Set<Mastersheet> = setOf<Mastersheet>()


) : UpdateableBaseEntity() {

        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "language_id", nullable = false)
        lateinit var language: Language

        @ManyToOne()
        @JoinColumn(name = "artist_id", nullable = false)
        lateinit var artist: Artist
}

输出类似于:

{
  "_embedded" : {
    "songs" : [ {
      "title" : "Hello World",
      "songTypeId" : 1,
      "insertDate" : "2018-09-06T07:25:14.307+0000",
      "updateDate" : null,
      "_links" : {
        "self" : {
          "href" : "http://localhost/songs/1"
        },
        "song" : {
          "href" : "http://localhost/songs/1"
        },
        "artist" : {
          "href" : "http://localhost/songs/1/artist"
        },
        "mastersheets" : {
          "href" : "http://localhost/songs/1/mastersheets"
        },
        "language" : {
          "href" : "http://localhost/songs/1/language"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost/songs"
    },
    "profile" : {
      "href" : "http://localhost/profile/songs"
    }
  }
}

注意:我也试过这个配置

@Bean
fun repositoryRestConfigurer(): RepositoryRestConfigurer {
    return object : RepositoryRestConfigurerAdapter() {
        override fun configureRepositoryRestConfiguration(config: RepositoryRestConfiguration?) {
            config!!.exposeIdsFor(Language::class.java)
        }
    }
}

【问题讨论】:

    标签: json spring-data-rest


    【解决方案1】:

    我在这里找到了我的解决方案https://stackoverflow.com/a/38165158/2248405

    使用 SpringExpression 语言 (SpEL) 可以将所有内容都放在同一个对象中:

    @Projection(name = "fullDetails", types = arrayOf(Song::class))
    interface SongsFullDetailsProjection {
        fun getId(): Long
        fun getTitle(): String
    
        @Value("#{target.getArtist()?.getId()}")
        fun getArtistId(): Long?
    
        @Value("#{target.getSongType()?.getId()}")
        fun getSongTypeId(): Long?
    
    
        @Value("#{target.getLanguage()?.getId()}")
        fun getLanguageId(): Long?
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-08
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 2015-04-18
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      相关资源
      最近更新 更多