Deserialization Json file with objectMapper in Java REST app - java

Hi Everyone, I hava a Json file like this:
{
"Events":[{
"sport_event_id": "sr:sport_event:27636100",
"start_date": "2021-06-22T18:00:00+00:00",
"sport_name": "Soccer",
"competition_name": "UEFA Champions League",
"competition_id": "sr:competition:7",
"season_name": "UEFA Champions League 21/22",
"competitors": [
{
"id": "sr:competitor:37863",
"name": "SS Folgore Falciano Calcio",
"country": "San Marino",
"country_code": "SMR",
"abbreviation": "FFC",
"qualifier": "home",
"gender": "male"
},
{
"id": "sr:competitor:277829",
"name": "FC Prishtina",
"country": "Kosovo",
"country_code": "KOS",
"abbreviation": "PRI",
"qualifier": "away",
"gender": "male"
}
],
"venue": {
"id": "sr:venue:8329",
"name": "Elbasan Arena",
"capacity": 12500,
"city_name": "Elbasan",
"country_name": "Albania",
"map_coordinates": "41.115875,20.091992",
"country_code": "ALB"
},
"probability_home_team_winner": 2.5,
"probability_draw": 88.1,
"probability_away_team_winner": 9.4
}
]
}
I would like to read the json from the file and display the contents.
For Json deserialization, I created appropriate Entity,Repo and Service classes for:
Competitor, Venue, Events
Venue Class:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"name",
"capacity",
"city_name",
"country_name",
"map_coordinates",
"country_code"
})
#Entity
public class Venue implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonIgnore
private Long venueId;
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("capacity")
private int capacity;
#JsonProperty("city_name")
private String cityName;
#JsonProperty("country_name")
private String countryName;
#JsonProperty("map_coordinates")
private String mapCoordinates;
#JsonProperty("country_code")
private String countryCode;
public Venue() {
}
public Venue(Long venueId, String id, String name, int capacity, String cityName, String countryName,
String mapCoordinates, String countryCode) {
this.venueId = venueId;
this.id=id;
this.name = name;
this.capacity = capacity;
this.cityName = cityName;
this.countryName = countryName;
this.mapCoordinates = mapCoordinates;
this.countryCode = countryCode;
}
public Long getVenueId() {
return venueId;
}
public void setVenueId(Long venueId) {
this.venueId = venueId;
}
#JsonProperty("id")
public String getId() {
return id;
}
#JsonProperty("id")
public void setId(String id) {
this.id = id;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("capacity")
public Integer getCapacity() {
return capacity;
}
#JsonProperty("capacity")
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
#JsonProperty("city_name")
public String getCityName() {
return cityName;
}
#JsonProperty("city_name")
public void setCityName(String cityName) {
this.cityName = cityName;
}
#JsonProperty("country_name")
public String getCountryName() {
return countryName;
}
#JsonProperty("country_name")
public void setCountryName(String countryName) {
this.countryName = countryName;
}
#JsonProperty("map_coordinates")
public String getMapCoordinates() {
return mapCoordinates;
}
#JsonProperty("map_coordinates")
public void setMapCoordinates(String mapCoordinates) {
this.mapCoordinates = mapCoordinates;
}
#JsonProperty("country_code")
public String getCountryCode() {
return countryCode;
}
#JsonProperty("country_code")
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Venue venue = (Venue) o;
return capacity == venue.capacity && Objects.equals(venueId, venue.venueId) && Objects.equals(id, venue.id) && Objects.equals(name, venue.name) && Objects.equals(cityName, venue.cityName) && Objects.equals(countryName, venue.countryName) && Objects.equals(mapCoordinates, venue.mapCoordinates) && Objects.equals(countryCode, venue.countryCode);
}
#Override
public int hashCode() {
return Objects.hash(venueId, id, name, capacity, cityName, countryName, mapCoordinates, countryCode);
}
#Override
public String toString() {
return "Venue{" +
"venueId=" + venueId +
", id='" + id + '\'' +
", name='" + name + '\'' +
", capacity=" + capacity +
", cityName='" + cityName + '\'' +
", countryName='" + countryName + '\'' +
", mapCoordinates='" + mapCoordinates + '\'' +
", countryCode='" + countryCode + '\'' +
'}';
}
}
**Competitor Class:
**
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"name",
"country",
"country_code",
"abbreviation",
"qualifier",
"gender"
})
#Entity
public class Competitor implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonIgnore
private Long competitorId;
#JsonProperty("id")
private String id;
#JsonProperty("name")
private String name;
#JsonProperty("country")
private String country;
#JsonProperty("country_code")
private String countryCode;
#JsonProperty("abbreviation")
private String abbreviation;
#JsonProperty("qualifier")
private String qualifier;
#JsonProperty("gender")
private String gender;
public Competitor() {
}
public Competitor(Long competitorId, String id, String name, String country, String countryCode, String abbreviation,
String qualifier, String gender) {
this.competitorId = competitorId;
this.id=id;
this.name = name;
this.country = country;
this.countryCode = countryCode;
this.abbreviation = abbreviation;
this.qualifier = qualifier;
this.gender = gender;
}
public Long getCompetitorId() {
return competitorId;
}
public void setCompetitorId(Long id) {
this.competitorId = id;
}
#JsonProperty("id")
public String getId() {
return id;
}
#JsonProperty("id")
public void setId(String id) {
this.id = id;
}
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("country")
public String getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(String country) {
this.country = country;
}
#JsonProperty("country_code")
public String getCountryCode() {
return countryCode;
}
#JsonProperty("country_code")
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#JsonProperty("abbreviation")
public String getAbbreviation() {
return abbreviation;
}
#JsonProperty("abbreviation")
public void setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
}
#JsonProperty("qualifier")
public String getQualifier() {
return qualifier;
}
#JsonProperty("qualifier")
public void setQualifier(String qualifier) {
this.qualifier = qualifier;
}
#JsonProperty("gender")
public String getGender() {
return gender;
}
#JsonProperty("gender")
public void setGender(String gender) {
this.gender = gender;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Competitor that = (Competitor) o;
return Objects.equals(competitorId, that.competitorId) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(country, that.country) && Objects.equals(countryCode, that.countryCode) && Objects.equals(abbreviation, that.abbreviation) && Objects.equals(qualifier, that.qualifier) && Objects.equals(gender, that.gender);
}
#Override
public int hashCode() {
return Objects.hash(competitorId, id, name, country, countryCode, abbreviation, qualifier, gender);
}
#Override
public String toString() {
return "Competitor{" +
"competitorId=" + competitorId +
", id='" + id + '\'' +
", name='" + name + '\'' +
", country='" + country + '\'' +
", countryCode='" + countryCode + '\'' +
", abbreviation='" + abbreviation + '\'' +
", qualifier='" + qualifier + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
Events Class:
#Entity
#JsonPropertyOrder({
"sport_event_id",
"start_date",
"sport_name",
"competition_name",
"competition_id",
"season_name",
"competitors",
"venue",
"probability_home_team_winner",
"probability_draw",
"probability_away_team_winner"
})
public class Events implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonIgnore
private Long eventsId;
#JsonProperty("sport_event_id")
private String sportEventId;
#JsonProperty("start_date")
private ZonedDateTime startDate;
#JsonProperty("sport_name")
private String sportName;
#JsonProperty("competition_name")
private String competitionName;
#JsonProperty("competition_id")
private String competitionId;
#JsonProperty("season_name")
private String seasonName;
#OneToMany
#JsonProperty("competitors")
private List<Competitor> competitors;
#ManyToOne
#JoinColumn
#JsonProperty("venue")
private Venue venue;
#JsonProperty("probability_home_team_winner")
private double probabilityHomeTeamWinner;
#JsonProperty("probability_draw")
private double probabilityDraw;
#JsonProperty("probability_away_team_winner")
private double probabilityAwayTeamWinner;
public Events() {
}
public Events(Long eventsId, String sportEventId, ZonedDateTime startDate, String sportName, String competitionName, String competitionId, String seasonName,
List<Competitor> competitors, Venue venue, double probabilityHomeTeamWinner, double probabilityDraw, double probabilityAwayTeamWinner) {
this.sportEventId = sportEventId;
this.startDate = startDate;
this.sportName = sportName;
this.competitionName = competitionName;
this.competitionId = competitionId;
this.seasonName = seasonName;
this.competitors = competitors;
this.venue = venue;
this.probabilityHomeTeamWinner = probabilityHomeTeamWinner;
this.probabilityDraw = probabilityDraw;
this.probabilityAwayTeamWinner = probabilityAwayTeamWinner;
}
public Long getEventsId() {
return eventsId;
}
public void setEventsId(Long eventsId) {
this.eventsId = eventsId;
}
#JsonProperty("sport_event_id")
public String getSportEventId() {
return sportEventId;
}
#JsonProperty("sport_event_id")
public void setSportEventId(String sportEventId) {
this.sportEventId = sportEventId;
}
#JsonProperty("start_date")
public ZonedDateTime getStartDate() {
return startDate;
}
#JsonProperty("start_date")
public void setStartDate(ZonedDateTime startDate) {
this.startDate = startDate;
}
#JsonProperty("sport_name")
public String getSportName() {
return sportName;
}
#JsonProperty("sport_name")
public void setSportName(String sportName) {
this.sportName = sportName;
}
#JsonProperty("competition_name")
public String getCompetitionName() {
return competitionName;
}
#JsonProperty("competition_name")
public void setCompetitionName(String competitionName) {
this.competitionName = competitionName;
}
#JsonProperty("competition_id")
public String getCompetitionId() {
return competitionId;
}
#JsonProperty("competition_id")
public void setCompetitionId(String competitionId) {
this.competitionId = competitionId;
}
#JsonProperty("season_name")
public String getSeasonName() {
return seasonName;
}
#JsonProperty("season_name")
public void setSeasonName(String seasonName) {
this.seasonName = seasonName;
}
#JsonProperty("competitors")
public List<Competitor> getCompetitors() {return competitors; }
#JsonProperty("competitors")
public void setCompetitors(List<Competitor> competitors) {
this.competitors = competitors;
}
#JsonProperty("venue")
public Venue getVenue() {
return venue;
}
#JsonProperty("venue")
public void setVenue(Venue venue) {
this.venue = venue;
}
#JsonProperty("probability_home_team_winner")
public double getProbabilityHomeTeamWinner() {
return probabilityHomeTeamWinner;
}
#JsonProperty("probability_home_team_winner")
public void setProbabilityHomeTeamWinner(double probabilityHomeTeamWinner) {
this.probabilityHomeTeamWinner = probabilityHomeTeamWinner;
}
#JsonProperty("probability_draw")
public double getProbabilityDraw() {
return probabilityDraw;
}
#JsonProperty("probability_draw")
public void setProbabilityDraw(double probabilityDraw) {
this.probabilityDraw = probabilityDraw;
}
#JsonProperty("probability_away_team_winner")
public double getProbabilityAwayTeamWinner() {
return probabilityAwayTeamWinner;
}
#JsonProperty("probability_away_team_winner")
public void setProbabilityAwayTeamWinner(double probabilityAwayTeamWinner) {
this.probabilityAwayTeamWinner = probabilityAwayTeamWinner;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Events events = (Events) o;
return Double.compare(events.probabilityHomeTeamWinner, probabilityHomeTeamWinner) == 0 && Double.compare(events.probabilityDraw, probabilityDraw) == 0 && Double.compare(events.probabilityAwayTeamWinner, probabilityAwayTeamWinner) == 0 && Objects.equals(eventsId, events.eventsId) && Objects.equals(sportEventId, events.sportEventId) && Objects.equals(startDate, events.startDate) && Objects.equals(sportName, events.sportName) && Objects.equals(competitionName, events.competitionName) && Objects.equals(competitionId, events.competitionId) && Objects.equals(seasonName, events.seasonName) && Objects.equals(competitors, events.competitors) && Objects.equals(venue, events.venue);
}
#Override
public int hashCode() {
return Objects.hash(eventsId, sportEventId, startDate, sportName, competitionName, competitionId, seasonName, competitors, venue, probabilityHomeTeamWinner, probabilityDraw, probabilityAwayTeamWinner);
}
#Override
public String toString() {
return "Events{" +
"eventsId=" + eventsId +
", sportEventId='" + sportEventId + '\'' +
", startDate=" + startDate +
", sportName='" + sportName + '\'' +
", competitionName='" + competitionName + '\'' +
", competitionId='" + competitionId + '\'' +
", seasonName='" + seasonName + '\'' +
//", competitors=" + competitors +
", venue=" + venue +
", probabilityHomeTeamWinner=" + probabilityHomeTeamWinner +
", probabilityDraw=" + probabilityDraw +
", probabilityAwayTeamWinner=" + probabilityAwayTeamWinner +
'}';
}
}
In EventsController, I implemented the getItemFromJSon() method which is supposed to return the contents of a Json.
EventsController Class:
#RestController
public class EventsController {
private final ObjectMapper objectMapper;
private final EventsServiceImpl eventsServiceImpl;
public EventsController(EventsServiceImpl eventsServiceImpl, ObjectMapper objectMapper) {
this.eventsServiceImpl = eventsServiceImpl;
this.objectMapper= objectMapper;
}
#GetMapping("/json/events")
public Events getItemFromJson() throws IOException {
/* InputStream inputStream = new FileInputStream(new File("src/main/resources/BE_data.json"));
TypeReference<Events> typeReference = new TypeReference<Events>(){};
return objectMapper.readValue(inputStream,typeReference);
*/
return objectMapper.readValue(new File("src/main/resources/BE_data.json"), Events.class);
}
}
After running the program and calling endpoint, I get a response in the form of :
{
"sport_event_id": null,
"start_date": null,
"sport_name": null,
"competition_name": null,
"competition_id": null,
"season_name": null,
"competitors": null,
"venue": null,
"probability_home_team_winner": 0.0,
"probability_draw": 0.0,
"probability_away_team_winner": 0.0
}
What did I do wrong in my code?
For Json deserialisation I used objectMapper.

Please try these POJO classes. I have used this online tool to autogenerate the POJO Objects
public class Competitor{
public String id;
public String name;
public String country;
public String country_code;
public String abbreviation;
public String qualifier;
public String gender;
}
public class Event{
public String sport_event_id;
public Date start_date;
public String sport_name;
public String competition_name;
public String competition_id;
public String season_name;
public ArrayList<Competitor> competitors;
public Venue venue;
public double probability_home_team_winner;
public double probability_draw;
public double probability_away_team_winner;
}
public class Root{
#JsonProperty("Events")
public ArrayList<Event> events;
}
public class Venue{
public String id;
public String name;
public int capacity;
public String city_name;
public String country_name;
public String map_coordinates;
public String country_code;
}
Then deserialize it like this
return objectMapper.readValue(new File("src/main/resources/BE_data.json"), Root.class);

Related

I had a problem with getting datas from Json output

i was trying to show Json output in my Android app. I'm dropping the site link here: https://jsonplaceholder.typicode.com/users
When i try to show ResponseDTO.java output in AddressPage, it works. But when change it to Address.java or AddressDTO.java, i get null value in my app(in AddressPage)
AddressPage.java:
public class AdressPage extends AppCompatActivity {
String id, usr_name;
List<Address> userAdressList;
TextView street, suite, city, zipcode, latText, lngText;
List<GeoDTO> geoDTOList;
Float lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address_page_adapter);
defVars();
get_parameters();
request();
}
public void get_parameters() {
Bundle bundle = getIntent().getExtras();
id = bundle.getString("post_id");
usr_name = bundle.getString("user_name");
}
public void defVars() {
street = findViewById(R.id.street);
suite = findViewById(R.id.suite);
city = findViewById(R.id.city);
zipcode = findViewById(R.id.zipcode);
latText = findViewById(R.id.lat);
lngText = findViewById(R.id.lng);
}
public void assignment(List<Address> addresses) {
street.setText(""+addresses.get(0).getStreet());
suite.setText(""+addresses.get(0).getSuite());
city.setText(""+addresses.get(0).getCity());
zipcode.setText(""+addresses.get(0).getZipcode());
/*zipcode.setText(id);
street.setText(id);
suite.setText(usr_name);
city.setText(usr_name);*/
}
public void request() {
userAdressList = new ArrayList<>();
Call<List<Address>> call = ManagerAll.getInstance().managerGetAdress(id, usr_name);
call.enqueue(new Callback<List<Address>>() {
#Override
public void onResponse(Call<List<Address>> call, Response<List<Address>> response) {
if (response.isSuccessful()) {
userAdressList = response.body();
assignment(userAdressList);
}
}
#Override
public void onFailure(Call<List<Address>> call, Throwable t) {
}
});
}
}
AddressDTO or Address (Same codes):
public class Address implements Serializable {
private String zipcode;
private Geo geo;
private String suite;
private String city;
private String street;
public void setZipcode(String zipcode){
this.zipcode = zipcode;
}
public String getZipcode(){
return zipcode;
}
public void setGeo(Geo geo){
this.geo = geo;
}
public Geo getGeo(){
return geo;
}
public void setSuite(String suite){
this.suite = suite;
}
public String getSuite(){
return suite;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public void setStreet(String street){
this.street = street;
}
public String getStreet(){
return street;
}
#Override
public String toString(){
return
"Address{" +
"zipcode = '" + zipcode + '\'' +
",geo = '" + geo + '\'' +
",suite = '" + suite + '\'' +
",city = '" + city + '\'' +
",street = '" + street + '\'' +
"}";
}
}
RestApi interface:
public interface RestApi {
#GET("/users")
Call<List<ResponseDTO>> bring();
#GET("/users") Call<List<ResponseDTO>> bringResponse(#Query("id")String id, #Query("username")String usr_name);
#GET("/users") Call<List<Address>> bringAdress(#Query("id")String id, #Query("username")String usr_name);
//#GET("/users") Call<List<GeoDTO>> bringGeo(#Query("id")String id, #Query("username")String usr_name);
}
ManagerAll.java:
public class ManagerAll extends BaseManager {
private static ManagerAll ourInstance = new ManagerAll();
public static synchronized ManagerAll getInstance() {
return ourInstance;
}
public Call<List<ResponseDTO>> bringCall() {
Call<List<ResponseDTO>> x = getRestApi().bring();
return x;
}
public Call<List<Address>> managerGetAdress(String post, String username) {
Call<List<Address>> y = getRestApi().bringAdress(post, username);
return y;
}
public Call<List<ResponseDTO>> managerBringResponse(String post, String username) {
Call<List<ResponseDTO>> z = getRestApi().bringResponse(post, username);
return z;
}
}
This is ResponseDTO:
public class ResponseDTO implements Serializable {
private String website;
private AddressDTO address;
private String phone;
private String name;
private CompanyDTO company;
private int id;
private String email;
private String username;
public void setWebsite(String website){
this.website = website;
}
public String getWebsite(){
return website;
}
public void setAddress(AddressDTO address){
this.address = address;
}
public AddressDTO getAddress(){
return address;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setCompany(CompanyDTO company){
this.company = company;
}
public CompanyDTO getCompany(){
return company;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
#Override
public String toString(){
return
"ResponseDTO{" +
"website = '" + website + '\'' +
",address = '" + address + '\'' +
",phone = '" + phone + '\'' +
",name = '" + name + '\'' +
",company = '" + company + '\'' +
",id = '" + id + '\'' +
",email = '" + email + '\'' +
",username = '" + username + '\'' +
"}";
}
}
As i said, when i set the list in AddressPage AddressDto(or Address) to Response i can get datas. But it gives me null value when i set it to AddressDto.
GeoDTO:
public class GeoDTO implements Serializable {
private String lng;
private String lat;
public void setLng(String lng){
this.lng = lng;
}
public String getLng(){
return lng;
}
public void setLat(String lat){
this.lat = lat;
}
public String getLat(){
return lat;
}
#Override
public String toString(){
return
"GeoDTO{" +
"lng = '" + lng + '\'' +
",lat = '" + lat + '\'' +
"}";
}
}
CompanyDTO:
public class CompanyDTO implements Serializable {
private String bs;
private String catchPhrase;
private String name;
public void setBs(String bs){
this.bs = bs;
}
public String getBs(){
return bs;
}
public void setCatchPhrase(String catchPhrase){
this.catchPhrase = catchPhrase;
}
public String getCatchPhrase(){
return catchPhrase;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
#Override
public String toString(){
return
"CompanyDTO{" +
"bs = '" + bs + '\'' +
",catchPhrase = '" + catchPhrase + '\'' +
",name = '" + name + '\'' +
"}";
}
}
Address class is not similar to your json response so you are not getting data from your service . You can read first ResponseDTO data then read address data from json.

Is this HQL/SQL query possible? Java, Spring Boot

I have multiple Entities mapped to my MySQL database and I can map those entities into relevant objects using Spring's CrudRepository. The three entities are: Snapshot, Market, and Contract
Each Snapshot contains a unique id, a timestamp, and a List of Market objects
Each Market contains a unique primary key id, a nonUniquemarketId, name, url, ...., and List of Contract objects.
Each Contract contains fields regarding pricing information.
The nonUniqueMarketId is an id given by the API I am getting data from. It only occurs once in each Snapshot's List of Market objects
I am wondering if it is possible to get the List of Contracts from a specific Market in List of Markets from a specific Snapshot. That is, if I have a Snapshot's timestamp and a nonUniqueMarketId, is it possible to write a query that looks at all the Snapshots in the DB, gets the one with the given timestamp, then looks at that Snapshot's List of Markets and either gets that Market whose nonUniqueMarketId is given or the List of Contracts field in it?
More generally, I know what Snapshot I want and what Market I want, is it possible to get that specific Market given those two parameters?
Snapshot.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Snapshot{
#Id
private Integer hashId;
#JsonProperty("markets")
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
private List<Market> markets;
private long timestamp;
public Snapshot(List<Market> markets, long timestamp, Integer hashId) {
this.markets = markets;
this.timestamp = timestamp;
this.hashId = hashId;
}
public Snapshot() {
}
public void setMarkets(List<Market> markets){
this.markets = markets;
}
public List<Market> getMarkets(){
return markets;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public Integer getHashId() {
return hashId;
}
public void setHashId(Integer hashId) {
this.hashId = hashId;
}
#Override
public String toString() {
return "Snapshot{" +
"hashId=" + hashId +
", markets=" + markets +
", timestamp=" + timestamp +
'}';
}
}
Market.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.List;
#Entity
public class Market {
#Id
#GeneratedValue
private Integer marketUniqueID;
#JsonProperty("timeStamp")
private String timeStamp;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#ElementCollection(fetch=FetchType.EAGER)
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) //ALL, not persist
#JsonProperty("contracts")
private List<Contract> contracts;
#JsonProperty("url")
private String url;
#JsonProperty("status")
private String status;
public Market(String timeStamp, String image, String name, int id, String shortName, List<Contract> contracts, String url, String status) {
this.timeStamp = timeStamp;
this.image = image;
this.name = name;
this.id = id;
this.shortName = shortName;
this.contracts = contracts;
this.url = url;
this.status = status;
}
public Market() {
}
public Integer getMarketUniqueID() {
return marketUniqueID;
}
public void setMarketUniqueID(Integer marketUniqueID) {
this.marketUniqueID = marketUniqueID;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public List<Contract> getContracts() {
return contracts;
}
public void setContracts(List<Contract> contracts) {
this.contracts = contracts;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "\n\nMarket{" +
"marketUniqueID='" + marketUniqueID + '\'' +
", timeStamp='" + timeStamp + '\'' +
", image='" + image + '\'' +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", contracts=" + contracts +
", url='" + url + '\'' +
", status='" + status + '\'' +
"\n}";
}
}
Contract.java
package com.axlor.predictionassistantanalyzer.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;
#Entity
public class Contract {
/*
Why do we need contractUniqueID?:
See explanation in Market.java
Basically, the JsonProperty 'id' field cannot be used as a primary key in the database. We need to create one, so we generate it here.
*/
#Id
#GeneratedValue
private Integer contractUniqueID;
#Transient
#JsonProperty("image")
private String image;
#JsonProperty("lastClosePrice")
private double lastClosePrice;
#JsonProperty("bestBuyNoCost")
private double bestBuyNoCost;
#JsonProperty("bestSellNoCost")
private double bestSellNoCost;
#Transient
#JsonProperty("displayOrder")
private int displayOrder; //not sure what this even is supposed to do lol
#JsonProperty("dateEnd")
private String dateEnd;
#JsonProperty("bestSellYesCost")
private double bestSellYesCost;
#JsonProperty("bestBuyYesCost")
private double bestBuyYesCost;
#JsonProperty("lastTradePrice")
private double lastTradePrice;
#JsonProperty("name")
private String name;
#JsonProperty("id")
private int id;
#Transient
#JsonProperty("shortName")
private String shortName;
#JsonProperty("status")
private String status;
public Contract(String image, double lastClosePrice, double bestBuyNoCost, double bestSellNoCost, int displayOrder, String dateEnd, double bestSellYesCost, double bestBuyYesCost, double lastTradePrice, String name, int id, String shortName, String status) {
this.image = image;
this.lastClosePrice = lastClosePrice;
this.bestBuyNoCost = bestBuyNoCost;
this.bestSellNoCost = bestSellNoCost;
this.displayOrder = displayOrder;
this.dateEnd = dateEnd;
this.bestSellYesCost = bestSellYesCost;
this.bestBuyYesCost = bestBuyYesCost;
this.lastTradePrice = lastTradePrice;
this.name = name;
this.id = id;
this.shortName = shortName;
this.status = status;
}
public Contract() {
}
public Integer getContractUniqueID() {
return contractUniqueID;
}
public void setContractUniqueID(Integer contractUniqueID) {
this.contractUniqueID = contractUniqueID;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getLastClosePrice() {
return lastClosePrice;
}
public void setLastClosePrice(double lastClosePrice) {
this.lastClosePrice = lastClosePrice;
}
public double getBestBuyNoCost() {
return bestBuyNoCost;
}
public void setBestBuyNoCost(double bestBuyNoCost) {
this.bestBuyNoCost = bestBuyNoCost;
}
public double getBestSellNoCost() {
return bestSellNoCost;
}
public void setBestSellNoCost(double bestSellNoCost) {
this.bestSellNoCost = bestSellNoCost;
}
public int getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
public String getDateEnd() {
return dateEnd;
}
public void setDateEnd(String dateEnd) {
this.dateEnd = dateEnd;
}
public double getBestSellYesCost() {
return bestSellYesCost;
}
public void setBestSellYesCost(double bestSellYesCost) {
this.bestSellYesCost = bestSellYesCost;
}
public double getBestBuyYesCost() {
return bestBuyYesCost;
}
public void setBestBuyYesCost(double bestBuyYesCost) {
this.bestBuyYesCost = bestBuyYesCost;
}
public double getLastTradePrice() {
return lastTradePrice;
}
public void setLastTradePrice(double lastTradePrice) {
this.lastTradePrice = lastTradePrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "Contract{" +
"contractUniqueID='" + contractUniqueID + '\'' +
", image='" + image + '\'' +
", lastClosePrice=" + lastClosePrice +
", bestBuyNoCost=" + bestBuyNoCost +
", bestSellNoCost=" + bestSellNoCost +
", displayOrder=" + displayOrder +
", dateEnd='" + dateEnd + '\'' +
", bestSellYesCost=" + bestSellYesCost +
", bestBuyYesCost=" + bestBuyYesCost +
", lastTradePrice=" + lastTradePrice +
", name='" + name + '\'' +
", id=" + id +
", shortName='" + shortName + '\'' +
", status='" + status + '\'' +
'}';
}
}

Getting null while Parsing XML

I'm trying to parse strig xml using JaxB API.
Below is my code
XML
http://www.devx.com/supportitems/showSupportItem.php?co=38898&supportitem=listing1
Pojo Classes
#XmlRootElement(name = "employees")
public class FileWrapper {
private LinkedHashSet<Employee> employees;
public LinkedHashSet<Employee> getEmployees() {
return employees;
}
#XmlElement(name = "employee")
public void setEmployees(LinkedHashSet<Employee> employees) {
this.employees = employees;
}
}
Employee.java
import javax.xml.bind.annotation.XmlAttribute;
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlAttribute
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlAttribute
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlAttribute
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlAttribute
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlAttribute
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlAttribute
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlAttribute
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}
MainEntry
public class TestEntryPoint {
public static void main(String[] args) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(FileWrapper.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("XML from above link as String");
FileWrapper person = (FileWrapper) unmarshaller.unmarshal(reader);
List<Employee> emp = new ArrayList<Employee>(person.getEmployees());
System.out.println(emp.get(0).getFirstname());
}
}
So when am trying to extract any tag's value its showing null. Is there any problem with my XML's data structure or pojo classes ? I'm stuck in this from last couple of hours.
What am doing wrong ? Canyone suggest please ?
Thanks
Annotations in Employee class refer to XML attributes instead of the elements.
Here is corrected version:
public class Employee {
private String division;
private String firstname;
private String id;
private String title;
private String building;
private String room;
private String supervisor;
private String lastname;
public String getDivision() {
return division;
}
#XmlElement(name = "division")
public void setDivision(String division) {
this.division = division;
}
public String getFirstname() {
return firstname;
}
#XmlElement(name = "firstname")
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getId() {
return id;
}
#XmlAttribute
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
#XmlElement(name = "title")
public void setTitle(String title) {
this.title = title;
}
public String getBuilding() {
return building;
}
#XmlElement(name = "building")
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
#XmlElement(name = "room")
public void setRoom(String room) {
this.room = room;
}
public String getSupervisor() {
return supervisor;
}
#XmlElement(name = "supervisor")
public void setSupervisor(String supervisor) {
this.supervisor = supervisor;
}
public String getLastname() {
return lastname;
}
#XmlElement(name = "lastname")
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public String toString() {
return "ClassPojo [division = " + division + ", firstname = " + firstname + ", id = " + id + ", title = "
+ title + ", building = " + building + ", room = " + room + ", supervisor = " + supervisor
+ ", lastname = " + lastname + "]";
}
}

how to obtain a model of a parent model with information obtained from a service

I learn to use Web services, I have a service which I can obtain in a model without problem, but this model has subClasses as RESULT that in turn contains PRODUCTS and FEE which in JSON language are objects, my problem is that I need to obtain the information stored in the model PRODUCT that is inside the RESULT class and I have no idea how to do it, it is complicated ah at this point, I leave the service hoping they can help me, I must clarify that my Java model has been created correctly.
{
"links": {
"previous": null,
"next": null
},
"results": [
{
"created_at": "2018-08-29T15:52:29.175042Z",
"total_amount": "700.00",
"reference_number": "CD1006",
"is_fee": true,
"id": 47,
"products": [
{
"price": "150.00",
"description": "Description",
"discount": "150.00",
"pin_code": "IS73DR",
"is_billable": false,
"contract": null,
"product_type": 1,
"sale": 47,
"attribute_product": {
"id": 100,
"plan_name": "Express",
"is_chosen": false,
"is_active": true,
"validity_months": 1,
"query_quantity": 1,
"available_queries": 1,
"expiration_date": null
},
"product_type_name": "Planes de Consulta"
},
{
"price": "700.00",
"description": "Description",
"discount": "0.00",
"pin_code": "VIKDBE",
"is_billable": true,
"contract": null,
"product_type": 1,
"sale": 47,
"attribute_product": {
"id": 101,
"plan_name": "Express Duo",
"is_chosen": false,
"is_active": false,
"validity_months": 3,
"query_quantity": 2,
"available_queries": 2,
"expiration_date": null
},
"product_type_name": "Planes de Consulta"
}
],
"fee": {
"fee_amount": "150.00",
"fee_order_number": 1,
"fee_quantity": 1,
"pay_before": "2018-09-01",
"status": 1,
"id": 43
}
}
],
"count": 1,
"total_pages": 1
}
this is the model :
public class ContactProducts implements Serializable {
#SerializedName("count")
private Integer count;
#SerializedName("results")
private List<Result> results = null;
#SerializedName("total_pages")
private Integer totalPages;
#SerializedName("links")
private Links links;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
public Integer getTotalPages() {
return totalPages;
}
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
#Override
public String toString() {
return "ContactProducts{" +
"count=" + count +
", results=" + results +
", totalPages=" + totalPages +
", links=" + links +
'}';
}
public static class Result {
#SerializedName("created_at")
private String createdAt;
#SerializedName("total_amount")
private String totalAmount;
#SerializedName("reference_number")
private String referenceNumber;
#SerializedName("is_fee")
private Boolean isFee;
#SerializedName("id")
private Integer id;
#SerializedName("products")
private List<Product> products = null;
#SerializedName("fee")
private Fee fee;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
public String getReferenceNumber() {
return referenceNumber;
}
public void setReferenceNumber(String referenceNumber) {
this.referenceNumber = referenceNumber;
}
public Boolean getFee() {
return isFee;
}
public void setFee(Fee fee) {
this.fee = fee;
}
public void setFee(Boolean fee) {
isFee = fee;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
#Override
public String toString() {
return "Result{" +
"createdAt='" + createdAt + '\'' +
", totalAmount='" + totalAmount + '\'' +
", referenceNumber='" + referenceNumber + '\'' +
", isFee=" + isFee +
", id=" + id +
", products=" + products +
", fee=" + fee +
'}';
}
public static class Product {
#SerializedName("price")
private String price;
#SerializedName("description")
private String description;
#SerializedName("discount")
private String discount;
#SerializedName("pin_code")
private String pinCode;
#SerializedName("is_billable")
private Boolean isBillable;
#SerializedName("contract")
private Integer contract;
#SerializedName("product_type")
private Integer productType;
#SerializedName("sale")
private Integer sale;
#SerializedName("attribute_product")
private AttributeProduct attributeProduct;
#SerializedName("product_type_name")
private String productTypeName;
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getPinCode() {
return pinCode;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public Boolean getBillable() {
return isBillable;
}
public void setBillable(Boolean billable) {
isBillable = billable;
}
public Integer getContract() {
return contract;
}
public void setContract(Integer contract) {
this.contract = contract;
}
public Integer getProductType() {
return productType;
}
public void setProductType(Integer productType) {
this.productType = productType;
}
public Integer getSale() {
return sale;
}
public void setSale(Integer sale) {
this.sale = sale;
}
public AttributeProduct getAttributeProduct() {
return attributeProduct;
}
public void setAttributeProduct(AttributeProduct attributeProduct) {
this.attributeProduct = attributeProduct;
}
public String getProductTypeName() {
return productTypeName;
}
public void setProductTypeName(String productTypeName) {
this.productTypeName = productTypeName;
}
#Override
public String toString() {
return "Product{" +
"price='" + price + '\'' +
", description='" + description + '\'' +
", discount='" + discount + '\'' +
", pinCode='" + pinCode + '\'' +
", isBillable=" + isBillable +
", contract=" + contract +
", productType=" + productType +
", sale=" + sale +
", attributeProduct=" + attributeProduct +
", productTypeName='" + productTypeName + '\'' +
'}';
}
public static class AttributeProduct {
#SerializedName("id")
private Integer id;
#SerializedName("plan_name")
private String planName;
#SerializedName("is_chosen")
private Boolean isChosen;
#SerializedName("is_active")
private Boolean isActive;
#SerializedName("validity_months")
private Integer validityMonths;
#SerializedName("query_quantity")
private Integer queryQuantity;
#SerializedName("available_queries")
private Integer availableQueries;
#SerializedName("expiration_date")
private Integer expirationDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPlanName() {
return planName;
}
public void setPlanName(String planName) {
this.planName = planName;
}
public Boolean getChosen() {
return isChosen;
}
public void setChosen(Boolean chosen) {
isChosen = chosen;
}
public Boolean getActive() {
return isActive;
}
public void setActive(Boolean active) {
isActive = active;
}
public Integer getValidityMonths() {
return validityMonths;
}
public void setValidityMonths(Integer validityMonths) {
this.validityMonths = validityMonths;
}
public Integer getQueryQuantity() {
return queryQuantity;
}
public void setQueryQuantity(Integer queryQuantity) {
this.queryQuantity = queryQuantity;
}
public Integer getAvailableQueries() {
return availableQueries;
}
public void setAvailableQueries(Integer availableQueries) {
this.availableQueries = availableQueries;
}
public Integer getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Integer expirationDate) {
this.expirationDate = expirationDate;
}
#Override
public String toString() {
return "AttributeProduct{" +
"id=" + id +
", planName='" + planName + '\'' +
", isChosen=" + isChosen +
", isActive=" + isActive +
", validityMonths=" + validityMonths +
", queryQuantity=" + queryQuantity +
", availableQueries=" + availableQueries +
", expirationDate=" + expirationDate +
'}';
}
}
}
public static class Fee {
#SerializedName("fee_amount")
private String feeAmount;
#SerializedName("fee_order_number")
private Integer feeOrderNumber;
#SerializedName("fee_quantity")
private Integer feeQuantity;
#SerializedName("pay_before")
private String payBefore;
#SerializedName("status")
private Integer status;
#SerializedName("id")
private Integer id;
public String getFeeAmount() {
return feeAmount;
}
public void setFeeAmount(String feeAmount) {
this.feeAmount = feeAmount;
}
public Integer getFeeOrderNumber() {
return feeOrderNumber;
}
public void setFeeOrderNumber(Integer feeOrderNumber) {
this.feeOrderNumber = feeOrderNumber;
}
public Integer getFeeQuantity() {
return feeQuantity;
}
public void setFeeQuantity(Integer feeQuantity) {
this.feeQuantity = feeQuantity;
}
public String getPayBefore() {
return payBefore;
}
public void setPayBefore(String payBefore) {
this.payBefore = payBefore;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Override
public String toString() {
return "Fee{" +
"feeAmount='" + feeAmount + '\'' +
", feeOrderNumber=" + feeOrderNumber +
", feeQuantity=" + feeQuantity +
", payBefore='" + payBefore + '\'' +
", status=" + status +
", id=" + id +
'}';
}
}
}
}

Hibernate: LazyInitializationException: failed to lazily initialize a collection of role

Using Hibernate 3.6.0
I'm having a real hard time understanding hibernate. I keep running into this issue with lazy initialization exception.
I have an Event entity with a one-to-many relationship with RSVP. When a run a test get back a list of events it works. But when I'm making the call in my controller in order to return it as json, I run into this lazy init error.
This is my event class
#Entity
#Table(name = "EVENT")
public class Event implements Serializable {
#SequenceGenerator(name="event", sequenceName="EVENT_PK_SEQ")
#GeneratedValue(generator="event",strategy=GenerationType.SEQUENCE)
#Id
#Column(name = "EVENT_ID")
private int id;
#Column(name = "DATE_TIME")
private Date date;
#Column(name = "EVENT_NAME")
private String name;
#Column(name = "EVENT_PARTICIPANT_LIMIT")
private int limit;
#Column(name = "EVENT_VISIBILITY")
private boolean visibilty;
#Column(name = "EVENT_LOCATION")
private String location;
#Column(name = "EVENT_DESCRIPTION")
private String description;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private User author;
private Date create_date;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventType eventType;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
private EventClass eventClass;
#OneToMany(cascade = CascadeType.ALL)
private Set<RSVP> rsvps = new HashSet<RSVP>();
#ManyToMany(mappedBy="event")
private Set<Group> groups = new HashSet<Group>();
public Event(int id, Date date, String name, int limit, boolean visibilty, String location, String description,
User author, Date create_date, EventType eventType, EventClass eventClass) {
super();
this.id = id;
this.date = date;
this.name = name;
this.limit = limit;
this.visibilty = visibilty;
this.location = location;
this.description = description;
this.author = author;
this.create_date = create_date;
this.eventType = eventType;
this.eventClass = eventClass;
}
public Event(){
super();
}
#Override
public String toString() {
return "Event [id=" + id + ", date=" + date + ", name=" + name + ", limit=" + limit + ", visibilty=" + visibilty
+ ", location=" + location + ", description=" + description + ", author=" + author + ", create_date="
+ create_date + ", eventType=" + eventType + ", eventClass=" + eventClass + ", rsvps=" + rsvps
+ ", groups=" + groups + "]";
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public boolean isVisibilty() {
return visibilty;
}
public void setVisibilty(boolean visibilty) {
this.visibilty = visibilty;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public EventType getEventType() {
return eventType;
}
public void setEventType(EventType eventType) {
this.eventType = eventType;
}
public EventClass getEventClass() {
return eventClass;
}
public void setEventClass(EventClass eventClass) {
this.eventClass = eventClass;
}
public Set<RSVP> getRsvps() {
return rsvps;
}
public void setRsvps(Set<RSVP> rsvps) {
this.rsvps = rsvps;
}
public Set<Group> getGroups() {
return groups;
}
public void setGroups(Set<Group> groups) {
this.groups = groups;
}
}
My RSVP
#Entity
#Table(name="RSVP")
public class RSVP {
#Id
#Column(name="RSVP_ID")
#SequenceGenerator(name="rsvp", sequenceName="RSVP_PK_SEQ")
#GeneratedValue(generator="rsvp",strategy=GenerationType.SEQUENCE)
private int rsvpId;
#OneToOne(cascade=CascadeType.REMOVE, fetch= FetchType.EAGER)
#JoinColumn(name="STATUS_ID")
private RSVPStatus status;
#ManyToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="EVENT_ID")
private Event event;
public RSVP(int rsvpId, RSVPStatus status, User user, Event event) {
super();
this.rsvpId = rsvpId;
this.status = status;
this.user = user;
this.event = event;
}
public RSVP() {
}
#Override
public String toString() {
return "RSVP [rsvpId=" + rsvpId + ", status=" + status + ", user=" + user + ", event=" + event + "]";
}
public int getRsvpId() {
return rsvpId;
}
public void setRsvpId(int rsvpId) {
this.rsvpId = rsvpId;
}
public RSVPStatus getStatus() {
return status;
}
public void setStatus(RSVPStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
}
MY controller
public class MyController {
private static SessionFactory sf = HibernateUtils.getSessionFactory();
private DataFacade df = new DataFacade(sf);
#RequestMapping(value="home", method=RequestMethod.GET,
consumes= MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<List<Event>> getUserCal(){
DataFacade df = new DataFacade(sf);
List<Event> events= df.getAllEventsByAuthor(1);
for(Event e:events){
System.out.println(e);
}
return new ResponseEntity<List<Event>>(events,HttpStatus.OK);
}
}
Your RSVP collection is fetched lazily. (If you don't specify a fetch type, the default is lazy). You need to change it to eager if you are planning to access it after the Hibernate session is closed:
#OneToMany(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private Set<RSVP> rsvps = new HashSet<RSVP>();

Categories