I met this error of javax.faces.el.EvaluationException: java.lang.NullPointerException
Code of my controller method:
public String verify(){
String result = "failed";
int authcode = staffBean.getVerifyCodeByName(getLoginUserName()); //get verifycode from database by name
Staff temp = staffBean.find(authcode);
if ( code==authcode){
result ="success";
staff.setVerifystatus("Verified");
staffBean.edit(temp);
}
return result;
}
Code of my StaffFacadeLocal:
public interface StaffFacadeLocal {
void create(Staff staff);
void edit(Staff staff);
void remove(Staff staff);
Staff find(Object id);
List<Staff> findAll();
List<Staff> findRange(int[] range);
int count();
public List findByName(String string);
public int getVerifyCodeByName(String name);
}
Code of my StaffFacade:
public class StaffFacade /*extends AbstractFacade<Staff>*/ implements StaffFacadeLocal{
#PersistenceContext(unitName = "MajorProject-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
#Override
public void create(Staff staff) {
em.persist(staff);
}
#Override
public void edit(Staff staff) {
em.merge(staff);
}
#Override
public void remove(Staff staff) {
em.remove(em.merge(staff));
}
#Override
public Staff find(Object code) {
return em.find(Staff.class, code);
}
#Override
public List<Staff> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Staff.class));
return em.createQuery(cq).getResultList();
}
#Override
public List<Staff> findRange(int[] range) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Staff.class));
Query q = em.createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
#Override
public int count() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Staff> rt = cq.from(Staff.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
/*public StaffFacade() {
super(Staff.class);
}
*/
#Override
public List<Staff> findByName(String search1) {
Query q = em.createNamedQuery("Staff.findByName");
q.setParameter("name", search1);
return q.getResultList();
}
public int getVerifyCodeByName(String name) {
Query q = em.createNamedQuery("Staff.getVerifyCodeByName");
q.setParameter("name", name);
try{
int id = (int)q.getSingleResult();
return id;
}
catch(NoResultException e){
return -1;
}
}
}
My Staff entity:
#Entity
#Table(name = "staff")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Staff.findAll", query = "SELECT s FROM Staff s"),
#NamedQuery(name = "Staff.findByStaffId", query = "SELECT s FROM Staff s WHERE s.staffId = :staffId"),
#NamedQuery(name = "Staff.findByName", query = "SELECT s FROM Staff s WHERE s.name = :name"),
#NamedQuery(name = "Staff.findByPassword", query = "SELECT s FROM Staff s WHERE s.password = :password"),
#NamedQuery(name = "Staff.findByRoles", query = "SELECT s FROM Staff s WHERE s.roles = :roles"),
#NamedQuery(name = "Staff.findByEmail", query = "SELECT s FROM Staff s WHERE s.email = :email"),
#NamedQuery(name = "Staff.getVerifyCodeByName", query = "SELECT s.verifycode FROM Staff s WHERE s.name =:name"),
#NamedQuery(name = "Staff.findByVerifystatus", query = "SELECT s FROM Staff s WHERE s.verifystatus = :verifystatus"),
#NamedQuery(name = "Staff.findByVerifycode", query = "SELECT s FROM Staff s WHERE s.verifycode = :verifycode")})
public class Staff implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
//#NotNull
#Column(name = "STAFF_ID")
private Integer staffId;
#Size(max = 30)
#Column(name = "NAME")
private String name;
#Size(max = 64)
#Column(name = "PASSWORD")
private String password;
#Size(max = 20)
#Column(name = "ROLES")
private String roles;
#Size(max = 60)
#Column(name = "EMAIL")
private String email;
#Size(max = 20)
#Column(name = "VERIFYSTATUS")
private String verifystatus;
#Basic(optional = false)
#NotNull
#Column(name = "VERIFYCODE")
private int verifycode;
public Staff() {
}
public Staff(Integer staffId) {
this.staffId = staffId;
}
public Staff(Integer staffId, int verifycode) {
this.staffId = staffId;
this.verifycode = verifycode;
}
public Integer getStaffId() {
return staffId;
}
public void setStaffId(Integer staffId) {
this.staffId = staffId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getVerifystatus() {
return verifystatus;
}
public void setVerifystatus(String verifystatus) {
this.verifystatus = verifystatus;
}
public int getVerifycode() {
return verifycode;
}
public void setVerifycode(int verifycode) {
this.verifycode = verifycode;
}
#Override
public int hashCode() {
int hash = 0;
hash += (staffId != null ? staffId.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 Staff)) {
return false;
}
Staff other = (Staff) object;
if ((this.staffId == null && other.staffId != null) || (this.staffId != null && !this.staffId.equals(other.staffId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Staff[ staffId=" + staffId + " ]";
}
}
I am not sure which part of my controller returned a null value. Anyone can point out for me? Thanks alot!
I suspect it's this code:
Query q = em.createNamedQuery("Staff.getVerifyCodeByName");
...
int id = (int)q.getSingleResult();
Assuming the named query in fact returns a Staff entity, the cast to int would fail.
Related
I can add values to the database with tables that don't have foreign key using JSON format sent through postman, however, I am receiving an error when it comes to inserting in foreign keys.
Here is my error:
HTTP Status 500 - javax.persistence.RollbackException: java.lang.IllegalStateException:
During synchronization a new object was found through a relationship that was not marked
cascade PERSIST: com.balay.entity.HaDetails[ hadID=null ].
I am inserting:
{
"acceptedGender":"both",
"price":123123.00,
"type":"apartment",
"vacantNum":13,
"hadID":4
}
I used the post method below for inserting
Can someone pls help me
Here is my code:
#javax.ejb.Stateless
#Path("com.balay.entity.hatypes")
public class HaTypesFacadeREST extends AbstractFacade<HaTypes> {
#PersistenceContext(unitName = "BalayRSPU")
private EntityManager em;
public HaTypesFacadeREST() {
super(HaTypes.class);
}
**#POST
#Override
#Consumes({MediaType.APPLICATION_JSON})
public void create(HaTypes entity) {
em =
Persistence.createEntityManagerFactory("BalayRSPU").createEntityManager();
try{
em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
}finally{
em.close();
}
}**
#PUT
#Path("{id}")
#Consumes({MediaType.APPLICATION_JSON})
public void edit(#PathParam("id") Integer id, HaTypes entity) {
super.edit(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Integer id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({MediaType.APPLICATION_JSON})
public HaTypes find(#PathParam("id") Integer id) {
return super.find(id);
}
#GET
#Override
#Produces({MediaType.APPLICATION_JSON})
public List<HaTypes> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({MediaType.APPLICATION_JSON})
public List<HaTypes> findRange(#PathParam("from") Integer from,
#PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}
#Override
protected EntityManager getEntityManager() {
em =
Persistence.createEntityManagerFactory("BalayRSPU").createEntityManager();
return em;
}
}
#Entity
#Table(name = "ha_types")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "HaTypes.findAll", query = "SELECT h FROM HaTypes h")
, #NamedQuery(name = "HaTypes.findByHatID", query = "SELECT h FROM HaTypes h
WHERE h.hatID = :hatID")
, #NamedQuery(name = "HaTypes.findByType", query = "SELECT h FROM HaTypes h
WHERE h.type = :type")
, #NamedQuery(name = "HaTypes.findByAcceptedGender", query = "SELECT h FROM
HaTypes h WHERE h.acceptedGender = :acceptedGender")
, #NamedQuery(name = "HaTypes.findByVacantNum", query = "SELECT h FROM
HaTypes h WHERE h.vacantNum = :vacantNum")
, #NamedQuery(name = "HaTypes.findByPrice", query = "SELECT h FROM HaTypes h
WHERE h.price = :price")})
public class HaTypes implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "hatID")
private Integer hatID;
#Basic(optional = false)
#Column(name = "type")
private String type;
#Basic(optional = false)
#Column(name = "acceptedGender")
private String acceptedGender;
#Basic(optional = false)
#Column(name = "vacantNum")
private int vacantNum;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields
consider using these annotations to enforce field validation
#Basic(optional = false)
#Column(name = "price")
private BigDecimal price;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hatID")
private Collection<Reservation> reservationCollection;
#JoinColumn(name = "hadID", referencedColumnName = "hadID")
#ManyToOne(optional = false)
private HaDetails hadID;
public HaTypes() {
}
public HaTypes(Integer hatID) {
this.hatID = hatID;
}
public HaTypes(Integer hatID, String type, String acceptedGender, int
vacantNum, BigDecimal price) {
this.hatID = hatID;
this.type = type;
this.acceptedGender = acceptedGender;
this.vacantNum = vacantNum;
this.price = price;
}
public Integer getHatID() {
return hatID;
}
public void setHatID(Integer hatID) {
this.hatID = hatID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAcceptedGender() {
return acceptedGender;
}
public void setAcceptedGender(String acceptedGender) {
this.acceptedGender = acceptedGender;
}
public int getVacantNum() {
return vacantNum;
}
public void setVacantNum(int vacantNum) {
this.vacantNum = vacantNum;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
#XmlTransient
public Collection<Reservation> getReservationCollection() {
return reservationCollection;
}
public void setReservationCollection(Collection<Reservation>
reservationCollection) {
this.reservationCollection = reservationCollection;
}
public HaDetails getHadID() {
return hadID;
}
public void setHadID(HaDetails hadID) {
this.hadID = hadID;
}
#Override
public int hashCode() {
int hash = 0;
hash += (hatID != null ? hatID.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 HaTypes)) {
return false;
}
HaTypes other = (HaTypes) object;
if ((this.hatID == null && other.hatID != null) || (this.hatID != null
&& !this.hatID.equals(other.hatID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.balay.entity.HaTypes[ hatID=" + hatID + " ]";
}
}
#Entity
#Table(name = "ha_details")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "HaDetails.findAll", query = "SELECT h FROM HaDetails h")
, #NamedQuery(name = "HaDetails.findByHadID", query = "SELECT h FROM
HaDetails h WHERE h.hadID = :hadID")
, #NamedQuery(name = "HaDetails.findByBusinessName", query = "SELECT h FROM
HaDetails h WHERE h.businessName = :businessName")
, #NamedQuery(name = "HaDetails.findByContactNum", query = "SELECT h FROM
HaDetails h WHERE h.contactNum = :contactNum")
, #NamedQuery(name = "HaDetails.findByBusinessAddress", query = "SELECT h
FROM HaDetails h WHERE h.businessAddress = :businessAddress")
, #NamedQuery(name = "HaDetails.findByStatus", query = "SELECT h FROM
HaDetails h WHERE h.status = :status")
, #NamedQuery(name = "HaDetails.findByRegDate", query = "SELECT h FROM
HaDetails h WHERE h.regDate = :regDate")
, #NamedQuery(name = "HaDetails.findByRemarks", query = "SELECT h FROM
HaDetails h WHERE h.remarks = :remarks")
, #NamedQuery(name = "HaDetails.findByLongitude", query = "SELECT h FROM
HaDetails h WHERE h.longitude = :longitude")
, #NamedQuery(name = "HaDetails.findByLatitude", query = "SELECT h FROM
HaDetails h WHERE h.latitude = :latitude")})
public class HaDetails implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "hadID")
private Integer hadID;
#Basic(optional = false)
#Column(name = "businessName")
private String businessName;
#Basic(optional = false)
#Column(name = "contactNum")
private String contactNum;
#Basic(optional = false)
#Column(name = "businessAddress")
private String businessAddress;
#Basic(optional = false)
#Column(name = "status")
private String status;
#Basic(optional = false)
#Column(name = "regDate")
#Temporal(TemporalType.TIMESTAMP)
private Date regDate;
#Column(name = "remarks")
private String remarks;
#Basic(optional = false)
#Column(name = "longitude")
private String longitude;
#Basic(optional = false)
#Column(name = "latitude")
private String latitude;
#JoinColumn(name = "landlordID", referencedColumnName = "landlordID")
#ManyToOne(optional = false)
private Landlord landlordID;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hadID")
private Collection<HaImages> haImagesCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hadID")
private Collection<HaAmenities> haAmenitiesCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hadID")
private Collection<HaTypes> haTypesCollection;
#OneToMany(mappedBy = "hadID")
private Collection<Tenant> tenantCollection;
public HaDetails() {
}
public HaDetails(Integer hadID) {
this.hadID = hadID;
}
public HaDetails(Integer hadID, String businessName, String contactNum, String businessAddress, String status, Date regDate, String longitude, String latitude) {
this.hadID = hadID;
this.businessName = businessName;
this.contactNum = contactNum;
this.businessAddress = businessAddress;
this.status = status;
this.regDate = regDate;
this.longitude = longitude;
this.latitude = latitude;
}
public Integer getHadID() {
return hadID;
}
public void setHadID(Integer hadID) {
this.hadID = hadID;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getContactNum() {
return contactNum;
}
public void setContactNum(String contactNum) {
this.contactNum = contactNum;
}
public String getBusinessAddress() {
return businessAddress;
}
public void setBusinessAddress(String businessAddress) {
this.businessAddress = businessAddress;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public Landlord getLandlordID() {
return landlordID;
}
public void setLandlordID(Landlord landlordID) {
this.landlordID = landlordID;
}
#XmlTransient
public Collection<HaImages> getHaImagesCollection() {
return haImagesCollection;
}
public void setHaImagesCollection(Collection<HaImages> haImagesCollection) {
this.haImagesCollection = haImagesCollection;
}
#XmlTransient
public Collection<HaAmenities> getHaAmenitiesCollection() {
return haAmenitiesCollection;
}
public void setHaAmenitiesCollection(Collection<HaAmenities>
haAmenitiesCollection) {
this.haAmenitiesCollection = haAmenitiesCollection;
}
#XmlTransient
public Collection<HaTypes> getHaTypesCollection() {
return haTypesCollection;
}
public void setHaTypesCollection(Collection<HaTypes> haTypesCollection) {
this.haTypesCollection = haTypesCollection;
}
#XmlTransient
public Collection<Tenant> getTenantCollection() {
return tenantCollection;
}
public void setTenantCollection(Collection<Tenant> tenantCollection) {
this.tenantCollection = tenantCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (hadID != null ? hadID.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 HaDetails)) {
return false;
}
HaDetails other = (HaDetails) object;
if ((this.hadID == null && other.hadID != null) || (this.hadID != null
&& !this.hadID.equals(other.hadID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.balay.entity.HaDetails[ hadID=" + hadID + " ]";
}
}
How do you update an entity in jpa using the put method ?
I am updating using the following JSON:
{
"acceptedGender":"both",
"price":123123.00,
"type":"apartment",
"vacantNum":13,
"hadID":4
}
I used the put method below for updating is it correct?
Can someone pls help me
Here is my code:
#javax.ejb.Stateless
#Path("com.balay.entity.hatypes")
public class HaTypesFacadeREST extends AbstractFacade<HaTypes> {
#PersistenceContext(unitName = "BalayRSPU")
private EntityManager em;
public HaTypesFacadeREST() {
super(HaTypes.class);
}
**#POST
#Override
#Consumes({MediaType.APPLICATION_JSON})
public void create(HaTypes entity) {
em = Persistence.createEntityManagerFactory("BalayRSPU").createEntityManager();
try{
em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();
}finally{
em.close();
}
}**
#PUT
#Path("{id}")
#Consumes({MediaType.APPLICATION_JSON})
public void edit(#PathParam("id") Integer id, HaTypes entity) {
em =
Persistence.createEntityManagerFactory("BalayRSPU").
createEntityManager();
try{
em.getTransaction().begin();
Admin update = em.getReference(Hatypes.class, id);
update = entity;
em.persist(update);
em.getTransaction().commit();
}finally{
em.close();
}
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Integer id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({MediaType.APPLICATION_JSON})
public HaTypes find(#PathParam("id") Integer id) {
return super.find(id);
}
#GET
#Override
#Produces({MediaType.APPLICATION_JSON})
public List<HaTypes> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({MediaType.APPLICATION_JSON})
public List<HaTypes> findRange(#PathParam("from") Integer from,
#PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String countREST() {
return String.valueOf(super.count());
}
#Override
protected EntityManager getEntityManager() {
em =
Persistence.createEntityManagerFactory("BalayRSPU").createEntityManager();
return em;
}
}
#Entity
#Table(name = "ha_types")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "HaTypes.findAll", query = "SELECT h FROM HaTypes h")
, #NamedQuery(name = "HaTypes.findByHatID", query = "SELECT h FROM HaTypes h
WHERE h.hatID = :hatID")
, #NamedQuery(name = "HaTypes.findByType", query = "SELECT h FROM HaTypes h
WHERE h.type = :type")
, #NamedQuery(name = "HaTypes.findByAcceptedGender", query = "SELECT h FROM
HaTypes h WHERE h.acceptedGender = :acceptedGender")
, #NamedQuery(name = "HaTypes.findByVacantNum", query = "SELECT h FROM
HaTypes h WHERE h.vacantNum = :vacantNum")
, #NamedQuery(name = "HaTypes.findByPrice", query = "SELECT h FROM HaTypes h
WHERE h.price = :price")})
public class HaTypes implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "hatID")
private Integer hatID;
#Basic(optional = false)
#Column(name = "type")
private String type;
#Basic(optional = false)
#Column(name = "acceptedGender")
private String acceptedGender;
#Basic(optional = false)
#Column(name = "vacantNum")
private int vacantNum;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields
consider using these annotations to enforce field validation
#Basic(optional = false)
#Column(name = "price")
private BigDecimal price;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hatID")
private Collection<Reservation> reservationCollection;
#JoinColumn(name = "hadID", referencedColumnName = "hadID")
#ManyToOne(optional = false)
private HaDetails hadID;
public HaTypes() {
}
public HaTypes(Integer hatID) {
this.hatID = hatID;
}
public HaTypes(Integer hatID, String type, String acceptedGender, int
vacantNum, BigDecimal price) {
this.hatID = hatID;
this.type = type;
this.acceptedGender = acceptedGender;
this.vacantNum = vacantNum;
this.price = price;
}
public Integer getHatID() {
return hatID;
}
public void setHatID(Integer hatID) {
this.hatID = hatID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAcceptedGender() {
return acceptedGender;
}
public void setAcceptedGender(String acceptedGender) {
this.acceptedGender = acceptedGender;
}
public int getVacantNum() {
return vacantNum;
}
public void setVacantNum(int vacantNum) {
this.vacantNum = vacantNum;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
#XmlTransient
public Collection<Reservation> getReservationCollection() {
return reservationCollection;
}
public void setReservationCollection(Collection<Reservation>
reservationCollection) {
this.reservationCollection = reservationCollection;
}
public HaDetails getHadID() {
return hadID;
}
public void setHadID(HaDetails hadID) {
this.hadID = hadID;
}
#Override
public int hashCode() {
int hash = 0;
hash += (hatID != null ? hatID.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 HaTypes)) {
return false;
}
HaTypes other = (HaTypes) object;
if ((this.hatID == null && other.hatID != null) || (this.hatID != null
&& !this.hatID.equals(other.hatID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.balay.entity.HaTypes[ hatID=" + hatID + " ]";
}
}
#Entity
#Table(name = "ha_details")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "HaDetails.findAll", query = "SELECT h FROM HaDetails h")
, #NamedQuery(name = "HaDetails.findByHadID", query = "SELECT h FROM
HaDetails h WHERE h.hadID = :hadID")
, #NamedQuery(name = "HaDetails.findByBusinessName", query = "SELECT h FROM
HaDetails h WHERE h.businessName = :businessName")
, #NamedQuery(name = "HaDetails.findByContactNum", query = "SELECT h FROM
HaDetails h WHERE h.contactNum = :contactNum")
, #NamedQuery(name = "HaDetails.findByBusinessAddress", query = "SELECT h
FROM HaDetails h WHERE h.businessAddress = :businessAddress")
, #NamedQuery(name = "HaDetails.findByStatus", query = "SELECT h FROM
HaDetails h WHERE h.status = :status")
, #NamedQuery(name = "HaDetails.findByRegDate", query = "SELECT h FROM
HaDetails h WHERE h.regDate = :regDate")
, #NamedQuery(name = "HaDetails.findByRemarks", query = "SELECT h FROM
HaDetails h WHERE h.remarks = :remarks")
, #NamedQuery(name = "HaDetails.findByLongitude", query = "SELECT h FROM
HaDetails h WHERE h.longitude = :longitude")
, #NamedQuery(name = "HaDetails.findByLatitude", query = "SELECT h FROM
HaDetails h WHERE h.latitude = :latitude")})
public class HaDetails implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "hadID")
private Integer hadID;
#Basic(optional = false)
#Column(name = "businessName")
private String businessName;
#Basic(optional = false)
#Column(name = "contactNum")
private String contactNum;
#Basic(optional = false)
#Column(name = "businessAddress")
private String businessAddress;
#Basic(optional = false)
#Column(name = "status")
private String status;
#Basic(optional = false)
#Column(name = "regDate")
#Temporal(TemporalType.TIMESTAMP)
private Date regDate;
#Column(name = "remarks")
private String remarks;
#Basic(optional = false)
#Column(name = "longitude")
private String longitude;
#Basic(optional = false)
#Column(name = "latitude")
private String latitude;
#JoinColumn(name = "landlordID", referencedColumnName = "landlordID")
#ManyToOne(optional = false)
private Landlord landlordID;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hadID")
private Collection<HaImages> haImagesCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hadID")
private Collection<HaAmenities> haAmenitiesCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "hadID")
private Collection<HaTypes> haTypesCollection;
#OneToMany(mappedBy = "hadID")
private Collection<Tenant> tenantCollection;
public HaDetails() {
}
public HaDetails(Integer hadID) {
this.hadID = hadID;
}
public HaDetails(Integer hadID, String businessName, String contactNum, String businessAddress, String status, Date regDate, String longitude, String latitude) {
this.hadID = hadID;
this.businessName = businessName;
this.contactNum = contactNum;
this.businessAddress = businessAddress;
this.status = status;
this.regDate = regDate;
this.longitude = longitude;
this.latitude = latitude;
}
public Integer getHadID() {
return hadID;
}
public void setHadID(Integer hadID) {
this.hadID = hadID;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getContactNum() {
return contactNum;
}
public void setContactNum(String contactNum) {
this.contactNum = contactNum;
}
public String getBusinessAddress() {
return businessAddress;
}
public void setBusinessAddress(String businessAddress) {
this.businessAddress = businessAddress;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public Landlord getLandlordID() {
return landlordID;
}
public void setLandlordID(Landlord landlordID) {
this.landlordID = landlordID;
}
#XmlTransient
public Collection<HaImages> getHaImagesCollection() {
return haImagesCollection;
}
public void setHaImagesCollection(Collection<HaImages> haImagesCollection) {
this.haImagesCollection = haImagesCollection;
}
#XmlTransient
public Collection<HaAmenities> getHaAmenitiesCollection() {
return haAmenitiesCollection;
}
public void setHaAmenitiesCollection(Collection<HaAmenities>
haAmenitiesCollection) {
this.haAmenitiesCollection = haAmenitiesCollection;
}
#XmlTransient
public Collection<HaTypes> getHaTypesCollection() {
return haTypesCollection;
}
public void setHaTypesCollection(Collection<HaTypes> haTypesCollection) {
this.haTypesCollection = haTypesCollection;
}
#XmlTransient
public Collection<Tenant> getTenantCollection() {
return tenantCollection;
}
public void setTenantCollection(Collection<Tenant> tenantCollection) {
this.tenantCollection = tenantCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (hadID != null ? hadID.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 HaDetails)) {
return false;
}
HaDetails other = (HaDetails) object;
if ((this.hadID == null && other.hadID != null) || (this.hadID != null
&& !this.hadID.equals(other.hadID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.balay.entity.HaDetails[ hadID=" + hadID + " ]";
}
}
Basically I'm implementing a PDS (Personal Data Sheet) so I have tables such as Client (employee), Personalinfo, Otherinfo.
Client table structure:
idClients, name, institute, username, password, usertype
Personalinfo table structure:
idPersonalInfo, agencyno, bloodtype, status, citizenship, address, idClients
I can add client successfully but when I'm trying to add/update personalinfo, I get
MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
In personalinfo class I have this line also:
#JoinColumn(name = "idClients", referencedColumnName = "idClients", insertable = false, updatable = false)
In Clients class I also included:
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
private Personalinfo personalinfo;
But I can't figure out why I'm getting constraint violations.
Error Code: 1452
Call: INSERT INTO personalinfo (...) VALUES (...)
bind => [7parameters bound]
Query: InsertObjectQuery(com.profiling.database.Personalinfo[ idPersonalInfo=null ])
EDIT:
if (personal != null) {
.....
personal.setClients(client);
personal.setIdPersonalInfo(client.getIdClients());
EntityManager em = emanager.getEntityManager();
em.getTransaction().begin();
em.persist(personal);
em.getTransaction().commit();
JOptionPane.showMessageDialog(rootPane, "Personal Info Updated Successfully");
} else {
personal = new Personalinfo();
....
personal.setClients(client);
client.setPersonalinfo(personal);
EntityManager em = emanager.getEntityManager();
em.getTransaction().begin();
em.persist(personal);
em.getTransaction().commit();
JOptionPane.showMessageDialog(rootPane, "New Personal Info Save");
}
EDIT
Client Class:
#Entity
#Table(name = "clients")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Clients.findAll", query = "SELECT c FROM Clients c"),
#NamedQuery(name = "Clients.findByIdClients", query = "SELECT c FROM Clients c WHERE c.idClients = :idClients"),
#NamedQuery(name = "Clients.findByFirstName", query = "SELECT c FROM Clients c WHERE c.firstName = :firstName"),
#NamedQuery(name = "Clients.findByGender", query = "SELECT c FROM Clients c WHERE c.gender = :gender"),
#NamedQuery(name = "Clients.findByLastName", query = "SELECT c FROM Clients c WHERE c.lastName = :lastName"),
#NamedQuery(name = "Clients.findByMiddlename", query = "SELECT c FROM Clients c WHERE c.middlename = :middlename"),
#NamedQuery(name = "Clients.findByNameExtension", query = "SELECT c FROM Clients c WHERE c.nameExtension = :nameExtension")})
public class Clients implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idClients")
private Integer idClients;
#Column(name = "FirstName")
private String firstName;
#Column(name = "Gender")
private String gender;
#Column(name = "LastName")
private String lastName;
#Column(name = "Middlename")
private String middlename;
#Column(name = "NameExtension")
private String nameExtension;
#Column(name = "Institute")
private String institute;
//value added
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "userType")
private String userType;
#OneToMany(mappedBy = "idClients")
private List<Workexpe> workexpeList;
#OneToMany(mappedBy = "idClients")
private List<Ratingscore> ratingscoreList;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
private Familyback familyback;
#OneToMany(mappedBy = "idClients")
private List<Civilservice> civilserviceList;
#OneToMany(mappedBy = "idClients")
private List<Staffscore> staffscoreList;
#OneToMany(mappedBy = "idClients")
private List<Referenceinfo> referenceinfoList;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
private Personalinfo personalinfo;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
// #OneToOne(mappedBy = "idClients")
private Otherinfo otherinfo;
#OneToMany(mappedBy = "idClients")
private List<Trainingprog> trainingprogList;
#OneToMany(mappedBy = "idClients")
private List<Children> childrenList;
#OneToMany(mappedBy = "idClients")
private List<Specialskills> specialskillsList;
#OneToMany(mappedBy = "idClients")
private List<Educback> educbackList;
#OneToMany(mappedBy = "idClients")
private List<Voluntarywork> voluntaryworkList;
public Clients() {
}
public Clients(Integer idClients) {
this.idClients = idClients;
}
public Integer getIdClients() {
return idClients;
}
public void setIdClients(Integer idClients) {
this.idClients = idClients;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getNameExtension() {
return nameExtension;
}
public void setNameExtension(String nameExtension) {
this.nameExtension = nameExtension;
}
#XmlTransient
public List<Workexpe> getWorkexpeList() {
return workexpeList;
}
public void setWorkexpeList(List<Workexpe> workexpeList) {
this.workexpeList = workexpeList;
}
#XmlTransient
public List<Ratingscore> getRatingscoreList() {
return ratingscoreList;
}
public void setRatingscoreList(List<Ratingscore> ratingscoreList) {
this.ratingscoreList = ratingscoreList;
}
public Familyback getFamilyback() {
return familyback;
}
public void setFamilyback(Familyback familyback) {
this.familyback = familyback;
}
#XmlTransient
public List<Civilservice> getCivilserviceList() {
return civilserviceList;
}
public void setCivilserviceList(List<Civilservice> civilserviceList) {
this.civilserviceList = civilserviceList;
}
#XmlTransient
public List<Staffscore> getStaffscoreList() {
return staffscoreList;
}
public void setStaffscoreList(List<Staffscore> staffscoreList) {
this.staffscoreList = staffscoreList;
}
#XmlTransient
public List<Referenceinfo> getReferenceinfoList() {
return referenceinfoList;
}
public void setReferenceinfoList(List<Referenceinfo> referenceinfoList) {
this.referenceinfoList = referenceinfoList;
}
public Personalinfo getPersonalinfo() {
return personalinfo;
}
public void setPersonalinfo(Personalinfo personalinfo) {
this.personalinfo = personalinfo;
}
public Otherinfo getOtherinfo() {
return otherinfo;
}
public void setOtherinfo(Otherinfo otherinfo) {
this.otherinfo = otherinfo;
}
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 String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
#XmlTransient
public List<Trainingprog> getTrainingprogList() {
return trainingprogList;
}
public void setTrainingprogList(List<Trainingprog> trainingprogList) {
this.trainingprogList = trainingprogList;
}
#XmlTransient
public List<Children> getChildrenList() {
return childrenList;
}
public void setChildrenList(List<Children> childrenList) {
this.childrenList = childrenList;
}
#XmlTransient
public List<Specialskills> getSpecialskillsList() {
return specialskillsList;
}
public void setSpecialskillsList(List<Specialskills> specialskillsList) {
this.specialskillsList = specialskillsList;
}
#XmlTransient
public List<Educback> getEducbackList() {
return educbackList;
}
public void setEducbackList(List<Educback> educbackList) {
this.educbackList = educbackList;
}
#XmlTransient
public List<Voluntarywork> getVoluntaryworkList() {
return voluntaryworkList;
}
public void setVoluntaryworkList(List<Voluntarywork> voluntaryworkList) {
this.voluntaryworkList = voluntaryworkList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idClients != null ? idClients.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 Clients)) {
return false;
}
Clients other = (Clients) object;
if ((this.idClients == null && other.idClients != null) || (this.idClients != null && !this.idClients.equals(other.idClients))) {
return false;
}
return true;
}
#Override
public String toString() {
return this.lastName + ", " + this.firstName;
}
public String getInstitute() {
return institute;
}
public void setInstitute(String institute) {
this.institute = institute;
}
}
Personalinfo
#Entity
#Table(name = "personalinfo")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Personalinfo.findAll", query = "SELECT p FROM Personalinfo p"),
#NamedQuery(name = "Personalinfo.findByIdPersonalInfo", query = "SELECT p FROM Personalinfo p WHERE p.idPersonalInfo = :idPersonalInfo"),
#NamedQuery(name = "Personalinfo.findByAgencyNumber", query = "SELECT p FROM Personalinfo p WHERE p.agencyNumber = :agencyNumber"),
#NamedQuery(name = "Personalinfo.findByBloodType", query = "SELECT p FROM Personalinfo p WHERE p.bloodType = :bloodType"),
#NamedQuery(name = "Personalinfo.findByCellphone", query = "SELECT p FROM Personalinfo p WHERE p.cellphone = :cellphone"),
#NamedQuery(name = "Personalinfo.findByCevilStatus", query = "SELECT p FROM Personalinfo p WHERE p.cevilStatus = :cevilStatus"),
#NamedQuery(name = "Personalinfo.findByCitizenship", query = "SELECT p FROM Personalinfo p WHERE p.citizenship = :citizenship"),
#NamedQuery(name = "Personalinfo.findByDateofBirth", query = "SELECT p FROM Personalinfo p WHERE p.dateofBirth = :dateofBirth"),
#NamedQuery(name = "Personalinfo.findByEmailAdd", query = "SELECT p FROM Personalinfo p WHERE p.emailAdd = :emailAdd"),
#NamedQuery(name = "Personalinfo.findByGsis", query = "SELECT p FROM Personalinfo p WHERE p.gsis = :gsis"),
#NamedQuery(name = "Personalinfo.findByHeight", query = "SELECT p FROM Personalinfo p WHERE p.height = :height"),
#NamedQuery(name = "Personalinfo.findByPagibig", query = "SELECT p FROM Personalinfo p WHERE p.pagibig = :pagibig"),
#NamedQuery(name = "Personalinfo.findByPermanentAddress", query = "SELECT p FROM Personalinfo p WHERE p.permanentAddress = :permanentAddress"),
#NamedQuery(name = "Personalinfo.findByPhilHealth", query = "SELECT p FROM Personalinfo p WHERE p.philHealth = :philHealth"),
#NamedQuery(name = "Personalinfo.findByPlaceofBirth", query = "SELECT p FROM Personalinfo p WHERE p.placeofBirth = :placeofBirth"),
#NamedQuery(name = "Personalinfo.findByResidentialAddress", query = "SELECT p FROM Personalinfo p WHERE p.residentialAddress = :residentialAddress"),
#NamedQuery(name = "Personalinfo.findBySssNo", query = "SELECT p FROM Personalinfo p WHERE p.sssNo = :sssNo"),
#NamedQuery(name = "Personalinfo.findByTelephone1", query = "SELECT p FROM Personalinfo p WHERE p.telephone1 = :telephone1"),
#NamedQuery(name = "Personalinfo.findByTelephone2", query = "SELECT p FROM Personalinfo p WHERE p.telephone2 = :telephone2"),
#NamedQuery(name = "Personalinfo.findByTin", query = "SELECT p FROM Personalinfo p WHERE p.tin = :tin"),
#NamedQuery(name = "Personalinfo.findByWeight", query = "SELECT p FROM Personalinfo p WHERE p.weight = :weight"),
#NamedQuery(name = "Personalinfo.findByZipcode1", query = "SELECT p FROM Personalinfo p WHERE p.zipcode1 = :zipcode1"),
#NamedQuery(name = "Personalinfo.findByZipcode2", query = "SELECT p FROM Personalinfo p WHERE p.zipcode2 = :zipcode2")})
public class Personalinfo implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idPersonalInfo")
private Integer idPersonalInfo;
#Column(name = "AgencyNumber")
private String agencyNumber;
#Column(name = "BloodType")
private String bloodType;
#Column(name = "Cellphone")
private String cellphone;
#Column(name = "CevilStatus")
private String cevilStatus;
#Column(name = "Citizenship")
private String citizenship;
#Column(name = "DateofBirth")
#Temporal(TemporalType.TIMESTAMP)
private Date dateofBirth;
#Column(name = "EmailAdd")
private String emailAdd;
#Column(name = "GSIS")
private String gsis;
#Column(name = "Height")
private String height;
#Column(name = "Pagibig")
private String pagibig;
#Column(name = "PermanentAddress")
private String permanentAddress;
#Column(name = "PhilHealth")
private String philHealth;
#Lob
#Column(name = "Picture")
private byte[] picture;
#Column(name = "PlaceofBirth")
private String placeofBirth;
#Column(name = "ResidentialAddress")
private String residentialAddress;
#Column(name = "SssNo")
private String sssNo;
#Column(name = "Telephone1")
private String telephone1;
#Column(name = "Telephone2")
private String telephone2;
#Column(name = "Tin")
private String tin;
#Column(name = "Weight")
private String weight;
#Column(name = "Zipcode1")
private String zipcode1;
#Column(name = "Zipcode2")
private String zipcode2;
#Column(name = "IdClients")
private String idClients;
#JoinColumn(name = "idClients", referencedColumnName = "idClients", insertable = false, updatable = false)
// #JoinColumn(name = "idClients", referencedColumnName = "idClients")
#OneToOne(optional = false)
private Clients clients;
public Personalinfo() {
}
public Personalinfo(Integer idPersonalInfo) {
this.idPersonalInfo = idPersonalInfo;
}
public Integer getIdPersonalInfo() {
return idPersonalInfo;
}
public void setIdPersonalInfo(Integer idPersonalInfo) {
this.idPersonalInfo = idPersonalInfo;
}
public String getAgencyNumber() {
return agencyNumber;
}
public void setAgencyNumber(String agencyNumber) {
this.agencyNumber = agencyNumber;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getCevilStatus() {
return cevilStatus;
}
public void setCevilStatus(String cevilStatus) {
this.cevilStatus = cevilStatus;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
public Date getDateofBirth() {
return dateofBirth;
}
public void setDateofBirth(Date dateofBirth) {
this.dateofBirth = dateofBirth;
}
public String getEmailAdd() {
return emailAdd;
}
public void setEmailAdd(String emailAdd) {
this.emailAdd = emailAdd;
}
public String getGsis() {
return gsis;
}
public void setGsis(String gsis) {
this.gsis = gsis;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getPagibig() {
return pagibig;
}
public void setPagibig(String pagibig) {
this.pagibig = pagibig;
}
public String getPermanentAddress() {
return permanentAddress;
}
public void setPermanentAddress(String permanentAddress) {
this.permanentAddress = permanentAddress;
}
public String getPhilHealth() {
return philHealth;
}
public void setPhilHealth(String philHealth) {
this.philHealth = philHealth;
}
public byte[] getPicture() {
return picture;
}
public void setPicture(byte[] picture) {
this.picture = picture;
}
public String getPlaceofBirth() {
return placeofBirth;
}
public void setPlaceofBirth(String placeofBirth) {
this.placeofBirth = placeofBirth;
}
public String getResidentialAddress() {
return residentialAddress;
}
public void setResidentialAddress(String residentialAddress) {
this.residentialAddress = residentialAddress;
}
public String getSssNo() {
return sssNo;
}
public void setSssNo(String sssNo) {
this.sssNo = sssNo;
}
public String getTelephone1() {
return telephone1;
}
public void setTelephone1(String telephone1) {
this.telephone1 = telephone1;
}
public String getTelephone2() {
return telephone2;
}
public void setTelephone2(String telephone2) {
this.telephone2 = telephone2;
}
public String getTin() {
return tin;
}
public void setTin(String tin) {
this.tin = tin;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getZipcode1() {
return zipcode1;
}
public void setZipcode1(String zipcode1) {
this.zipcode1 = zipcode1;
}
public String getZipcode2() {
return zipcode2;
}
public void setZipcode2(String zipcode2) {
this.zipcode2 = zipcode2;
}
#MapsId
public Clients getClients() {
return clients;
}
#MapsId
public void setClients(Clients clients) {
this.clients = clients;
}
public String getIdClient() {
return idClients;
}
public void setIdClients(String clients) {
this.idClients = clients;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idPersonalInfo != null ? idPersonalInfo.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 Personalinfo)) {
return false;
}
Personalinfo other = (Personalinfo) object;
if ((this.idPersonalInfo == null && other.idPersonalInfo != null) || (this.idPersonalInfo != null && !this.idPersonalInfo.equals(other.idPersonalInfo))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.doscst.profiling.database.Personalinfo[ idPersonalInfo=" + idPersonalInfo + " ]";
}
}
Suppose you try with this in PersonalInfo class and check.
#OneToOne
#JoinColumn(name = "idClients")
private Clients clients;
Hi I'm new to EJB (NetBeans), I'm trying to retrieve Named queryProperty.findAll via my servlet but I'm having a problem.
this the problem
non static method cannot be referenced from a static context where T
is a type of variable
AbstractFacade class
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Entity class (Property)
#Entity
#Table(name = "property")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Property.findAll", query = "SELECT p FROM Property p")
, #NamedQuery(name = "Property.findByPropertyId", query = "SELECT p FROM Property p WHERE p.propertyId = :propertyId")
, #NamedQuery(name = "Property.findByPropertyType", query = "SELECT p FROM Property p WHERE p.propertyType = :propertyType")
, #NamedQuery(name = "Property.findByNumOfBedroom", query = "SELECT p FROM Property p WHERE p.numOfBedroom = :numOfBedroom")
, #NamedQuery(name = "Property.findByNumOfBathroom", query = "SELECT p FROM Property p WHERE p.numOfBathroom = :numOfBathroom")
, #NamedQuery(name = "Property.findByAddress", query = "SELECT p FROM Property p WHERE p.address = :address")
, #NamedQuery(name = "Property.findByDescription", query = "SELECT p FROM Property p WHERE p.description = :description")
, #NamedQuery(name = "Property.findByFurnish", query = "SELECT p FROM Property p WHERE p.furnish = :furnish")
, #NamedQuery(name = "Property.findByGarden", query = "SELECT p FROM Property p WHERE p.garden = :garden")
, #NamedQuery(name = "Property.findByArea", query = "SELECT p FROM Property p WHERE p.area = :area")
, #NamedQuery(name = "Property.findByBuyType", query = "SELECT p FROM Property p WHERE p.buyType = :buyType")
, #NamedQuery(name = "Property.findByPropertyPrice", query = "SELECT p FROM Property p WHERE p.propertyPrice = :propertyPrice")})
public class Property implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "PropertyId")
private Integer propertyId;
#Size(max = 45)
#Column(name = "PropertyType")
private String propertyType;
#Column(name = "NumOfBedroom")
private Long numOfBedroom;
#Column(name = "NumOfBathroom")
private Long numOfBathroom;
#Size(max = 250)
#Column(name = "Address")
private String address;
#Size(max = 500)
#Column(name = "Description")
private String description;
#Size(max = 45)
#Column(name = "Furnish")
private String furnish;
#Size(max = 45)
#Column(name = "Garden")
private String garden;
#Column(name = "Area")
private Long area;
#Size(max = 45)
#Column(name = "BuyType")
private String buyType;
#Column(name = "PropertyPrice")
private Integer propertyPrice;
#Lob
#Column(name = "ImageUrl")
private byte[] imageUrl;
#OneToMany(mappedBy = "propertyId")
private Collection<Offer> offerCollection;
#JoinColumn(name = "agentsId", referencedColumnName = "AgentsId")
#ManyToOne
private Agents agentsId;
#JoinColumn(name = "OwnerId", referencedColumnName = "OwnerId")
#ManyToOne
private Owner ownerId;
public Property() {
}
public Property(Integer propertyId) {
this.propertyId = propertyId;
}
public Integer getPropertyId() {
return propertyId;
}
public void setPropertyId(Integer propertyId) {
this.propertyId = propertyId;
}
public String getPropertyType() {
return propertyType;
}
public void setPropertyType(String propertyType) {
this.propertyType = propertyType;
}
public Long getNumOfBedroom() {
return numOfBedroom;
}
public void setNumOfBedroom(Long numOfBedroom) {
this.numOfBedroom = numOfBedroom;
}
public Long getNumOfBathroom() {
return numOfBathroom;
}
public void setNumOfBathroom(Long numOfBathroom) {
this.numOfBathroom = numOfBathroom;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFurnish() {
return furnish;
}
public void setFurnish(String furnish) {
this.furnish = furnish;
}
public String getGarden() {
return garden;
}
public void setGarden(String garden) {
this.garden = garden;
}
public Long getArea() {
return area;
}
public void setArea(Long area) {
this.area = area;
}
public String getBuyType() {
return buyType;
}
public void setBuyType(String buyType) {
this.buyType = buyType;
}
public Integer getPropertyPrice() {
return propertyPrice;
}
public void setPropertyPrice(Integer propertyPrice) {
this.propertyPrice = propertyPrice;
}
public byte[] getImageUrl() {
return imageUrl;
}
public void setImageUrl(byte[] imageUrl) {
this.imageUrl = imageUrl;
}
#XmlTransient
public Collection<Offer> getOfferCollection() {
return offerCollection;
}
public void setOfferCollection(Collection<Offer> offerCollection) {
this.offerCollection = offerCollection;
}
public Agents getAgentsId() {
return agentsId;
}
public void setAgentsId(Agents agentsId) {
this.agentsId = agentsId;
}
public Owner getOwnerId() {
return ownerId;
}
public void setOwnerId(Owner ownerId) {
this.ownerId = ownerId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (propertyId != null ? propertyId.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 Property)) {
return false;
}
Property other = (Property) object;
if ((this.propertyId == null && other.propertyId != null) || (this.propertyId != null && !this.propertyId.equals(other.propertyId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Entities.Property[ propertyId=" + propertyId + " ]";
}
}
Servelt page
#Override
public void init() throws ServletException {
List<Property> PropertyList= PropertyFacade.findAll();
getServletContext().setAttribute("property", PropertyList);
}
PropertyFacade class
public class PropertyFacade extends AbstractFacade<Property> {
#PersistenceContext(unitName = "testRealPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PropertyFacade() {
super(Property.class);
}
Since findAll is not static, you need to create an instance of your PropertyFaçade. You can't just call PropertyFacade.findAll(). In spring, you would get this instance from the ApplicationContext, not sure how it is being created in ejb.
Note: mind the naming convention in java: the variables start with lowercase letter and the classes start with an uppercase letter. So, you should change PropertyList to propertyList.
In your servlet, do following:
#EJB
PropertyFacade propertyFacade;
#Override
public void init() throws ServletException {
List<Property> PropertyList= propertyFacade.findAll();
getServletContext().setAttribute("property", PropertyList);
}
And add #Stateless annotation in your PropertyFacade.class
#Stateless
public class PropertyFacade extends AbstractFacade<Property> {
#PersistenceContext(unitName = "testRealPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PropertyFacade() {
super(Property.class);
}
}
I have a class named Urunler and another class named Kategoriler.
Urunler table has foreign key which is primary key of Kategoriler table.
A Kategoriler object can have multiple Urunler object.
I need to have ManyToOne mapping from Urunler class to Kategoriler class.
But I could not achieve it.
Error tells me that I have not set katid foreign key of Urunler table.
Here is my code:
#Entity
#Table(name = "urunler")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Urunler.findAll", query = "SELECT u FROM Urunler u"),
#NamedQuery(name = "Urunler.findById", query = "SELECT u FROM Urunler u WHERE u.id = :id"),
#NamedQuery(name = "Urunler.findByAd", query = "SELECT u FROM Urunler u WHERE u.ad = :ad"),
#NamedQuery(name = "Urunler.findByAlis", query = "SELECT u FROM Urunler u WHERE u.alis = :alis"),
#NamedQuery(name = "Urunler.findBySatis", query = "SELECT u FROM Urunler u WHERE u.satis = :satis"),
#NamedQuery(name = "Urunler.findByStok", query = "SELECT u FROM Urunler u WHERE u.stok = :stok"),
#NamedQuery(name = "Urunler.findByAciklama", query = "SELECT u FROM Urunler u WHERE u.aciklama = :aciklama"),
#NamedQuery(name = "Urunler.findByKatid", query = "SELECT u FROM Urunler u WHERE u.katid = :katid")})
public class Urunler implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#ManyToOne(cascade = CascadeType.ALL)
private Kategoriler kategori;
public Kategoriler getKategori() {
return kategori;
}
public void setKategori(Kategoriler kategori) {
this.kategori = kategori;
}
#Basic(optional = false)
#Column(name = "ad")
private String ad;
#Basic(optional = false)
#Column(name = "alis")
private String alis;
#Basic(optional = false)
#Column(name = "satis")
private String satis;
#Basic(optional = false)
#Column(name = "stok")
private String stok;
#Column(name = "aciklama")
private String aciklama;
#Basic(optional = false)
#Column(name = "katid")
private Integer katid;
public Integer getKatid() {
return katid;
}
public void setKatid(Integer katid) {
this.katid = katid;
}
public Urunler() {
}
public Urunler(Integer id) {
this.id = id;
}
public Urunler(Integer id, String ad, String kategori, String alis, String satis, String stok, int katid) {
this.id = id;
this.ad = ad;
this.alis = alis;
this.satis = satis;
this.stok = stok;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
this.ad = ad;
}
public String getAlis() {
return alis;
}
public void setAlis(String alis) {
this.alis = alis;
}
public String getSatis() {
return satis;
}
public void setSatis(String satis) {
this.satis = satis;
}
public String getStok() {
return stok;
}
public void setStok(String stok) {
this.stok = stok;
}
public String getAciklama() {
return aciklama;
}
public void setAciklama(String aciklama) {
this.aciklama = aciklama;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Urunler)) {
return false;
}
Urunler other = (Urunler) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "HibClasses.Urunler[ id=" + id + " ]";
}
}
And this Kategoriler class:
#Entity
#Table(name = "kategoriler")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Kategoriler.findAll", query = "SELECT k FROM Kategoriler k"),
#NamedQuery(name = "Kategoriler.findById", query = "SELECT k FROM Kategoriler k WHERE k.id = :id"),
#NamedQuery(name = "Kategoriler.findByAd", query = "SELECT k FROM Kategoriler k WHERE k.ad = :ad"),
#NamedQuery(name = "Kategoriler.findByAciklama", query = "SELECT k FROM Kategoriler k WHERE k.aciklama = :aciklama")})
public class Kategoriler implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "ad")
private String ad;
#Column(name = "aciklama")
private String aciklama;
public Kategoriler() {
}
public Kategoriler(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAd() {
return ad;
}
public void setAd(String ad) {
this.ad = ad;
}
public String getAciklama() {
return aciklama;
}
public void setAciklama(String aciklama) {
this.aciklama = aciklama;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.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 Kategoriler)) {
return false;
}
Kategoriler other = (Kategoriler) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "HibClasses.Kategoriler[ id=" + id + " ]";
}
}
And this is where I call them:
btnDuzenle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Urunler urunler = new Urunler();
Kategoriler kategoriler = new Kategoriler();
kategoriler.setAd("Gıda");
kategoriler.setAciklama("Yenir la bunlar");
urunler.setAd("Bisküvi");
urunler.setAciklama("Biskrem");
urunler.setAlis("4");
urunler.setSatis("5");
urunler.setKategori(kategoriler);
urunler.setStok("4");
session.save(urunler);
session.getTransaction().commit();
}
});
I found a solution.
I have changed
...
#ManyToOne(cascade = CascadeType.ALL)
private Kategoriler kategori;
public Kategoriler getKategori() {
return kategori;
}
...
to that:
...
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "katid")
private Kategoriler kategori;
public Kategoriler getKategori() {
return kategori;
}
...
AND
...
#Column(name = "katid")
private Integer katid;
public Integer getKatid() {
return katid;
}
...
to that:
...
#Column(name = "katid", insertable = false , updatable = false)
private Integer katid;
public Integer getKatid() {
return katid;
}
...
Kategoriler should have a list of mapped by Kategoriler objects with proper anotations:
#OneToMany(mappedBy="kategoriler",cascade=CascadeType.ALL)
private List<Urunler> employees = new ArrayList<Urunler >();