I am trying to develop Web services using Spring boot, Hibernate with database MySql. I am using stored procedure to retrieve the list. The response that i get is not in the form of valid json format.
[
2,
"7598149597",
"2019-09-02T05:10:43.000+0000",
"Digital Marketing",
"2015002",
"Rohit",
"Ramakrishnan",
"C",
"2019-09-02T05:10:43.000+0000"
]
This is how i get the response it should actually be like
{
"id": 2,
"first_name": "Rohit",
"middle_name": "C",
"last_name": "Ramakrishnan",
"employee_id": "2015002",
"designation": "Digital Marketing",
"contact_number": "7598149597",
"create_date": "2019-09-02T05:10:43.000+0000",
"update_date": "2019-09-02T05:10:43.000+0000"
}
The Entity class has toString Method that returns
#Override
public String toString() {
// TODO Auto-generated method stub
return "Employee [id=" + id + ", first_name=" + first_name + ", middle_name=" + middle_name + ", last_name=" + last_name + ", employee_id="+ employee_id + ", designation=" + designation + ", contact_number=" + contact_number + ", create_date=" + create_date + ", update_date=" + update_date +"]";
}
The repository class looks like this
#Repository
public class EmployeeDetailsDao {
#Autowired
EntityManager em;
/**
* Retrieve List
* #return
*/
#SuppressWarnings("unchecked")
public Iterable<EmployeeDetailsSP> getEmployeeList(){
return em.createStoredProcedureQuery("find_all_employees").getResultList();
}
The controller class looks like this
#RestController
#RequestMapping(value = "/sp/emloyee")
public class EmployeeDetailControllerSP {
#Autowired
EmployeeDetailsDao employeeDetailsDao;
private static final Logger log = LoggerFactory.getLogger(EmployeeDetailControllerSP.class);
/**
* Retrieve List
*
* #return
*/
#GetMapping("retrieve_list")
public Iterable<EmployeeDetailsSP> retrieveList() {
log.debug("retrieve_list");
return employeeDetailsDao.getEmployeeList();
}
EmployeeDetailsSP
#Entity
#Table(name = "employee_details")
#NamedStoredProcedureQueries(value = {
#NamedStoredProcedureQuery(name = "FindEmployeeList", procedureName = "find_all_employees"),
#NamedStoredProcedureQuery(name = "FindEmployeeDetails", procedureName = "find_employee_by_id", parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, name = "emp_id", type = Integer.class) }),
#NamedStoredProcedureQuery(name = "CheckDuplicateEmployee", procedureName = "check_duplicate", parameters = {
#StoredProcedureParameter(mode = ParameterMode.IN, name = "emp_id", type = Integer.class),
#StoredProcedureParameter(mode = ParameterMode.OUT, name = "emp_count", type = Integer.class) }) })
public class EmployeeDetailsSP {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotBlank
private String first_name;
private String middle_name;
#NotBlank
private String last_name;
#NotBlank
private String employee_id;
#NotBlank
private String designation;
#NotBlank
private String contact_number;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date create_date;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date update_date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getMiddle_name() {
return middle_name;
}
public void setMiddle_name(String middle_name) {
this.middle_name = middle_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmployee_id() {
return employee_id;
}
public void setEmployee_id(String employee_id) {
this.employee_id = employee_id;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContact_number() {
return contact_number;
}
public void setContact_number(String contact_number) {
this.contact_number = contact_number;
}
public Date getCreate_date() {
return create_date;
}
public void setCreate_date(Date create_date) {
this.create_date = create_date;
}
public Date getUpdate_date() {
return update_date;
}
public void setUpdate_date(Date update_date) {
this.update_date = update_date;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Employee [id=" + id + ", first_name=" + first_name + ", middle_name=" + middle_name + ", last_name=" + last_name + ", employee_id="+ employee_id + ", designation=" + designation + ", contact_number=" + contact_number + ", create_date=" + create_date + ", update_date=" + update_date +"]";
}
Related
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);
Hello i am trying to add data from a json file to my local Postgres database but no luck. i keep getting this error, i created the employee.json but still no luck with getting it running, can anyone assit with this. i followed the tutorial found on https://www.danvega.dev/blog/2017/07/05/read-json-data-spring-boot-write-database/*
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "employee" violates foreign key constraint "department_id"
Detail: Key (department_id)=(1) is not present in table "department".
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2532) ~[postgresql-42.2.14.jar:42.2.14]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2267) ~[postgresql-42.2.14.jar:42.2.14]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:312) ~[postgresql-42.2.14.jar:42.2.14]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448) ~[postgresql-42.2.14.jar:42.2.14]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369) ~[postgresql-42.2.14.jar:42.2.14]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:153) ~[postgresql-42.2.14.jar:42.2.14]
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:119) ~[postgresql-42.2.14.jar:42.2.14]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.18.Final.jar:5.4.18.Final]
... 78 common frames omitted
HERES MY CODE
EMPLOYEE.JAVA
Table
#Entity
public class Employee implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "employee_id")
#NotNull
private Long id;
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="department_id")
#NotNull
private Long department;
#Column(name="team_id")
#NotNull
private Long team;
#Column(name="policy_id")
#NotNull
private Long policy;
#Column(name = "first_name")
#NotNull
private String firstName;
#Column(name = "last_name")
#NotNull
private String lastName;
#Column(name = "GMID")
#NotNull
private String GMID;
#Column(name = "GMIN", nullable = false)
#NotNull
private Long GMIN;
#Column(name = "policy_overrides")
#NotNull
private String policyOverrides;
#Column(name = "holiday_details")
#NotNull
private String holidayDetails;
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#JsonFormat(pattern="yyyy-MM-dd")
#Column(name = "date_started")
#NotNull
private LocalDate dateStarted;
#Column(name = "email_address")
#NotNull
private String emailAddress;
public Employee() {
}
public Employee(Long department, Long team, Long policy, String firstName, String lastName, String GMID, Long GMIN, String policyOverrides, String holidayDetails, LocalDate dateStarted, String emailAddress) {
this.department = department;
this.team = team;
this.policy = policy;
this.firstName = firstName;
this.lastName = lastName;
this.GMID = GMID;
this.GMIN = GMIN;
this.policyOverrides = policyOverrides;
this.holidayDetails = holidayDetails;
this.dateStarted = dateStarted;
this.emailAddress = emailAddress;
}
// For updating existing column in database
public Employee(Long id, Long department, Long team, Long policy, String firstName, String lastName, String GMID, Long GMIN, String policyOverrides, String holidayDetails, LocalDate dateStarted, String emailAddress){
this.id = id;
this.department = department;
this.team = team;
this.policy = policy;
this.firstName = firstName;
this.lastName = lastName;
this.GMID = GMID;
this.GMIN = GMIN;
this.policyOverrides = policyOverrides;
this.holidayDetails = holidayDetails;
this.dateStarted = dateStarted;
this.emailAddress = emailAddress;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getDepartment() {
return department;
}
public void setDepartment(Long department) {
this.department = department;
}
public Long getTeam() {
return team;
}
public void setTeam(Long team) {
this.team = team;
}
public Long getPolicy() {
return policy;
}
public void setPolicy(Long policy) {
this.policy = policy;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGMID() {
return GMID;
}
public void setGMID(String GMID) {
this.GMID = GMID;
}
public Long getGMIN() {
return GMIN;
}
public void setGMIN(Long GMIN) {
this.GMIN = GMIN;
}
public String getHolidayDetails() {
return holidayDetails;
}
public void setHolidayDetails(String holidayDetails) {
this.holidayDetails = holidayDetails;
}
public LocalDate getDateStarted() {
return dateStarted;
}
public void setDateStarted(LocalDate date_started) {
this.dateStarted = date_started;
}
public String getPolicyOverrides() {
return policyOverrides;
}
public void setPolicyOverrides(String policyOverrides) {
this.policyOverrides = policyOverrides;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#Override
public String toString() {
return "{" +
"\"id\":" + id +
", \"department\":" + department +
", \"team\":" + team +
", \"policy\":" + policy +
", \"firstName\":\"" + firstName + "\"" +
", \"lastName\":\"" + lastName + "\"" +
", \"email\":\"" + emailAddress + "\"" +
", \"GMID\":\"" + GMID + "\"" +
", \"GMIN\":" + GMIN + "" +
", \"policyOverrides\":\"" + policyOverrides + "\"" +
", \"holidayDetails\":\"" + holidayDetails + "\"" +
", \"dateStarted\":\"" + dateStarted + "\"" +
'}';
}
}
DEPARTMENT.JAVA
package com.gm.absencetracker.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
#Table
#Entity
public class Department implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "department_id")
#NotNull
#JsonProperty("id")
private Long id;
#Column(name = "department_name")
#NotNull
#JsonProperty("departmentName")
private String departmentName;
#Column(name = "first_manager")
#NotNull
#JsonProperty("firstManager")
private String firstManager;
#Column(name = "alternative_manager")
#NotNull
#JsonProperty("alternativeManager")
private String alternativeManager;
public Department() {
}
public Department(String departmentName, String firstManager, String alternativeManager ) {
this.departmentName = departmentName;
this.firstManager = firstManager;
this.alternativeManager = alternativeManager;
}
// For updating existing column in database
public Department(Long id, String departmentName, String firstManager, String alternativeManager ) {
this.id = id;
this.departmentName = departmentName;
this.firstManager = firstManager;
this.alternativeManager = alternativeManager;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getFirstManager() {
return firstManager;
}
public void setFirstManager(String firstManager) {
this.firstManager = firstManager;
}
public String getAlternativeManager() {
return alternativeManager;
}
public void setAlternativeManager(String alternativeManager) {
this.alternativeManager = alternativeManager;
}
#Override
public String toString() {
return "{" +
"\"id\":" + id +
", \"departmentName\":\"" + departmentName + "\"" +
", \"firstManager\":\"" + firstManager + "\"" +
", \"alternativeManager\":\"" + alternativeManager + "\"" +
'}';
}
}
employee.json
[
{
"id": 1,
"department": 1,
"team": 1,
"policy": 1,
"firstName": "Laxmivaraprasad",
"lastName": "Ale",
"gmid": "HZDT3V",
"gmin": "475609900",
"policyOverrides": "",
"holidayDetails":"",
"dateStarted": "2020-07-13",
"emailAddress": "laxmivaraprasad.1.ale#gm.com"
},
{
"id": 1,
"department":1,
"team": 1,
"policy": 1,
"firstName": "Michael",
"lastName": "Aroyehun",
"gmid": "KZV0FP",
"gmin": "246873348",
"policyOverrides": "",
"holidayDetails":"",
"dateStarted": "2020-07-13",
"emailAddress": "michael.o.aroyehun#gm.com"
}
]
MainApplication.java
package com.gm.absencetracker;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.gm.absencetracker.models.Employee;
import com.gm.absencetracker.repository.EmployeeRepository;
import com.gm.absencetracker.service.EmployeeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
#SpringBootApplication
public class AbsenceTrackerServiceApplication {
private final static Logger LOGGER = LoggerFactory.getLogger(AbsenceTrackerServiceApplication.class);
#Autowired
private FakeDataFactory fakeDataFactory;
#Autowired
private EmployeeService employeeService;
#Autowired
private EmployeeRepository employeeRepository;
#Autowired
private ObjectMapper objectMapper;
public static void main(String[] args) {
LOGGER.info("Application is running");
SpringApplication.run(AbsenceTrackerServiceApplication.class, args);
}
#PostConstruct
public void setUp() {
objectMapper.registerModule(new JavaTimeModule());
}
#EventListener(ApplicationReadyEvent.class)
public void addData() {
fakeDataFactory.addPolicys();
fakeDataFactory.addDepartments();
fakeDataFactory.addTeams();
//fakeDataFactory.addEmployees();
fakeDataFactory.addHolidays();
}
#Bean
CommandLineRunner runner(EmployeeService employeeService) {
return args -> {
// read json and write to db
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Employee>> typeReference = new TypeReference<>() {
};
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/employee.json");
try {
List<Employee> users = mapper.readValue(inputStream, typeReference);
employeeService.saveAll(users);
System.out.println("Users Saved!");
} catch (IOException e) {
System.out.println("Unable to save users: " + e.getMessage());
}
};
}
}
TL;DR: addData() runs before the CommandLineRunner. Change event to ApplicationStartedEvent.
If you look at the source code for SpringApplication, you will see the sequence of events.
The sequence of events are:
Event: ApplicationStartingEvent
Logs "Starting ...Application on ..."
Event: ContextRefreshedEvent
Logs "Started ...Application in ... seconds ..."
Event: ApplicationStartedEvent
Executing CommandLineRunner beans
Event: ApplicationReadyEvent
Returns, likely to main()
This means that your addData() runs after the CommandLineRunner.
Solution 1: Change to #EventListener(ApplicationStartedEvent.class) to make it run before the CommandLineRunner.
Solution 2: Move the code that's in the CommandLineRunner to the main() method.
Here is the abbreviated source code for SpringApplication.run():
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// ...
listeners.starting(); // #1
try {
// ...
Banner printedBanner = printBanner(environment); // #2
context = createApplicationContext(); // #3
// ...
stopWatch.stop();
if (this.logStartupInfo) { // #4
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context); // #5
callRunners(context, applicationArguments); // #6
}
catch (Throwable ex) {
// ...
}
try {
listeners.running(context); // #7
}
catch (Throwable ex) {
// ...
}
return context; // #8
}
I am new to JPA and I am trying to persist an Entity that will run through 3 stages New, Processing and Completed. I want the below timestamps to be updated accordingly
#Entity
#Table(name = "feedertable")
#JsonIgnoreProperties(value = { "processStatus" })
public class FeederTable {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private String id;
private String orderID;
private String status;
#Column(name="CREATEDDATETIME",nullable = false)
private Timestamp createdDateTime;
#Column(name="PROCESSSTATUS",nullable = false)
private String processStatus;
#Column(name="HOSTNAME",nullable = true)
private String hostName;
//#Temporal(TemporalType.TIMESTAMP)
#Column(name="PROCESSINGDATETIME",nullable = false)
private Timestamp processingDateTime;
#Column(name="COMPLETEDDATETIME",nullable = false)
private Timestamp completedDateTime; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Timestamp getCreatedDateTime() {
return createdDateTime;
}
public void setCreatedDateTime(Timestamp createdDateTime) {
this.createdDateTime = createdDateTime;
}
public String getProcessStatus() {
return processStatus;
}
public void setProcessStatus(String processStatus) {
this.processStatus = processStatus;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public Timestamp getProcessingDateTime() {
return processingDateTime;
}
public void setProcessingDateTime(Timestamp processingDateTime) {
this.processingDateTime = processingDateTime;
}
public Timestamp getCompletedDateTime() {
return completedDateTime;
}
public void setCompletedDateTime(Timestamp completedDateTime) {
this.completedDateTime = completedDateTime;
}
#Override
public String toString() {
return "FeederTable{" +
"id='" + id + '\'' +
", orderID='" + orderID + '\'' +
", status='" + status + '\'' +
", createdDateTime=" + createdDateTime +
", processStatus='" + processStatus + '\'' +
", hostName='" + hostName + '\'' +
", processingDateTime=" + processingDateTime +
", completedDateTime=" + completedDateTime +
'}';
}
Persist in JPARepository:
FeederTable feederTable = new FeederTable();
feederTable.setOrderID(orderId);
feederTable.setStatus(status);
feederTable.setCreatedDateTime(new Timestamp(format.getTime())); feederTable.setProcessStatus("New");
feederTable.setHostName(hostname);
feederTable.setCompletedDateTime(null);
feederTable.setProcessingDateTime(null);
repository.save(feederTable);
However when first time the Entity is persisted, All the Timestamps are populated. I want the PROCESSINGDATETIME and COMPLETEDDATETIME as null and populate it only when it reaches corresponding status. Any idea how to acheive it?.
I did a similar thing in my project using #PrePersist and #PreUpdate annotations.
There are other lifecycle hooks that you can use. Read about them here.
MyEntity{
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Temporal(TemporalType.TIMESTAMP)
private Date updationDate;
#PrePersist
public void onCreate() {
creationDate = new Date();
}
#PreUpdate
public void onUpdate() {
updationDate = new Date();
}
}
Did I understand your question correctly? Is this what you were looking for?
I have the following query in my repository:
SELECT p FROM Project p JOIN p.users u WHERE u.login =:login
There is a Many To Many relationshio between user and project.
Everything works fine and it returns the user's projects, but I want it for each project to return the corresponding set of users. So updated it with a fetch join:
SELECT p FROM Project p JOIN FETCH p.users JOIN p.users u WHERE u.login =:login
But now i got the following exception:
nested exception is java.lang.IllegalArgumentException: Count query validation failed for method public abstract org.springframework.data.domain.Page com.example.app.repository.ProjectRepository.findAllByUserLogin(java.lang.String,org.springframework.data.domain.Pageable)! org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
Cannot find a workaround for it to execute the where clause and fetch the collection at the same time.
Project Entity:
#Entity
#Table(name = "project")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "project")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(min = 10, max = 50)
#Column(name = "name", length = 50, nullable = false)
private String name;
#Size(max = 150)
#Column(name = "description", length = 150)
private String description;
#Column(name = "project_type")
private Integer projectType;
#Column(name = "is_active")
private Boolean isActive;
#Column(name = "date_created")
private ZonedDateTime dateCreated;
#Column(name = "date_updated")
private ZonedDateTime dateUpdated;
#ManyToMany
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#JoinTable(name = "project_user",
joinColumns = #JoinColumn(name="projects_id", referencedColumnName="ID"),
inverseJoinColumns = #JoinColumn(name="users_id", referencedColumnName="ID"))
private Set<User> users = new HashSet<>();
#OneToMany(mappedBy = "project")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Milestone> milestones = new HashSet<>();
#OneToMany(mappedBy = "project")
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<TaskList> taskLists = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getProjectType() {
return projectType;
}
public void setProjectType(Integer projectType) {
this.projectType = projectType;
}
public Boolean isIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public ZonedDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(ZonedDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public ZonedDateTime getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(ZonedDateTime dateUpdated) {
this.dateUpdated = dateUpdated;
}
public Set<User> getOwners() {
return users;
}
public void setOwners(Set<User> users) {
this.users = users;
}
public Set<Milestone> getMilestones() {
return milestones;
}
public void setMilestones(Set<Milestone> milestones) {
this.milestones = milestones;
}
public Set<TaskList> getTaskLists() {
return taskLists;
}
public void setTaskLists(Set<TaskList> taskLists) {
this.taskLists = taskLists;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Project project = (Project) o;
if(project.id == null || id == null) {
return false;
}
return Objects.equals(id, project.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Project{" +
"id=" + id +
", name='" + name + "'" +
", description='" + description + "'" +
", projectType='" + projectType + "'" +
", isActive='" + isActive + "'" +
", dateCreated='" + dateCreated + "'" +
", dateUpdated='" + dateUpdated + "'" +
'}';
}
}
User Entity:
#Entity
#Table(name = "user")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "user")
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Pattern(regexp = Constants.LOGIN_REGEX)
#Size(min = 1, max = 100)
#Column(length = 100, unique = true, nullable = false)
private String login;
#JsonIgnore
#NotNull
#Size(min = 60, max = 60)
#Column(name = "password_hash",length = 60)
private String password;
#Size(max = 50)
#Column(name = "first_name", length = 50)
private String firstName;
#Size(max = 50)
#Column(name = "last_name", length = 50)
private String lastName;
#Email
#Size(max = 100)
#Column(length = 100, unique = true)
private String email;
#NotNull
#Column(nullable = false)
private boolean activated = false;
#Size(min = 2, max = 5)
#Column(name = "lang_key", length = 5)
private String langKey;
#Size(max = 20)
#Column(name = "activation_key", length = 20)
#JsonIgnore
private String activationKey;
#Size(max = 20)
#Column(name = "reset_key", length = 20)
private String resetKey;
#Column(name = "reset_date", nullable = true)
private ZonedDateTime resetDate = null;
#Column(name = "avatar", nullable = true)
private String avatar;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login.toLowerCase(Locale.ENGLISH);
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public ZonedDateTime getResetDate() {
return resetDate;
}
public void setResetDate(ZonedDateTime resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
if (!login.equals(user.login)) {
return false;
}
return true;
}
#Override
public int hashCode() {
return login.hashCode();
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", avatar='" + avatar + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
Try to remove second join:
SELECT p FROM Project p JOIN FECTH p.users u WHERE u.login =:login
And if you want to get Projects which contains specified user by login then you can try this:
SELECT p FROM Project p JOIN FECTH p.users u WHERE :login in elements(u.login)
I am getting error when we try to map ResultSet of stored procedure.
could not deserialize
Result setmapping class:
#NamedNativeQueries({ #NamedNativeQuery( name = "callCurriculumSearchProc", query = "EXEC curriculumSearchProcedure :academy_id,:curriculum_id,:curriulum_abbr,:demand_forecasting," + ":event_custodian_id,:pre_post_flag,:reviewed_date,:is_active,:id", resultSetMapping = "curriculumSearchResult" ) }) #SqlResultSetMapping(name = "curriculumSearchResult", classes = { #ConstructorResult(targetClass = CurriculumSearchResult.class, columns = { #ColumnResult(name = "id" ,type = Long.class), #ColumnResult(name = "curriculum_name"), #ColumnResult(name = "cirriculum_abbr"), #ColumnResult(name = "academy_name"), #ColumnResult(name = "academy_short_Name"), #ColumnResult(name = "reviewed_date", type = DateTime.class), #ColumnResult(name = "custodian")}) })
#MappedSuperclass public class CurriculumSearchResult implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "ID")
private Long id;
#Column(name = "curriculum_name")
private String curriculum_name;
#Column(name = "curriculum_abbr")
private String curriculum_abbr;
#Column(name = "academy_name")
private String academy_name;
#Column(name = "academy_short_Name")
private String academy_short_name;
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#JsonSerialize(using = CustomDateTimeSerializer.class)
#JsonDeserialize(using = CustomDateTimeDeserializer.class)
#Column(name = "reviewed_date")
private DateTime reviewed_date;
#Column(name = "custodian")
private String eventCustodian;
public CurriculumSearchResult (){
}
public CurriculumSearchResult(Long id, String curriculum_name, String curriculum_abbr, String academy_name, String academy_short_name, DateTime reviewed_date, String eventCustodian) { super(); this.id = id; this.curriculum_name = curriculum_name; this.curriculum_abbr = curriculum_abbr; this.academy_name = academy_name; this.academy_short_name = academy_short_name; this.reviewed_date = reviewed_date; this.eventCustodian = eventCustodian; }
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCurriculum_name() {
return curriculum_name;
}
public void setCurriculum_name(String curriculum_name) {
this.curriculum_name = curriculum_name;
}
public String getCurriculum_abbr() {
return curriculum_abbr;
}
public void setCurriculum_abbr(String curriculum_abbr) {
this.curriculum_abbr = curriculum_abbr;
}
public String getAcademy_name() {
return academy_name;
}
public void setAcademy_name(String academy_name) {
this.academy_name = academy_name;
}
public String getAcademy_short_name() {
return academy_short_name;
}
public void setAcademy_short_name(String academy_short_name) {
this.academy_short_name = academy_short_name;
}
public DateTime getReviewed_date() {
return reviewed_date;
}
public void setReviewed_date(DateTime reviewed_date) {
this.reviewed_date = reviewed_date;
}
public String getEventCustodian() {
return eventCustodian;
}
public void setEventCustodian(String eventCustodian) {
this.eventCustodian = eventCustodian;
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "CurriculumSearchResult [id=" + id + ", curriculum_name="
+ curriculum_name + ", curriculum_abbr=" + curriculum_abbr
+ ", academy_name=" + academy_name + ", academy_short_name="
+ academy_short_name + ", reviewed_date=" + reviewed_date
+ ", eventCustodian=" + eventCustodian + "]";
}
}
I get this error when there is value in reviewed_date column, but it works well when value is null.