I currently have a simple Spring Boot app set up with two entities - AppUser and Settings. One AppUser has many Settings in a List like so -
AppUser -
@Entity
@Table(name = "app_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AppUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "first_name", nullable = false)
private String firstName;
@NotNull
@Column(name = "last_name", nullable = false)
private String lastName;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "appUser")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private List<Setting> settings = new ArrayList<>();
// getters and setters ...
Setting -
@Entity
@Table(name = "setting")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Setting implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@JsonIgnore
private Long id;
@Column(name = "test_setting_1")
private Boolean testSetting1;
@Column(name = "test_setting_2")
private Boolean testSetting2;
@ManyToOne
@JsonIgnore
private AppUser appUser;
// getters and setters ...
I'm currently using the repository to return a List of settings by using
List<Setting> findByAppUserId(Long id);
Which is being called by the controller -
@GetMapping("/settings")
public List<Setting> getAllSettings() {
return settingRepository.findByAppUserId(1001L);
}
When I return that via a controller though, I get an array of objects like this -
[
{
"testSetting1": true
},
{
"testSetting2": true
}
]
What I'd like to return to the front end is a single object with all the settings in it, something like this -
{
"testSetting1": true,
"testSetting2": true
}
I'm curious what's the best way to do this in Spring?