could not resolve property Query Exception - java

I get following exception when I try to display data from EmergencyContact. SurveyData and EmergencyData are related by OneToMany. I'm able to persist the data but not able to retrieve it back.
I want to give a SurveyID as input and get back emergency contacts of that survey. I verified all my setter and getter methods and they look okay. I'm unable to trace where I made mistake. Any help is appreciated.
16:53:42,029 ERROR [stderr] (http-localhost-127.0.0.1-8080-1) Caused by: org.hibernate.QueryException: could not resolve property: survey_id of: masonsurveyejb.businesslogic.EmergencyContact [SELECT emc FROM masonsurveyejb.businesslogic.EmergencyContact emc WHERE emc.survey_id = 11]
My query string looks like below. I receive survey_id variable value as an argument in this method.
"SELECT emc FROM EmergencyContact emc WHERE emc.survey_id = " + survey_id
Following are my EmergencyContact and SurveyData classes
package masonsurveyejb.businesslogic;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "EmergencyData")
public class EmergencyContact implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "EMERGENCY_SEQUENCE", sequenceName = "Survey_Seq", initialValue = 100, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EMERGENCY_SEQUENCE")
private Integer contactId;
#Column(name = "Name")
private String emName;
#Column(name = "Phone")
private String emPhone;
#Column(name = "Email")
private String emEmail;
#ManyToOne
#JoinColumn(name = "SurveyID")
private SurveyData surveyData;
public Integer getContactId() {
return contactId;
}
public void setContactId(Integer contactId) {
this.contactId = contactId;
}
public SurveyData getSurveyData() {
return surveyData;
}
public void setSurveyData(SurveyData surveyData) {
this.surveyData = surveyData;
}
public String getEmName() {
return emName;
}
public void setEmName(String emName) {
this.emName = emName;
}
public String getEmPhone() {
return emPhone;
}
public void setEmPhone(String emPhone) {
this.emPhone = emPhone;
}
public String getEmEmail() {
return emEmail;
}
public void setEmEmail(String emEmail) {
this.emEmail = emEmail;
}
}
///////////////////////////////////////////////////////////////////////////////
// #filename: Student.java
// #description: This file is the a simple class which is used as a model
// object for Student.
//
// Modification History
// Date Author Change Reason
// ==== ====== =============
// 2014-02-20 Santosh K Tadikonda Initial Creation
//
///////////////////////////////////////////////////////////////////////////////
package masonsurveyejb.businesslogic;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
#Entity
public class SurveyData {
#Id
#SequenceGenerator(name = "SURVEY_SEQUENCE", sequenceName = "Survey_Seq", initialValue = 100, allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SURVEY_SEQUENCE")
#Column(name = "SurveyID")
private Integer survey_id;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String zipcode;
private String telephone;
private String email;
private String surveydate;
#Column(name = "Likes")
private String chklike;
#Column(name = "Know")
private String radioknow;
private String recommend;
private String raffle;
private String comments;
#OneToMany(mappedBy = "surveyData", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<EmergencyContact> emContacts;
public List<EmergencyContact> getEmContacts() {
return emContacts;
}
public void setEmContacts(List<EmergencyContact> emContacts) {
this.emContacts = emContacts;
}
public Integer getSurvey_id() {
return survey_id;
}
public void setSurvey_id(Integer survey_id) {
this.survey_id = survey_id;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurveydate() {
return surveydate;
}
public void setSurveydate(String surveydate) {
this.surveydate = surveydate;
}
public String getChklike() {
return chklike;
}
public void setChklike(String chklike) {
this.chklike = chklike;
}
public String getRadioknow() {
return radioknow;
}
public void setRadioknow(String radioknow) {
this.radioknow = radioknow;
}
public String getRecommend() {
return recommend;
}
public void setRecommend(String recommend) {
this.recommend = recommend;
}
public String getRaffle() {
return raffle;
}
public void setRaffle(String raffle) {
this.raffle = raffle;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String toString() {
String studentString;
studentString = getSurvey_id() + ";" +getFirstname() + ";" + getLastname() + ";"
+ getAddress() + ";" + getCity() + ";" + getState() + ";"
+ getZipcode() + ";" + getTelephone() + ";" + getEmail() + ";"
+ getSurveydate() + ";" + getChklike() + ";" + getRadioknow()
+ ";" + getRecommend() + ";" + getRaffle() + ";"
+ getComments();
return studentString;
}
}
Following is the method from which I make query
#Override
public ArrayList<EmergencyContact> GetEmergencyContacts(String survey_id) {
try {
if (survey_id == null || survey_id.length() == 0) {
System.out.println("Received a null or empty survey ID.");
return null;
}
System.out.println("Getting emergency contacts for " + survey_id);
String queryStr = "SELECT emc FROM EmergencyContact emc WHERE emc.survey_id = "
+ survey_id;
Query query = entityManager.createQuery(queryStr);
List resultList = query.getResultList();
if (resultList != null && resultList.size() > 0) {
ArrayList<EmergencyContact> emList = new ArrayList<EmergencyContact>();
for (Object result : resultList) {
EmergencyContact emc = new EmergencyContact();
emc = (EmergencyContact) result;
emList.add(emc);
}
return emList;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

You receiving the exception because entity 'EmergencyContact' has no property named 'survey_id'.
Your query should be:
String queryStr = "SELECT emc FROM EmergencyContact emc WHERE emc.surveyData.survey_id = :id";
Query query = entityManager.createQuery(queryStr).setParameter("id", survey_id);
List resultList = query.getResultList();
Please consider 2 things:
Use property names in JPQL query (surveyData.survey_id)
It's better to set query parameters with special method, "setParameter"

Related

trying to read and write json data into psotgres database from Spring Boot

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
}

Data not persisting in join column using spring-data

The hibernate output is as follows.
Hibernate: insert into usernew (ACTIVE, EMAIL, FIRST_NAME, CGUID, LAST_NAME, MIDDLE_NAME, PIN) values (?, ?, ?, ?, ?, ?, ?)
Hibernate:insert into usernew (ACTIVE, EMAIL, FIRST_NAME, CGUID, LAST_NAME,MIDDLE_NAME, PIN) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into eventnew (ACTIVE, ADDRESS, DESCRIPTION, END_TS, HOST_PHONE_NUMBER,IMAGE, LATITUDE, LONGITUDE, NAME, PLACE_ID, START_TS) values (?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?)
User user = new User();
user.setActive(true);
user.setFirstName("test");
user.setLastName("test");
user.setPin("3333");
user.setEmail("n#f.com");
userRepositoryNew.save(user);
User user1 = new User();
user1.setActive(true);
user1.setFirstName("test");
user1.setLastName("test");
user1.setPin("3333");
user1.setEmail("nauman#f1.com");
userRepositoryNew.save(user1);
Event event = new Event();
event.setName("event");
event.setDescription("testing event");
event.setHostPhoneNumber("4455-33-990");
event.setLongitude("dddd");
EventUser eventUser = new EventUser();
eventUser.setUser(user);
eventUser.setEvent(event);
EventUser eventUser1 = new EventUser();
eventUser.setUser(user1);
eventUser.setEvent(event);
event.getEventUsers().add(eventUser);
event.getEventUsers().add(eventUser1);
eventRepositoryNew.save(event);
Below is the code, not sure why join table is not getting populated.
package com.hive.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import com.hive.json.marshaller.DateUTCDeserializer;
import com.hive.json.marshaller.DateUTCSerializer;
import com.hive.json.marshaller.ImageDeserializer;
import com.hive.json.marshaller.ImageSerializer;
#Entity
#Table(name = "eventnew")
public class Event implements java.io.Serializable {
private Integer id;
private String name;
private String description;
private String address;
private String latitude;
private String longitude;
#JsonSerialize(using = ImageSerializer.class)
#JsonDeserialize(using = ImageDeserializer.class)
private byte[] image;
private String placeId;
#JsonSerialize(using = DateUTCSerializer.class)
#JsonDeserialize(using = DateUTCDeserializer.class)
private Date startAt;
#JsonSerialize(using = DateUTCSerializer.class)
#JsonDeserialize(using = DateUTCDeserializer.class)
private Date endAt;
private boolean active;
private String hostPhoneNumber;
private Set<User> participants = new HashSet<User>(0);
private Set<EventUser> eventUsers = new HashSet<EventUser>(0);
public Event() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "NAME", nullable = false, length = 10)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "LATITUDE")
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
#Column(name = "LONGITUDE")
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
#Column(name = "START_TS")
public Date getStartAt() {
return startAt;
}
public void setStartAt(Date startAt) {
this.startAt = startAt;
}
#Column(name = "END_TS")
public Date getEndAt() {
return endAt;
}
public void setEndAt(Date endAt) {
this.endAt = endAt;
}
#Column(name = "IMAGE")
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Column(name = "PLACE_ID")
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
#Column(name = "ACTIVE")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "HOST_PHONE_NUMBER")
public String getHostPhoneNumber() {
return hostPhoneNumber;
}
public void setHostPhoneNumber(String hostPhoneNumber) {
this.hostPhoneNumber = hostPhoneNumber;
}
#Transient
public Set<User> getParticipants() {
return participants;
}
public void setParticipants(Set<User> participants) {
this.participants = participants;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.event")
public Set<EventUser> getEventUsers() {
return this.eventUsers;
}
public void setEventUsers(Set<EventUser> eventUsers) {
this.eventUsers = eventUsers;
}
}
package com.hive.domain;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "usernew")
public class User implements java.io.Serializable {
private String guid;
private String firstName;
private String middleName;
private String lastName;
private Integer phoneNumber;
private String email;
private String pin;
private boolean active;
private Set<EventUser> eventUsers = new HashSet<EventUser>(0);
public User() {
}
#Column(name = "CGUID")
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PHONE_NUMBER", unique = true, nullable = false)
public Integer getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Integer phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "MIDDLE_NAME")
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "PIN")
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
#Column(name = "ACTIVE")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user", cascade = CascadeType.ALL)
public Set<EventUser> getEventUsers() {
return this.eventUsers;
}
public void setEventUsers(Set<EventUser> eventUsers) {
this.eventUsers = eventUsers;
}
}
package com.hive.domain;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name = "eventusernew", catalog = "hive")
#AssociationOverrides({ #AssociationOverride(name = "pk.user", joinColumns = #JoinColumn(name = "USER_ID") ),
#AssociationOverride(name = "pk.event", joinColumns = #JoinColumn(name = "EVENT_ID") ) })
public class EventUser implements java.io.Serializable {
private EventUserId pk = new EventUserId();
// private String state;
// private String comment;
// private String displayName;
public EventUser() {
}
// #Column(name = "STATE")
// public String getState() {
// return state;
// }
//
// #Column(name = "DISPLAY_NAME")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// #Column(name = "COMMENT")
// public String getComment() {
// return comment;
// }
//
// public void setComment(String comment) {
// this.comment = comment;
// }
#EmbeddedId
public EventUserId getPk() {
return pk;
}
public void setPk(EventUserId pk) {
this.pk = pk;
}
#Transient
public User getUser() {
return getPk().getUser();
}
public void setUser(User stock) {
getPk().setUser(stock);
}
#Transient
public Event getEvent() {
return getPk().getEvent();
}
public void setEvent(Event category) {
getPk().setEvent(category);
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
EventUser that = (EventUser) o;
if (getPk() != null ? !getPk().equals(that.getPk()) : that.getPk() != null)
return false;
return true;
}
public int hashCode() {
return (getPk() != null ? getPk().hashCode() : 0);
}
}
package com.hive.domain;
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
#Embeddable
public class EventUserId implements java.io.Serializable {
private User user;
private Event event;
#ManyToOne
public User getUser() {
return user;
}
public void setUser(User stock) {
this.user = stock;
}
#ManyToOne
public Event getEvent() {
return event;
}
public void setEvent(Event category) {
this.event = category;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EventUserId that = (EventUserId) o;
if (user != null ? !user.equals(that.user) : that.user != null) return false;
if (event != null ? !event.equals(that.event) : that.event != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (user != null ? user.hashCode() : 0);
result = 31 * result + (event != null ? event.hashCode() : 0);
return result;
}
}
you need to cascade your save.
In your Event entity, change the one-to-many to something like this :
#OneToMany(mappedBy="pk.event", cascade=CascadeType.ALL)

JPA Left Join IS NULL condition not working

I have User and Employee tables on MySQL, and there is employeeId as foreign key in User table.
Now I need to get Employees who do not have User.
I write this SQL in MySQL Workbench, this works exactly how I want:
SELECT * FROM HUMANRESOURCE.EMPLOYEE E LEFT JOIN AUTHORIZE.USER U
ON U.EMPLOYEEOBJID = E.OBJID
WHERE U.EMPLOYEEOBJID is NULL;
But when I try to implement this SQL as JPA query, it returns nothing. Here is JPA Query:
Query query = em.createQuery("SELECT e FROM Employee e LEFT JOIN User u
WHERE u.employee.objid = e.objid
AND u.employee IS NULL");
And here is truely working JPA Query that I use for getting Employees who have user:
Query query = em.createQuery("SELECT e FROM Employee e INNER JOIN User u
WHERE u.employee.objid = e.objid");
What am I doing wrong here?
Update for entity classes:
Base.java
package com.kadir.entity;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
#Cacheable
#MappedSuperclass
public abstract class Base {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "OBJID")
private BigInteger objid;
#Column(name = "CREATEDBY")
private String createdby;
#Column(name = "CREATEDDATE")
private Timestamp createddate;
#Version
#Column(name = "ROWVERSION")
private Integer rowversion;
#Column(name = "UPDATEDBY")
private String updatedby;
#Column(name = "UPDATEDDATE")
private Timestamp updateddate;
#Column(name = "ARCHIVED", columnDefinition = "int default 0")
private int archived;
public BigInteger getObjid() {
return this.objid;
}
public void setObjid(BigInteger objid) {
this.objid = objid;
}
public String getCreatedby() {
return this.createdby;
}
public void setCreatedby(String createdby) {
this.createdby = createdby;
}
public Date getCreateddate() {
return this.createddate;
}
public void setCreateddate(Timestamp createddate) {
this.createddate = createddate;
}
public Integer getRowversion() {
return this.rowversion;
}
public void setRowversion(Integer rowversion) {
this.rowversion = rowversion;
}
public String getUpdatedby() {
return this.updatedby;
}
public void setUpdatedby(String updatedby) {
this.updatedby = updatedby;
}
public Timestamp getUpdateddate() {
return this.updateddate;
}
public void setUpdateddate(Timestamp updateddate) {
this.updateddate = updateddate;
}
public int getArchived() {
return archived;
}
public void setArchived(int archived) {
this.archived = archived;
}
}
Employee.java
package com.kadir.entity.humanresource;
import com.kadir.entity.corporation.Company;
import com.kadir.entity.Base;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the EMPLOYEE database table.
*
*/
#Cacheable
#Entity
#Table(name = "EMPLOYEE", schema = "HUMANRESOURCE")
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
public class Employee extends Base implements Serializable {
private static final long serialVersionUID = 1L;
#ManyToOne
#JoinColumn(name = "COMPANYOBJID")
private Company company;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "GENDER")
private int gender;
#Column(name = "EMAIL")
private String email;
#Column(name = "PHONE")
private String phone;
#Column(name = "LASTNAME")
private String lastname;
public Employee() {
}
public Company getCompany() {
return this.company;
}
public void setCompany(Company company) {
this.company = company;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public int getGender() {
return this.gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
User.java
package com.kadir.entity.authorize;
import com.kadir.entity.Employee;
import com.kadir.entity.Base;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the USER database table.
*
*/
#Cacheable
#Entity
#Table(name="USER", schema="AUTHORIZE")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User extends Base implements Serializable {
private static final long serialVersionUID = 1L;
#OneToOne
#JoinColumn(name="EMPLOYEEOBJID")
private Employee employee;
#Column(name="NAME")
private String name;
#Column(name="PASSWORD")
private String password;
public User() {
}
public Employee getEmployee() {
return this.employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
EclipseLink has support for the ON clause, so try using
"SELECT e FROM Employee e LEFT JOIN User u on u.employee = e WHERE u.employee IS NULL"
You can also use exist and a subquery:
"select e from Employee e where not exists (select 1 from User u where u.employee = e)"
In my case, I'm using Apache OpenJPA.
Query should be something like this:
SELECT e FROM Employee e LEFT JOIN e.user u WHERE u.employeeId IS NULL
I had similar error. I had conditional OneToOne relation. I fixed problem like that.
#Query("SELECT e FROM Employee e LEFT OUTER JOIN User u ON u = e.user " +
"WHERE (u IS NULL OR e.condition = :conditionValue) ")

Why I don't see the data of the oneToOne?

I am new in JPA
I created two entities Questionnaire and Patient
I want that Questionnaire will have data of Patient.
Before I created the Questionnaire with only patientId but now I want to add new structure to get all the patientData.
I added new field of patientData and added new join( I hope I did it ok ).
The problem when I call to query AllQuestionnaires I didn't get data of patientData.
Could you please advise me ?
#Entity
#NamedQueries({
#NamedQuery(name = "AllQuestionnaires", query = "select q from Questionnaire q order by q.patientId") })
public class Questionnaire implements Serializable {
private static final long serialVersionUID = 1L;
public Questionnaire() {
}
#Id
#GeneratedValue
private long id;
private long patientId;
private Timestamp created;
#OneToOne
#JoinColumn(name = "patientId" ,referencedColumnName = "id" , insertable = false, updatable = false)
private Patient patientData;
public Patient getPatient() {
return patientData;
}
public void setPatient(Patient patient) {
this.patientData = patient;
}
#OneToMany(cascade = CascadeType.ALL)
private List<QuestionnaireAnswer> answers;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getPatientId() {
return patientId;
}
public void setPatientId(long patientId) {
this.patientId = patientId;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public void setCreated(long created) {
this.created = new Timestamp(created);
}
public List<QuestionnaireAnswer> getAnswers() {
return answers;
}
public void setAnswers(List<QuestionnaireAnswer> answers) {
this.answers = answers;
}
}
class Patient
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Transient;
#Entity
#NamedQueries({
#NamedQuery(name = "AllPatients", query = "select p from Patient p"),
#NamedQuery(name = "PatientsByUserType", query = "select p from Patient p where p.userType = :userType"),
#NamedQuery(name = "PatientByEmail", query = "select p from Patient p where p.email = :email"),
#NamedQuery(name = "PatientById", query = "select p from Patient p where p.id = :id") })
public class Patient implements Serializable {
public enum UserType {
PATIENT,
CONTROL
}
private static final long serialVersionUID = 1L;
public Patient() {
}
#Id
#GeneratedValue
private long id;
private String firstName;
private String lastName;
private String email;
private String password;
private int gender;
private Timestamp birthday;
private Timestamp diagnoseDate;
private Timestamp created;
private UserType userType;
#Transient
private ArrayList<Task> lastSubmittedTasks;
public UserType getUserType() {
return userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public Timestamp getBirthday() {
return birthday;
}
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
public void setBirthday(long birthday) {
this.birthday = new Timestamp(birthday);
}
public Timestamp getDiagnoseDate() {
return diagnoseDate;
}
public void setDiagnoseDate(Timestamp diagnoseDate) {
this.diagnoseDate = diagnoseDate;
}
public void setDiagnoseDate(long diagnoseDate) {
this.diagnoseDate = new Timestamp(diagnoseDate);
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public void setCreated(long created) {
this.created = new Timestamp(created);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ArrayList<Task> getLastSubmittedTask() {
return lastSubmittedTasks;
}
public void setLastSubmittedTasks(ArrayList<Task> lastSubmittedTasks) {
this.lastSubmittedTasks = lastSubmittedTasks;
}
}
#RequestMapping(value = "/questionnaires", method = RequestMethod.POST)
#ResponseBody
public String createQuestionnaires(#RequestBody String body, HttpSession session) {
EntityManager em = emf.createEntityManager();
long patientId = (long) session.getAttribute("patientId");
try {
Questionnaire questionnaire = gson.fromJson(body, Questionnaire.class);
questionnaire.setPatientId(patientId);
questionnaire.setCreated(new Timestamp(System.currentTimeMillis()));
em.getTransaction().begin();
em.persist(questionnaire);
em.getTransaction().commit();
return "{\"status\": \"OK\", \"id\": " + questionnaire.getId() + "}";
} finally {
em.close();
}
}

PropertyNotFoundException: Target Unreachable, 'null' returned null [duplicate]

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
Hello i have new Problem with Add Form
my problem here
WARNING: /test.xhtml #24,173 value="#{userController.users.username}": Target Unreachable, 'null' returned null
javax.el.PropertyNotFoundException: /test.xhtml #24,173 value="#{userController.users.username}": Target Unreachable, 'null' returned null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:93)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1008)
at javax.faces.component.UIInput.validate(UIInput.java:934)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1189)
at javax.faces.component.UIInput.processValidators(UIInput.java:691)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIForm.processValidators(UIForm.java:243)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1180)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:619)
and my back bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ejb.controller;
import com.ejbbean.iUserBean;
import com.entity.Igroup;
import com.entity.Iuser;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
/**
*
* #author KencyWindy
*/
#ManagedBean
#ViewScoped
public class UserController implements Serializable{
#EJB
private iUserBean iUserBean;
private Iuser users ;
private Igroup groupa;
public UserController() {
}
public Igroup getGroupa() {
return groupa;
}
public void setGroupa(Igroup groupa) {
this.groupa = groupa;
}
public Iuser getUsers() {
return users;
}
public void setUsers(Iuser users) {
this.users = users;
}
public List<Iuser> getAllUser(){
return iUserBean.retrieve();
}
public void addUser(){
users = new Iuser();
users = iUserBean.createUser(users);
}
public javax.faces.model.SelectItem[] getAllOfGroups(){
SelectItem[] options = null;
List<Igroup> lgroup = iUserBean.retrieveGroup();
if(lgroup.size() > 0 && lgroup != null){
options = new SelectItem[lgroup.size()];
int i = 0 ;
for ( Igroup igroup : lgroup){
options[i++] = new SelectItem(igroup.getGId(), igroup.getGroupname());
}
}
return options;
}
public void submit(ActionEvent event) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Correct", "Correct");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Igroup Entity Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* #author KencyWindy
*/
#Entity
#Table(name = "igroup")
#NamedQueries({
#NamedQuery(name = "Igroup.findAll", query = "SELECT i FROM Igroup i"),
#NamedQuery(name = "Igroup.findByGId", query = "SELECT i FROM Igroup i WHERE i.gId = :gId"),
#NamedQuery(name = "Igroup.findByGroupname", query = "SELECT i FROM Igroup i WHERE i.Groupname = :Groupname"),
#NamedQuery(name = "Igroup.findByAdministrator", query = "SELECT i FROM Igroup i WHERE i.administrator = :administrator"),
#NamedQuery(name = "Igroup.findByReaded", query = "SELECT i FROM Igroup i WHERE i.readed = :readed"),
#NamedQuery(name = "Igroup.findByDeleted", query = "SELECT i FROM Igroup i WHERE i.deleted = :deleted"),
#NamedQuery(name = "Igroup.findByUpdated", query = "SELECT i FROM Igroup i WHERE i.updated = :updated"),
#NamedQuery(name = "Igroup.findByModed", query = "SELECT i FROM Igroup i WHERE i.moded = :moded"),
#NamedQuery(name = "Igroup.findByAdded", query = "SELECT i FROM Igroup i WHERE i.added = :added")})
public class Igroup implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "g_id")
private Integer gId;
#Basic(optional = false)
#Column(name = "g_name")
private String Groupname;
#Column(name = "administrator")
private Boolean administrator;
#Basic(optional = false)
#Column(name = "readed")
private boolean readed;
#Column(name = "deleted")
private Boolean deleted;
#Column(name = "updated")
private Boolean updated;
#Column(name = "moded")
private Boolean moded;
#Column(name = "added")
private Boolean added;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "igroup")
private List<Iuser> iuserList;
public Igroup() {
}
public Igroup(Integer gId) {
this.gId = gId;
}
public Igroup(Integer gId, String gName, boolean readed) {
this.gId = gId;
this.Groupname = gName;
this.readed = readed;
}
public Integer getGId() {
return gId;
}
public void setGId(Integer gId) {
this.gId = gId;
}
public String getGroupname() {
return Groupname;
}
public void setGroupname(String Groupname) {
this.Groupname = Groupname;
}
public Boolean getAdministrator() {
return administrator;
}
public void setAdministrator(Boolean administrator) {
this.administrator = administrator;
}
public boolean getReaded() {
return readed;
}
public void setReaded(boolean readed) {
this.readed = readed;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public Boolean getUpdated() {
return updated;
}
public void setUpdated(Boolean updated) {
this.updated = updated;
}
public Boolean getModed() {
return moded;
}
public void setModed(Boolean moded) {
this.moded = moded;
}
public Boolean getAdded() {
return added;
}
public void setAdded(Boolean added) {
this.added = added;
}
public List<Iuser> getIuserList() {
return iuserList;
}
public void setIuserList(List<Iuser> iuserList) {
this.iuserList = iuserList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (gId != null ? gId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Igroup)) {
return false;
}
Igroup other = (Igroup) object;
if ((this.gId == null && other.gId != null) || (this.gId != null && !this.gId.equals(other.gId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Igroup[gId=" + gId + "]";
}
}
Iuser Entity Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author KencyWindy
*/
#Entity
#Table(name = "iuser")
#NamedQueries({
#NamedQuery(name = "Iuser.findAll", query = "SELECT i FROM Iuser i"),
#NamedQuery(name = "Iuser.findByUid", query = "SELECT i FROM Iuser i WHERE i.uid = :uid"),
#NamedQuery(name = "Iuser.findByUsername", query = "SELECT i FROM Iuser i WHERE i.username = :username"),
#NamedQuery(name = "Iuser.findByPassword", query = "SELECT i FROM Iuser i WHERE i.password = :password"),
#NamedQuery(name = "Iuser.findByPnum", query = "SELECT i FROM Iuser i WHERE i.pnum = :pnum"),
#NamedQuery(name = "Iuser.findByZipcode", query = "SELECT i FROM Iuser i WHERE i.zipcode = :zipcode"),
#NamedQuery(name = "Iuser.findByState", query = "SELECT i FROM Iuser i WHERE i.state = :state"),
#NamedQuery(name = "Iuser.findByDob", query = "SELECT i FROM Iuser i WHERE i.dob = :dob"),
#NamedQuery(name = "Iuser.findByEmail", query = "SELECT i FROM Iuser i WHERE i.email = :email"),
#NamedQuery(name = "Iuser.findByLastlogin", query = "SELECT i FROM Iuser i WHERE i.lastlogin = :lastlogin"),
#NamedQuery(name = "Iuser.findByRegdate", query = "SELECT i FROM Iuser i WHERE i.regdate = :regdate"),
#NamedQuery(name = "Iuser.findByAddress", query = "SELECT i FROM Iuser i WHERE i.address = :address"),
#NamedQuery(name = "Iuser.findByCity", query = "SELECT i FROM Iuser i WHERE i.city = :city")})
public class Iuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "uid")
private Integer uid;
#Basic(optional = false)
#Column(name = "username")
private String username;
#Basic(optional = false)
#Column(name = "password")
private String password;
#Basic(optional = false)
#Column(name = "pnum")
private int pnum;
#Basic(optional = false)
#Column(name = "zipcode")
private int zipcode;
#Basic(optional = false)
#Column(name = "state")
private String state;
#Basic(optional = false)
#Column(name = "dob")
#Temporal(TemporalType.TIMESTAMP)
private Date dob;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Column(name = "lastlogin")
#Temporal(TemporalType.TIMESTAMP)
private Date lastlogin;
#Column(name = "regdate")
#Temporal(TemporalType.TIMESTAMP)
private Date regdate;
#Basic(optional = false)
#Column(name = "address")
private String address;
#Basic(optional = false)
#Column(name = "city")
private String city;
#JoinColumn(name = "igroup", referencedColumnName = "g_id")
#ManyToOne(optional = false)
private Igroup igroup;
public Iuser() {
}
public Iuser(Integer uid) {
this.uid = uid;
}
public Iuser(Integer uid, String username, String password, int pnum, int zipcode, String state, Date dob, String email, String address, String city) {
this.uid = uid;
this.username = username;
this.password = password;
this.pnum = pnum;
this.zipcode = zipcode;
this.state = state;
this.dob = dob;
this.email = email;
this.address = address;
this.city = city;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPnum() {
return pnum;
}
public void setPnum(int pnum) {
this.pnum = pnum;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getLastlogin() {
return lastlogin;
}
public void setLastlogin(Date lastlogin) {
this.lastlogin = lastlogin;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Igroup getIgroup() {
return igroup;
}
public void setIgroup(Igroup igroup) {
this.igroup = igroup;
}
public Integer getGrouplist(){
return this.igroup.getGId();
}
public void setGrouplist(Integer intgroup){
this.igroup = new Igroup(intgroup);
}
#Override
public int hashCode() {
int hash = 0;
hash += (uid != null ? uid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Iuser)) {
return false;
}
Iuser other = (Iuser) object;
if ((this.uid == null && other.uid != null) || (this.uid != null && !this.uid.equals(other.uid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Iuser[uid=" + uid + "]";
}
}
value="#{userController.users.username}":
Target Unreachable, 'null' returned null
Either #{userController} or #{userController.users} is null.
My cents that #{userController.users} is null. You aren't prepopulating it in your bean. The #{userController} is correctly declared and used as #ManagedBean.
You need to prepopulate it in the postconstruct of the bean:
#PostConstruct
public void init() {
users = new Iuser();
}
In UserController class, declare your variable like this.
public Iuser users = new Iuser();
Because unless you use new Iuser() the object is not created and it will returned a null value.
initialize your Iuser class in backing bean like this way
public Iuser getUsers() {
if(users == null){
users = (Iuser )super.getInstance(Iuser.Class);
}
return users;
}
this will create a new Iuser object if the object become null

Categories