How to get Many To One object displayed in JSON format









up vote
0
down vote

favorite
1












I have two entities - BaseEvent (sport event) and Team:



Team:



@Entity
@Table(name = "teams")
@EntityListeners(AuditingEntityListener.class)
public class Team extends AbstractPersistable<Long>
private Long id;

@NotBlank
private String nameOfTeam;

// we will create one transient field for leagueId
@Transient
private Long leagueId;

@ManyToOne
@JoinColumn(name = "league_id")
@JsonBackReference
private League league;

// team promenlivata ot player
@OneToMany(targetEntity = Player.class, mappedBy = "team", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
private Set<Player> players = new HashSet<>();



public Team(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Team()



public League getLeague()
return league;


public void setLeague(League league)
this.league = league;


public String getNameOfTeam()
return nameOfTeam;


public void setNameOfTeam(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Long getLeagueId()
return leagueId;


public void setLeagueId(Long leagueId)
this.leagueId = leagueId;


public Set<Player> getPlayers()
return players;


public void setPlayers(Set<Player> players)
this.players = players;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




BaseEntity:



 @Entity
@Table(name = "base_events")
@EntityListeners(AuditingEntityListener.class)
public class BaseEvent extends AbstractPersistable<Long>

private Long id;


@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
@NotNull(message = "Start time cannot be empty")
@Column
private Date startTime;


// we will create one transient field for teamId
@Transient
private Long firstTeamId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "first_team_id")
@JsonBackReference
private Team firstTeam;

public BaseEvent()

public BaseEvent(Date startTime)
this.startTime = startTime;


public Date getStartTime()
return startTime;


public void setStartTime(Date startTime)
this.startTime = startTime;


public Long getFirstTeamId()
return firstTeamId;


public void setFirstTeamId(Long firstTeamId)
this.firstTeamId = firstTeamId;


public Team getFirstTeam()
return firstTeam;


public void setFirstTeam(Team firstTeam)
this.firstTeam = firstTeam;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




I have BaseEventDAO and BaseEventController:



// DATA ACCESS OBJECT
@Service
public class BaseEventDAO

@Autowired
private BaseEventRepository baseEventRepository;

/* to save an baseEvent in DB */

public BaseEvent save(BaseEvent baseEvent)
return this.baseEventRepository.save(baseEvent);


/* search all baseEvents */

public List<BaseEvent> findAll()
return this.baseEventRepository.findAll();


/* get an baseEvent */

public BaseEvent findOne(Long baseEventId)
return this.baseEventRepository.findOne(baseEventId);


/* delete an baseEvent */

public void delete(BaseEvent baseEvent)
this.baseEventRepository.delete(baseEvent);




BaseEventController:



@RestController
@RequestMapping("/sportapp")
public class BaseEventController

@Autowired
BaseEventDAO baseEventDAO;

/* to save an baseEvent */
@PostMapping("/baseEvent")
public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
return this.baseEventDAO.save(baseEvent);


/* get all baseEvents */
@GetMapping("/baseEvents")
public List<BaseEvent> getAllBaseEvents()
return this.baseEventDAO.findAll();


/* get an baseEvent by ID */
@GetMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> getBaseEventById(@PathVariable(value = "id") Long baseEventId)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

return ResponseEntity.ok().body(baseEvent);


/* update an baseEvent */
// TO DO SET THE NEW PROPERTIES OBJECT
@PutMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> updateBaseEvent(@PathVariable(value = "id") Long baseEventId,
@Valid @RequestBody BaseEvent baseEventDetails)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();


baseEvent.setStartTime(baseEventDetails.getStartTime());

BaseEvent updateBaseEvent = this.baseEventDAO.save(baseEvent);
return ResponseEntity.ok().body(updateBaseEvent);



/* delete an baseEvent */
@DeleteMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> deleteBaseEvent(@PathVariable(value = "id") Long baseEventId)

BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

this.baseEventDAO.delete(baseEvent);

return ResponseEntity.ok().build();





When i do PostMapping in Postman (/baseEvent):




"startTime" : "01/01/2019 22:22:22",
"firstTeamId" : 1



Object BaseEvent is being saved to the DB (response):




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"new": false



But when i do GetMapping to get this object (/baseEvents/2),This is the response:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": null,
"new": false



I think what i need is:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"firstTeam" :
"id" : 1,
"nameOfTeam": "Barca",
"leagueId": null,
"players": ,
"new": false
,
"new": false



I have two problems I can't solve. First one is ("firstTeamId": null) should say 1 not "null". Second one I'm not getting the mapped Team object (firstTeam) so the front-end can use it.



First time asking a question, please excuse me and tell me if you need more details.










share|improve this question



















  • 1




    fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/…, docs.oracle.com/javaee/7/api/javax/persistence/Transient.html
    – JB Nizet
    Nov 11 at 19:34










  • @JBNizet I've read that JsonBackReference is two-way linkage between fields so i removed it. But when i do Post i want to specify the ID of firstTeam by ID (not by JSON Team object). And when i do Get, there, i want to see firstTeam as a JSON object with its properties. I don't know if this is even possible.
    – I.Stanev
    Nov 11 at 20:44















up vote
0
down vote

favorite
1












I have two entities - BaseEvent (sport event) and Team:



Team:



@Entity
@Table(name = "teams")
@EntityListeners(AuditingEntityListener.class)
public class Team extends AbstractPersistable<Long>
private Long id;

@NotBlank
private String nameOfTeam;

// we will create one transient field for leagueId
@Transient
private Long leagueId;

@ManyToOne
@JoinColumn(name = "league_id")
@JsonBackReference
private League league;

// team promenlivata ot player
@OneToMany(targetEntity = Player.class, mappedBy = "team", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
private Set<Player> players = new HashSet<>();



public Team(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Team()



public League getLeague()
return league;


public void setLeague(League league)
this.league = league;


public String getNameOfTeam()
return nameOfTeam;


public void setNameOfTeam(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Long getLeagueId()
return leagueId;


public void setLeagueId(Long leagueId)
this.leagueId = leagueId;


public Set<Player> getPlayers()
return players;


public void setPlayers(Set<Player> players)
this.players = players;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




BaseEntity:



 @Entity
@Table(name = "base_events")
@EntityListeners(AuditingEntityListener.class)
public class BaseEvent extends AbstractPersistable<Long>

private Long id;


@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
@NotNull(message = "Start time cannot be empty")
@Column
private Date startTime;


// we will create one transient field for teamId
@Transient
private Long firstTeamId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "first_team_id")
@JsonBackReference
private Team firstTeam;

public BaseEvent()

public BaseEvent(Date startTime)
this.startTime = startTime;


public Date getStartTime()
return startTime;


public void setStartTime(Date startTime)
this.startTime = startTime;


public Long getFirstTeamId()
return firstTeamId;


public void setFirstTeamId(Long firstTeamId)
this.firstTeamId = firstTeamId;


public Team getFirstTeam()
return firstTeam;


public void setFirstTeam(Team firstTeam)
this.firstTeam = firstTeam;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




I have BaseEventDAO and BaseEventController:



// DATA ACCESS OBJECT
@Service
public class BaseEventDAO

@Autowired
private BaseEventRepository baseEventRepository;

/* to save an baseEvent in DB */

public BaseEvent save(BaseEvent baseEvent)
return this.baseEventRepository.save(baseEvent);


/* search all baseEvents */

public List<BaseEvent> findAll()
return this.baseEventRepository.findAll();


/* get an baseEvent */

public BaseEvent findOne(Long baseEventId)
return this.baseEventRepository.findOne(baseEventId);


/* delete an baseEvent */

public void delete(BaseEvent baseEvent)
this.baseEventRepository.delete(baseEvent);




BaseEventController:



@RestController
@RequestMapping("/sportapp")
public class BaseEventController

@Autowired
BaseEventDAO baseEventDAO;

/* to save an baseEvent */
@PostMapping("/baseEvent")
public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
return this.baseEventDAO.save(baseEvent);


/* get all baseEvents */
@GetMapping("/baseEvents")
public List<BaseEvent> getAllBaseEvents()
return this.baseEventDAO.findAll();


/* get an baseEvent by ID */
@GetMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> getBaseEventById(@PathVariable(value = "id") Long baseEventId)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

return ResponseEntity.ok().body(baseEvent);


/* update an baseEvent */
// TO DO SET THE NEW PROPERTIES OBJECT
@PutMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> updateBaseEvent(@PathVariable(value = "id") Long baseEventId,
@Valid @RequestBody BaseEvent baseEventDetails)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();


baseEvent.setStartTime(baseEventDetails.getStartTime());

BaseEvent updateBaseEvent = this.baseEventDAO.save(baseEvent);
return ResponseEntity.ok().body(updateBaseEvent);



/* delete an baseEvent */
@DeleteMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> deleteBaseEvent(@PathVariable(value = "id") Long baseEventId)

BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

this.baseEventDAO.delete(baseEvent);

return ResponseEntity.ok().build();





When i do PostMapping in Postman (/baseEvent):




"startTime" : "01/01/2019 22:22:22",
"firstTeamId" : 1



Object BaseEvent is being saved to the DB (response):




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"new": false



But when i do GetMapping to get this object (/baseEvents/2),This is the response:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": null,
"new": false



I think what i need is:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"firstTeam" :
"id" : 1,
"nameOfTeam": "Barca",
"leagueId": null,
"players": ,
"new": false
,
"new": false



I have two problems I can't solve. First one is ("firstTeamId": null) should say 1 not "null". Second one I'm not getting the mapped Team object (firstTeam) so the front-end can use it.



First time asking a question, please excuse me and tell me if you need more details.










share|improve this question



















  • 1




    fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/…, docs.oracle.com/javaee/7/api/javax/persistence/Transient.html
    – JB Nizet
    Nov 11 at 19:34










  • @JBNizet I've read that JsonBackReference is two-way linkage between fields so i removed it. But when i do Post i want to specify the ID of firstTeam by ID (not by JSON Team object). And when i do Get, there, i want to see firstTeam as a JSON object with its properties. I don't know if this is even possible.
    – I.Stanev
    Nov 11 at 20:44













up vote
0
down vote

favorite
1









up vote
0
down vote

favorite
1






1





I have two entities - BaseEvent (sport event) and Team:



Team:



@Entity
@Table(name = "teams")
@EntityListeners(AuditingEntityListener.class)
public class Team extends AbstractPersistable<Long>
private Long id;

@NotBlank
private String nameOfTeam;

// we will create one transient field for leagueId
@Transient
private Long leagueId;

@ManyToOne
@JoinColumn(name = "league_id")
@JsonBackReference
private League league;

// team promenlivata ot player
@OneToMany(targetEntity = Player.class, mappedBy = "team", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
private Set<Player> players = new HashSet<>();



public Team(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Team()



public League getLeague()
return league;


public void setLeague(League league)
this.league = league;


public String getNameOfTeam()
return nameOfTeam;


public void setNameOfTeam(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Long getLeagueId()
return leagueId;


public void setLeagueId(Long leagueId)
this.leagueId = leagueId;


public Set<Player> getPlayers()
return players;


public void setPlayers(Set<Player> players)
this.players = players;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




BaseEntity:



 @Entity
@Table(name = "base_events")
@EntityListeners(AuditingEntityListener.class)
public class BaseEvent extends AbstractPersistable<Long>

private Long id;


@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
@NotNull(message = "Start time cannot be empty")
@Column
private Date startTime;


// we will create one transient field for teamId
@Transient
private Long firstTeamId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "first_team_id")
@JsonBackReference
private Team firstTeam;

public BaseEvent()

public BaseEvent(Date startTime)
this.startTime = startTime;


public Date getStartTime()
return startTime;


public void setStartTime(Date startTime)
this.startTime = startTime;


public Long getFirstTeamId()
return firstTeamId;


public void setFirstTeamId(Long firstTeamId)
this.firstTeamId = firstTeamId;


public Team getFirstTeam()
return firstTeam;


public void setFirstTeam(Team firstTeam)
this.firstTeam = firstTeam;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




I have BaseEventDAO and BaseEventController:



// DATA ACCESS OBJECT
@Service
public class BaseEventDAO

@Autowired
private BaseEventRepository baseEventRepository;

/* to save an baseEvent in DB */

public BaseEvent save(BaseEvent baseEvent)
return this.baseEventRepository.save(baseEvent);


/* search all baseEvents */

public List<BaseEvent> findAll()
return this.baseEventRepository.findAll();


/* get an baseEvent */

public BaseEvent findOne(Long baseEventId)
return this.baseEventRepository.findOne(baseEventId);


/* delete an baseEvent */

public void delete(BaseEvent baseEvent)
this.baseEventRepository.delete(baseEvent);




BaseEventController:



@RestController
@RequestMapping("/sportapp")
public class BaseEventController

@Autowired
BaseEventDAO baseEventDAO;

/* to save an baseEvent */
@PostMapping("/baseEvent")
public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
return this.baseEventDAO.save(baseEvent);


/* get all baseEvents */
@GetMapping("/baseEvents")
public List<BaseEvent> getAllBaseEvents()
return this.baseEventDAO.findAll();


/* get an baseEvent by ID */
@GetMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> getBaseEventById(@PathVariable(value = "id") Long baseEventId)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

return ResponseEntity.ok().body(baseEvent);


/* update an baseEvent */
// TO DO SET THE NEW PROPERTIES OBJECT
@PutMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> updateBaseEvent(@PathVariable(value = "id") Long baseEventId,
@Valid @RequestBody BaseEvent baseEventDetails)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();


baseEvent.setStartTime(baseEventDetails.getStartTime());

BaseEvent updateBaseEvent = this.baseEventDAO.save(baseEvent);
return ResponseEntity.ok().body(updateBaseEvent);



/* delete an baseEvent */
@DeleteMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> deleteBaseEvent(@PathVariable(value = "id") Long baseEventId)

BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

this.baseEventDAO.delete(baseEvent);

return ResponseEntity.ok().build();





When i do PostMapping in Postman (/baseEvent):




"startTime" : "01/01/2019 22:22:22",
"firstTeamId" : 1



Object BaseEvent is being saved to the DB (response):




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"new": false



But when i do GetMapping to get this object (/baseEvents/2),This is the response:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": null,
"new": false



I think what i need is:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"firstTeam" :
"id" : 1,
"nameOfTeam": "Barca",
"leagueId": null,
"players": ,
"new": false
,
"new": false



I have two problems I can't solve. First one is ("firstTeamId": null) should say 1 not "null". Second one I'm not getting the mapped Team object (firstTeam) so the front-end can use it.



First time asking a question, please excuse me and tell me if you need more details.










share|improve this question















I have two entities - BaseEvent (sport event) and Team:



Team:



@Entity
@Table(name = "teams")
@EntityListeners(AuditingEntityListener.class)
public class Team extends AbstractPersistable<Long>
private Long id;

@NotBlank
private String nameOfTeam;

// we will create one transient field for leagueId
@Transient
private Long leagueId;

@ManyToOne
@JoinColumn(name = "league_id")
@JsonBackReference
private League league;

// team promenlivata ot player
@OneToMany(targetEntity = Player.class, mappedBy = "team", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonManagedReference
private Set<Player> players = new HashSet<>();



public Team(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Team()



public League getLeague()
return league;


public void setLeague(League league)
this.league = league;


public String getNameOfTeam()
return nameOfTeam;


public void setNameOfTeam(String nameOfTeam)
this.nameOfTeam = nameOfTeam;


public Long getLeagueId()
return leagueId;


public void setLeagueId(Long leagueId)
this.leagueId = leagueId;


public Set<Player> getPlayers()
return players;


public void setPlayers(Set<Player> players)
this.players = players;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




BaseEntity:



 @Entity
@Table(name = "base_events")
@EntityListeners(AuditingEntityListener.class)
public class BaseEvent extends AbstractPersistable<Long>

private Long id;


@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
@NotNull(message = "Start time cannot be empty")
@Column
private Date startTime;


// we will create one transient field for teamId
@Transient
private Long firstTeamId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "first_team_id")
@JsonBackReference
private Team firstTeam;

public BaseEvent()

public BaseEvent(Date startTime)
this.startTime = startTime;


public Date getStartTime()
return startTime;


public void setStartTime(Date startTime)
this.startTime = startTime;


public Long getFirstTeamId()
return firstTeamId;


public void setFirstTeamId(Long firstTeamId)
this.firstTeamId = firstTeamId;


public Team getFirstTeam()
return firstTeam;


public void setFirstTeam(Team firstTeam)
this.firstTeam = firstTeam;


@Override
public Long getId()
return id;


@Override
public void setId(Long id)
this.id = id;




I have BaseEventDAO and BaseEventController:



// DATA ACCESS OBJECT
@Service
public class BaseEventDAO

@Autowired
private BaseEventRepository baseEventRepository;

/* to save an baseEvent in DB */

public BaseEvent save(BaseEvent baseEvent)
return this.baseEventRepository.save(baseEvent);


/* search all baseEvents */

public List<BaseEvent> findAll()
return this.baseEventRepository.findAll();


/* get an baseEvent */

public BaseEvent findOne(Long baseEventId)
return this.baseEventRepository.findOne(baseEventId);


/* delete an baseEvent */

public void delete(BaseEvent baseEvent)
this.baseEventRepository.delete(baseEvent);




BaseEventController:



@RestController
@RequestMapping("/sportapp")
public class BaseEventController

@Autowired
BaseEventDAO baseEventDAO;

/* to save an baseEvent */
@PostMapping("/baseEvent")
public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
return this.baseEventDAO.save(baseEvent);


/* get all baseEvents */
@GetMapping("/baseEvents")
public List<BaseEvent> getAllBaseEvents()
return this.baseEventDAO.findAll();


/* get an baseEvent by ID */
@GetMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> getBaseEventById(@PathVariable(value = "id") Long baseEventId)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

return ResponseEntity.ok().body(baseEvent);


/* update an baseEvent */
// TO DO SET THE NEW PROPERTIES OBJECT
@PutMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> updateBaseEvent(@PathVariable(value = "id") Long baseEventId,
@Valid @RequestBody BaseEvent baseEventDetails)
BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();


baseEvent.setStartTime(baseEventDetails.getStartTime());

BaseEvent updateBaseEvent = this.baseEventDAO.save(baseEvent);
return ResponseEntity.ok().body(updateBaseEvent);



/* delete an baseEvent */
@DeleteMapping("/baseEvents/id")
public ResponseEntity<BaseEvent> deleteBaseEvent(@PathVariable(value = "id") Long baseEventId)

BaseEvent baseEvent = this.baseEventDAO.findOne(baseEventId);
if (baseEvent == null)
return ResponseEntity.notFound().build();

this.baseEventDAO.delete(baseEvent);

return ResponseEntity.ok().build();





When i do PostMapping in Postman (/baseEvent):




"startTime" : "01/01/2019 22:22:22",
"firstTeamId" : 1



Object BaseEvent is being saved to the DB (response):




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"new": false



But when i do GetMapping to get this object (/baseEvents/2),This is the response:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": null,
"new": false



I think what i need is:




"id": 2,
"startTime": "01/01/2019 22:22:22",
"firstTeamId": 1,
"firstTeam" :
"id" : 1,
"nameOfTeam": "Barca",
"leagueId": null,
"players": ,
"new": false
,
"new": false



I have two problems I can't solve. First one is ("firstTeamId": null) should say 1 not "null". Second one I'm not getting the mapped Team object (firstTeam) so the front-end can use it.



First time asking a question, please excuse me and tell me if you need more details.







java mysql hibernate rest spring-boot






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 22:08

























asked Nov 11 at 19:29









I.Stanev

235




235







  • 1




    fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/…, docs.oracle.com/javaee/7/api/javax/persistence/Transient.html
    – JB Nizet
    Nov 11 at 19:34










  • @JBNizet I've read that JsonBackReference is two-way linkage between fields so i removed it. But when i do Post i want to specify the ID of firstTeam by ID (not by JSON Team object). And when i do Get, there, i want to see firstTeam as a JSON object with its properties. I don't know if this is even possible.
    – I.Stanev
    Nov 11 at 20:44













  • 1




    fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/…, docs.oracle.com/javaee/7/api/javax/persistence/Transient.html
    – JB Nizet
    Nov 11 at 19:34










  • @JBNizet I've read that JsonBackReference is two-way linkage between fields so i removed it. But when i do Post i want to specify the ID of firstTeam by ID (not by JSON Team object). And when i do Get, there, i want to see firstTeam as a JSON object with its properties. I don't know if this is even possible.
    – I.Stanev
    Nov 11 at 20:44








1




1




fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/…, docs.oracle.com/javaee/7/api/javax/persistence/Transient.html
– JB Nizet
Nov 11 at 19:34




fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/…, docs.oracle.com/javaee/7/api/javax/persistence/Transient.html
– JB Nizet
Nov 11 at 19:34












@JBNizet I've read that JsonBackReference is two-way linkage between fields so i removed it. But when i do Post i want to specify the ID of firstTeam by ID (not by JSON Team object). And when i do Get, there, i want to see firstTeam as a JSON object with its properties. I don't know if this is even possible.
– I.Stanev
Nov 11 at 20:44





@JBNizet I've read that JsonBackReference is two-way linkage between fields so i removed it. But when i do Post i want to specify the ID of firstTeam by ID (not by JSON Team object). And when i do Get, there, i want to see firstTeam as a JSON object with its properties. I don't know if this is even possible.
– I.Stanev
Nov 11 at 20:44













2 Answers
2






active

oldest

votes

















up vote
0
down vote













You need change FetchType.LAZY to FetchType.EAGER in order to be stronger persistented when Hibernate does the query to get the team..



@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "first_team_id")
@JsonBackReference
private Team firstTeam;





share|improve this answer




















  • Still says "firstTeamId" : null :(
    – I.Stanev
    Nov 12 at 11:13










  • So I guess that you have an issue with relationship when saving a foreign key.
    – Jonathan Johx
    Nov 12 at 16:13

















up vote
0
down vote



accepted










I fixed it as i changed the BaseEventController Post method:



@Autowired
BaseEventDAO baseEventDAO;


@Autowired
TeamDAO teamDAO;

/* to save an baseEvent */
@PostMapping("/baseEvent")
public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
Team team = this.teamDAO.findOne(baseEvent.getFirstTeamId());
BaseEvent event = new BaseEvent();
event.setStartTime(baseEvent.getStartTime());
event.setFirstTeam(team);
event.setFirstTeamId(baseEvent.getFirstTeamId());
return this.baseEventDAO.save(event);



And removed the @Transient from firstTeamId and changed the join column:



@Column(name="first_team_id")
private Long firstTeamId;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "team_id", referencedColumnName = "id")
private Team firstTeam;





share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252395%2fhow-to-get-many-to-one-object-displayed-in-json-format%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    You need change FetchType.LAZY to FetchType.EAGER in order to be stronger persistented when Hibernate does the query to get the team..



    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "first_team_id")
    @JsonBackReference
    private Team firstTeam;





    share|improve this answer




















    • Still says "firstTeamId" : null :(
      – I.Stanev
      Nov 12 at 11:13










    • So I guess that you have an issue with relationship when saving a foreign key.
      – Jonathan Johx
      Nov 12 at 16:13














    up vote
    0
    down vote













    You need change FetchType.LAZY to FetchType.EAGER in order to be stronger persistented when Hibernate does the query to get the team..



    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "first_team_id")
    @JsonBackReference
    private Team firstTeam;





    share|improve this answer




















    • Still says "firstTeamId" : null :(
      – I.Stanev
      Nov 12 at 11:13










    • So I guess that you have an issue with relationship when saving a foreign key.
      – Jonathan Johx
      Nov 12 at 16:13












    up vote
    0
    down vote










    up vote
    0
    down vote









    You need change FetchType.LAZY to FetchType.EAGER in order to be stronger persistented when Hibernate does the query to get the team..



    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "first_team_id")
    @JsonBackReference
    private Team firstTeam;





    share|improve this answer












    You need change FetchType.LAZY to FetchType.EAGER in order to be stronger persistented when Hibernate does the query to get the team..



    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "first_team_id")
    @JsonBackReference
    private Team firstTeam;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 11 at 21:10









    Jonathan Johx

    620111




    620111











    • Still says "firstTeamId" : null :(
      – I.Stanev
      Nov 12 at 11:13










    • So I guess that you have an issue with relationship when saving a foreign key.
      – Jonathan Johx
      Nov 12 at 16:13
















    • Still says "firstTeamId" : null :(
      – I.Stanev
      Nov 12 at 11:13










    • So I guess that you have an issue with relationship when saving a foreign key.
      – Jonathan Johx
      Nov 12 at 16:13















    Still says "firstTeamId" : null :(
    – I.Stanev
    Nov 12 at 11:13




    Still says "firstTeamId" : null :(
    – I.Stanev
    Nov 12 at 11:13












    So I guess that you have an issue with relationship when saving a foreign key.
    – Jonathan Johx
    Nov 12 at 16:13




    So I guess that you have an issue with relationship when saving a foreign key.
    – Jonathan Johx
    Nov 12 at 16:13












    up vote
    0
    down vote



    accepted










    I fixed it as i changed the BaseEventController Post method:



    @Autowired
    BaseEventDAO baseEventDAO;


    @Autowired
    TeamDAO teamDAO;

    /* to save an baseEvent */
    @PostMapping("/baseEvent")
    public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
    Team team = this.teamDAO.findOne(baseEvent.getFirstTeamId());
    BaseEvent event = new BaseEvent();
    event.setStartTime(baseEvent.getStartTime());
    event.setFirstTeam(team);
    event.setFirstTeamId(baseEvent.getFirstTeamId());
    return this.baseEventDAO.save(event);



    And removed the @Transient from firstTeamId and changed the join column:



    @Column(name="first_team_id")
    private Long firstTeamId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "team_id", referencedColumnName = "id")
    private Team firstTeam;





    share|improve this answer
























      up vote
      0
      down vote



      accepted










      I fixed it as i changed the BaseEventController Post method:



      @Autowired
      BaseEventDAO baseEventDAO;


      @Autowired
      TeamDAO teamDAO;

      /* to save an baseEvent */
      @PostMapping("/baseEvent")
      public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
      Team team = this.teamDAO.findOne(baseEvent.getFirstTeamId());
      BaseEvent event = new BaseEvent();
      event.setStartTime(baseEvent.getStartTime());
      event.setFirstTeam(team);
      event.setFirstTeamId(baseEvent.getFirstTeamId());
      return this.baseEventDAO.save(event);



      And removed the @Transient from firstTeamId and changed the join column:



      @Column(name="first_team_id")
      private Long firstTeamId;

      @ManyToOne(cascade = CascadeType.ALL)
      @JoinColumn(name = "team_id", referencedColumnName = "id")
      private Team firstTeam;





      share|improve this answer






















        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        I fixed it as i changed the BaseEventController Post method:



        @Autowired
        BaseEventDAO baseEventDAO;


        @Autowired
        TeamDAO teamDAO;

        /* to save an baseEvent */
        @PostMapping("/baseEvent")
        public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
        Team team = this.teamDAO.findOne(baseEvent.getFirstTeamId());
        BaseEvent event = new BaseEvent();
        event.setStartTime(baseEvent.getStartTime());
        event.setFirstTeam(team);
        event.setFirstTeamId(baseEvent.getFirstTeamId());
        return this.baseEventDAO.save(event);



        And removed the @Transient from firstTeamId and changed the join column:



        @Column(name="first_team_id")
        private Long firstTeamId;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "team_id", referencedColumnName = "id")
        private Team firstTeam;





        share|improve this answer












        I fixed it as i changed the BaseEventController Post method:



        @Autowired
        BaseEventDAO baseEventDAO;


        @Autowired
        TeamDAO teamDAO;

        /* to save an baseEvent */
        @PostMapping("/baseEvent")
        public BaseEvent createBaseEvent(@Valid @RequestBody BaseEvent baseEvent)
        Team team = this.teamDAO.findOne(baseEvent.getFirstTeamId());
        BaseEvent event = new BaseEvent();
        event.setStartTime(baseEvent.getStartTime());
        event.setFirstTeam(team);
        event.setFirstTeamId(baseEvent.getFirstTeamId());
        return this.baseEventDAO.save(event);



        And removed the @Transient from firstTeamId and changed the join column:



        @Column(name="first_team_id")
        private Long firstTeamId;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "team_id", referencedColumnName = "id")
        private Team firstTeam;






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 13 at 20:56









        I.Stanev

        235




        235



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53252395%2fhow-to-get-many-to-one-object-displayed-in-json-format%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3

            Museum of Modern and Contemporary Art of Trento and Rovereto