I did the following tutorial to create a restful webservice with my mysql db http://netbeans.org/kb/docs/websvc/rest.html
The basic things works fine, but now I want to extend the service functionality. How can I add additional parameters to the GET service ? I tried this
http://img15.hostingpics.net/pics/708229Capturedcran20111205205553.png
but as a result I have all cities. when I add the parameter countryCode links the service becomes localhost:8080/Data/resources/converter.city/?countryCode=TUR×tamp=1323114935089 This is my code
CityFacadeRest.java
#Stateless
#Path("converter.city")
public class CityFacadeREST extends AbstractFacade<City> {
#PersistenceContext(unitName = "DataPU")
private EntityManager em;
public CityFacadeREST() {
super(City.class);
}
#POST
#Override
#Consumes({"application/xml", "application/json"})
public void create(City entity) {
super.create(entity);
}
#PUT
#Override
#Consumes({"application/xml", "application/json"})
public void edit(City entity) {
super.edit(entity);
}
#DELETE
#Path("{id}")
public void remove(#PathParam("id") Integer id) {
super.remove(super.find(id));
}
#GET
#Path("{id}")
#Produces({"application/xml", "application/json"})
public City find(#PathParam("id") Integer id) {
return super.find(id);
}
#GET
#Override
#Produces({"application/xml", "application/json"})
public List<City> findAll() {
return super.findAll();
}
#GET
#Path("{from}/{to}")
#Produces({"application/xml", "application/json"})
public List<City> findRange(#PathParam("from") Integer from, #PathParam("to") Integer to) {
return super.findRange(new int[]{from, to});
}
#GET
#Path("count")
#Produces("text/plain")
public String countREST() {
return String.valueOf(super.count());
}
#java.lang.Override
protected EntityManager getEntityManager() {
return em;
}
}
City.java
#Entity
#Table(name = "City")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "City.findAll", query = "SELECT c FROM City c"),
#NamedQuery(name = "City.findById", query = "SELECT c FROM City c WHERE c.id = :id"),
#NamedQuery(name = "City.findByName", query = "SELECT c FROM City c WHERE c.name = :name"),
#NamedQuery(name = "City.findByCountryCode", query = "SELECT c FROM City c WHERE c.countryCode = :countryCode"),
#NamedQuery(name = "City.findByDistrict", query = "SELECT c FROM City c WHERE c.district = :district"),
#NamedQuery(name = "City.findByPopulation", query = "SELECT c FROM City c WHERE c.population = :population")})
public class City implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 35)
#Column(name = "Name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 3)
#Column(name = "CountryCode")
private String countryCode;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "District")
private String district;
#Basic(optional = false)
#NotNull
#Column(name = "Population")
private int population;
public City() {
}
public City(Integer id) {
this.id = id;
}
public City(Integer id, String name, String countryCode, String district, int population) {
this.id = id;
this.name = name;
this.countryCode = countryCode;
this.district = district;
this.population = population;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
#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 City)) {
return false;
}
City other = (City) 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 "converter.City[ id=" + id + " ]";
}
}
You need to add another method
#GET
#Produces({"application/xml", "application/json"})
public City find(#DefaultValue("") #QueryParam("countryCode") String country,
<any other parameters you want to allow>
{
//code to search by the different parameters
}
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 + " ]";
}
}
I create a Restful web service with netbeans, I just specify the database and netbeans to create everything. IN sub-resources , i have only 4 URI:
converter.city (http://localhost:8080/Data/resources/converter.city)
converter.city/{id}(http://localhost:8080/Data/resources/converter.city/{id})
converter.city/{from}/{to(http://localhost:8080/Data/resources/converter.city/{from}/{to})
converter.city/count(http://localhost:8080/Data/resources/converter.city/count)
this is the generated code , watch the first part
#Entity
#Table(name = "City")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "City.findAll", query = "SELECT c FROM City c"),
#NamedQuery(name = "City.findById", query = "SELECT c FROM City c WHERE c.id = :id"),
#NamedQuery(name = "City.findByName", query = "SELECT c FROM City c WHERE c.name = :name"),
#NamedQuery(name = "City.findByCountryCode", query = "SELECT c FROM City c WHERE c.countryCode = :countryCode"),
#NamedQuery(name = "City.findByDistrict", query = "SELECT c FROM City c WHERE c.district = :district"),
#NamedQuery(name = "City.findByPopulation", query = "SELECT c FROM City c WHERE c.population = :population")})
public class City implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 35)
#Column(name = "Name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 3)
#Column(name = "CountryCode")
private String countryCode;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "District")
private String district;
#Basic(optional = false)
#NotNull
#Column(name = "Population")
private int population;
public City() {
}
public City(Integer id) {
this.id = id;
}
public City(Integer id, String name, String countryCode, String district, int population) {
this.id = id;
this.name = name;
this.countryCode = countryCode;
this.district = district;
this.population = population;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
#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 City)) {
return false;
}
City other = (City) 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 "converter.City[ id=" + id + " ]";
}
In the generated code there are many query and among them one that interests me
#NamedQuery(name = "City.findByCountryCode", query = "SELECT c FROM City c WHERE c.countryCode = :countryCode")
How can i use City.findByCountryCode ?
Query query = em.createNamedQuery("City.findByCountryCode")
.setParameter("countryCode", yourCountryCode);
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.
Been messing around with Hibernate and PostgreSQL trying to get it to work as expected.
But for some reason when I try to persist an object with a #OneToMany relationship with more than one item in the set all but the first item seem to be ignored. I've tried this via local and remote interfaces but get the same results each time. No exceptions are thrown, it looks like hibernate just stops persisting after the first unit has been persisted.
Any help much appreciated this one has been eluding me for days now.
I'm using Hibernate 3.5 and PostgreSQL 8.4.4 with Glassfish v3. All the annotations in the source are from the package javax.persistence - had to remove imports because of the character limit.
The FacadeManager is simply a utility to take the hassle out of jndi lookups, it simplifies accessing remote facades.
Here is the test method
#Test
public void testOneToManyCascade() throws Exception {
/*
* Set up entities requred to perform the test
*/
UnitFacadeRemote unitfr = FacadeManager
.getFacade(UnitFacadeRemote.class);
UserFacadeRemote userfr = FacadeManager
.getFacade(UserFacadeRemote.class);
User user = new User("P", "P", "000000", true, new Date(), "ypy#ypy",
"wordof mout", "slacker", "password");
Address address = new Address("yo", "go", "YOKO", "4123");
address.setCountry(FacadeManager.getFacade(CountryFacadeRemote.class)
.find(2));
user.setAddress(address);
Unit unit1 = new Unit(1, "Test Unit1", new Date(), "DisService",
"MyNation");
Unit unit2 = new Unit(2, "Test Unit2", new Date(), "DisService",
"TheirNation");
Unit unit3 = new Unit(3, "Test Unit3", new Date(), "DisService",
"TheirNation");
// Check no game exists
assertThat(FacadeManager.getFacade(GameFacadeRemote.class).findAll()
.size(), is(0));
Game game = new Game("blabla", 3333, "A game!", true);
// Create game and return reference to persisted game instance
game = FacadeManager.getFacade(GameFacadeRemote.class).registerGame(
game);
unit1.setGame(game);
unit2.setGame(game);
unit3.setGame(game);
// Find a virtue
Virtue v = FacadeManager.getFacade(VirtueFacadeRemote.class).find(1);
unit1.setVirtue(v);
unit2.setVirtue(v);
unit3.setVirtue(v);
// check that none of the above exist already
assertThat(userfr.findAll().size(), is(0));
assertThat(unitfr.findAll().size(), is(0));
/*
* Try persisting the by cascading from the user
*/
Set<Unit> unitSet = new HashSet<Unit>();
unitSet.add(unit2);
unitSet.add(unit1);
unitSet.add(unit3);
user.setUnitSet(unitSet);
unit1.setUser(user);
unit2.setUser(user);
unit3.setUser(user);
// Persist
userfr.create(user);
/*
* The result of the preceding persist is that the game, user, address
* and one unit are persisted, in this case unit2 but it seems whichever
* unit is first added to unitSet is the one that is persisted.
*/
}
Here follow the various entity classes
package com.game.database.entity;
#Entity
#Table(name = "address")
#NamedQueries({
#NamedQuery(name = "Address.findAll", query = "SELECT a FROM Address a"),
#NamedQuery(name = "Address.findById", query = "SELECT a FROM Address a WHERE a.id = :id"),
#NamedQuery(name = "Address.findByLine1", query = "SELECT a FROM Address a WHERE a.line1 = :line1"),
#NamedQuery(name = "Address.findByLine2", query = "SELECT a FROM Address a WHERE a.line2 = :line2"),
#NamedQuery(name = "Address.findByCity", query = "SELECT a FROM Address a WHERE a.city = :city"),
#NamedQuery(name = "Address.findByAreaCode", query = "SELECT a FROM Address a WHERE a.areaCode = :areaCode") })
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "address_id_seq", sequenceName = "address_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "line1")
private String line1;
#Basic(optional = false)
#Column(name = "line2")
private String line2;
#Basic(optional = false)
#Column(name = "city")
private String city;
#Basic(optional = false)
#Column(name = "areaCode")
private String areaCode;
#JoinColumn(name = "country", referencedColumnName = "id")
#ManyToOne(optional = false)
private Country country;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
private Set<User> userSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
private Set<CardDetails> cardDetailsSet;
public Address() {
}
public Address(Integer id) {
this.id = id;
}
public Address(String line1, String line2, String city, String areaCode) {
this.line1 = line1;
this.line2 = line2;
this.city = city;
this.areaCode = areaCode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Set<User> getUserSet() {
return userSet;
}
public void setUserSet(Set<User> userSet) {
this.userSet = userSet;
}
public Set<CardDetails> getCardDetailsSet() {
return cardDetailsSet;
}
public void setCardDetailsSet(Set<CardDetails> cardDetailsSet) {
this.cardDetailsSet = cardDetailsSet;
}
#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 Address)) {
return false;
}
Address other = (Address) 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 "com.game.database.entity.Address[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "game")
#NamedQueries({
#NamedQuery(name = "Game.findAll", query = "SELECT g FROM Game g"),
#NamedQuery(name = "Game.findById", query = "SELECT g FROM Game g WHERE g.id = :id"),
#NamedQuery(name = "Game.findByHost", query = "SELECT g FROM Game g WHERE g.host = :host"),
#NamedQuery(name = "Game.findByPort", query = "SELECT g FROM Game g WHERE g.port = :port"),
#NamedQuery(name = "Game.findByDescription", query = "SELECT g FROM Game g WHERE g.description = :description"),
#NamedQuery(name = "Game.findByActive", query = "SELECT g FROM Game g WHERE g.active = :active"),
#NamedQuery(name = "Game.findByHostAndPort", query = "SELECT g FROM Game g WHERE g.host = :host AND g.port = :port") })
public class Game implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "game_id_seq", sequenceName = "game_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "game_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "host")
private String host;
#Basic(optional = false)
#Column(name = "port")
private int port;
#Basic(optional = false)
#Column(name = "description")
private String description;
#Basic(optional = false)
#Column(name = "active")
private Boolean active;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
private Set<Unit> unitSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
private Set<Payment> paymentSet;
public Game() {
}
public Game(Integer id) {
this.id = id;
}
public Game(String host, int port, String description, Boolean active) {
this.host = host;
this.port = port;
this.description = description;
this.active = active;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
public Set<Payment> getPaymentSet() {
return paymentSet;
}
public void setPaymentSet(Set<Payment> paymentSet) {
this.paymentSet = paymentSet;
}
#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 Game)) {
return false;
}
Game other = (Game) 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 "com.game.database.entity.Game[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "unit")
#NamedQueries({
#NamedQuery(name = "Unit.findAll", query = "SELECT u FROM Unit u"),
#NamedQuery(name = "Unit.findById", query = "SELECT u FROM Unit u WHERE u.id = :id"),
#NamedQuery(name = "Unit.findByUnitId", query = "SELECT u FROM Unit u WHERE u.unitId = :unitId"),
#NamedQuery(name = "Unit.findByName", query = "SELECT u FROM Unit u WHERE u.name = :name"),
#NamedQuery(name = "Unit.findByRegistrationDate", query = "SELECT u FROM Unit u WHERE u.registrationDate = :registrationDate"),
#NamedQuery(name = "Unit.findByService", query = "SELECT u FROM Unit u WHERE u.service = :service"),
#NamedQuery(name = "Unit.findByNation", query = "SELECT u FROM Unit u WHERE u.nation = :nation") })
public class Unit implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "unit_id_seq", sequenceName = "unit_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "unit_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "unitId")
private Integer unitId;
#Basic(optional = false)
#Column(name = "name")
private String name;
#Basic(optional = false)
#Column(name = "registrationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date registrationDate;
#Basic(optional = false)
#Column(name = "service")
private String service;
#Basic(optional = false)
#Column(name = "nation")
private String nation;
#JoinColumn(name = "virtue", referencedColumnName = "id")
#ManyToOne(optional = false)
private Virtue virtue;
#JoinColumn(name = "customer", referencedColumnName = "id")
#ManyToOne(optional = false)
private User customer;
#JoinColumn(name = "game", referencedColumnName = "id")
#ManyToOne(optional = false)
private Game game;
public Unit() {
}
public Unit(Integer id) {
this.id = id;
}
public Unit(Integer unitId, String name, Date registrationDate,
String service, String nation) {
this.unitId = unitId;
this.name = name;
this.registrationDate = registrationDate;
this.service = service;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUnitId() {
return unitId;
}
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public Virtue getVirtue() {
return virtue;
}
public void setVirtue(Virtue virtue) {
this.virtue = virtue;
}
public User getUser() {
return customer;
}
public void setUser(User user) {
this.customer = user;
}
public Game getGame() {
return game;
}
public void setGame(Game game) {
Logger.getLogger("org.hibernate").setLevel(Level.FINEST);
this.game = game;
}
#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 Unit)) {
return false;
}
Unit other = (Unit) 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 "com.game.database.entity.Unit[id=" + id + "]";
}
#Transient
private String command;
/**
* Get the value of command
*
* #return the value of command
*/
public String getCommand() {
return command;
}
/**
* Set the value of command
*
* #param command
* new value of command
*/
public void setCommand(String command) {
this.command = command;
}
#Transient
private String rank;
/**
* Get the value of rank
*
* #return the value of rank
*/
public String getRank() {
return rank;
}
/**
* Set the value of rank
*
* #param rank
* new value of rank
*/
public void setRank(String rank) {
this.rank = rank;
}
#Transient
private BigDecimal price;
/**
* Get the value of price
*
* #return the value of price
*/
public BigDecimal getPrice() {
return price;
}
/**
* Set the value of price
*
* #param price
* new value of price
*/
public void setPrice(BigDecimal price) {
this.price = price;
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "customer")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByGivenName", query = "SELECT u FROM User u WHERE u.givenName = :givenName"),
#NamedQuery(name = "User.findBySurname", query = "SELECT u FROM User u WHERE u.surname = :surname"),
#NamedQuery(name = "User.findByPhoneNumber", query = "SELECT u FROM User u WHERE u.phoneNumber = :phoneNumber"),
#NamedQuery(name = "User.findBySex", query = "SELECT u FROM User u WHERE u.sex = :sex"),
#NamedQuery(name = "User.findByBirthYear", query = "SELECT u FROM User u WHERE u.birthYear = :birthYear"),
#NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email"),
#NamedQuery(name = "User.findByInfoSource", query = "SELECT u FROM User u WHERE u.infoSource = :infoSource"),
#NamedQuery(name = "User.findByOccupation", query = "SELECT u FROM User u WHERE u.occupation = :occupation"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
#NamedQuery(name = "User.findByEmailAndPassword", query = "SELECT u FROM User u WHERE u.password = :password AND u.email = :email") })
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "user_id_seq", sequenceName = "user_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "givenName")
private String givenName;
#Basic(optional = false)
#Column(name = "surname")
private String surname;
#Basic(optional = false)
#Column(name = "phoneNumber")
private String phoneNumber;
#Basic(optional = false)
#Column(name = "sex")
private boolean sex;
#Basic(optional = false)
#Column(name = "birthYear")
#Temporal(TemporalType.DATE)
private Date birthYear;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Basic(optional = false)
#Column(name = "infoSource")
private String infoSource;
#Basic(optional = false)
#Column(name = "occupation")
private String occupation;
#Basic(optional = false)
#Column(name = "password")
private String password;
/**
* The EAGER fetch type ensures that when we get access a unit remotely it
* has had its unit set initialised and populated
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)
private Set<Unit> unitSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)
private Set<Payment> paymentSet;
#JoinColumn(name = "address", referencedColumnName = "id")
#ManyToOne(cascade = CascadeType.ALL, optional = false)
private Address address;
public User() {
}
public User(Integer id) {
this.id = id;
}
public User(String givenName, String surname, String phoneNumber,
boolean sex, Date birthYear, String email, String infoSource,
String occupation, String password) {
this.givenName = givenName;
this.surname = surname;
this.phoneNumber = phoneNumber;
this.sex = sex;
this.birthYear = birthYear;
this.email = email;
this.infoSource = infoSource;
this.occupation = occupation;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public boolean getSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public Date getBirthYear() {
return birthYear;
}
public void setBirthYear(Date birthYear) {
this.birthYear = birthYear;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getInfoSource() {
return infoSource;
}
public void setInfoSource(String infoSource) {
this.infoSource = infoSource;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
public Set<Payment> getPaymentSet() {
return paymentSet;
}
public void setPaymentSet(Set<Payment> paymentSet) {
this.paymentSet = paymentSet;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#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 User)) {
return false;
}
User other = (User) 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 "com.game.database.entity.User[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "virtue")
#NamedQueries({
#NamedQuery(name = "Virtue.findAll", query = "SELECT v FROM Virtue v"),
#NamedQuery(name = "Virtue.findById", query = "SELECT v FROM Virtue v WHERE v.id = :id"),
#NamedQuery(name = "Virtue.findByName", query = "SELECT v FROM Virtue v WHERE v.name = :name"),
#NamedQuery(name = "Virtue.findByDescription", query = "SELECT v FROM Virtue v WHERE v.description = :description") })
public class Virtue implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "virtue_id_seq", sequenceName = "virtue_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "virtue_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#Basic(optional = false)
#Column(name = "description")
private String description;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "virtue")
private Set<Unit> unitSet;
public Virtue() {
}
public Virtue(Integer id) {
this.id = id;
}
public Virtue(String name, String description) {
this.name = name;
this.description = description;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
#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 Virtue)) {
return false;
}
Virtue other = (Virtue) 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 "com.game.database.entity.Virtue[id=" + id + "]";
}
}
You have a problem with the identity of the Unit objects. You're using in your code a HashSet which relies on equals and hashCode methods which are overridden in your code.
If you run the main method in the code below, you will see that after adding the Unit objects there is only one of them in the set (I reused your original code but I simplified it a bit):
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Unit {
private Integer id;
private Integer unitId;
private String name;
private Date registrationDate;
private String service;
private String nation;
public Unit() {
}
public Unit(Integer id) {
this.id = id;
}
public Unit(Integer unitId, String name, Date registrationDate, String service, String nation) {
this.unitId = unitId;
this.name = name;
this.registrationDate = registrationDate;
this.service = service;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUnitId() {
return unitId;
}
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
#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 Unit)) {
return false;
}
Unit other = (Unit) 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 "com.game.database.entity.Unit[id=" + id + "]";
}
public static void main(String... args) {
Unit unit1 = new Unit(1, "Test Unit1", new Date(), "DisService", "MyNation");
Unit unit2 = new Unit(2, "Test Unit2", new Date(), "DisService", "TheirNation");
Unit unit3 = new Unit(3, "Test Unit3", new Date(), "DisService", "TheirNation");
Set unitSet = new HashSet();
unitSet.add(unit2);
unitSet.add(unit1);
unitSet.add(unit3);
System.out.println(unitSet.size());
}
If you comment out the equals() and hashCode() and run the code again you will see three objects in the set.
Your equals() method is based on the id property which is set by hibernate at time the object is being persisted and not at the time of adding to the set. It means that the Unit has always a null id and hashCode = 0 when added to the set. I recommend reading this article: http://community.jboss.org/wiki/EqualsandHashCode
Hope it helps!