Netbeans was kind enough to generate this class for me. But I'm wondering how I save data to the database?
I would think it would be like....
Content $content = new Content();
$content->setName();
$content->save();
But I don't see any save functionality or anything that hints that this content can be saved. I could write queries and such to do so, but with the annotations it created it seems like it has support already built in.
#Entity
#Table(name = "content")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Content.findAll", query = "SELECT c FROM Content c"),
#NamedQuery(name = "Content.findById", query = "SELECT c FROM Content c WHERE c.id = :id"),
#NamedQuery(name = "Content.findByUserId", query = "SELECT c FROM Content c WHERE c.userId = :userId")})
public class Content 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
#Column(name = "user_id")
private int userId;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "body")
private String body;
public Content() {
}
public Content(Integer id) {
this.id = id;
}
public Content(Integer id, int userId, String body) {
this.id = id;
this.userId = userId;
this.body = body;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
#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 Content)) {
return false;
}
Content other = (Content) 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 "model.Content[ id=" + id + " ]";
}
}
Related
I'm trying to display all data objects from the beers table in a list, and in the drill down, to display all beers data with their corresponding category name from the category table and their corresponding style name from the style table, it gets these results from the beer table style id and category id columns.
I've tried using the #SecondaryTables annotation as shown but in the list of beers it only displays 10 beers and that is the number of category names so it is messing up how it is being mapped.
the following is my attempt at doing this.
This is what I have added to the JPA class, what is the correct solution to this.
#Table(name = "beers")
#SecondaryTables({
#SecondaryTable(name = "categories"),
#SecondaryTable(name = "styles")})
#Column(table = "categories", name = "cat_name")
private String catName;
#Column(table = "styles", name = "style_name")
private String styleName;
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
here is a picture of the tables in an ER diagram
here is the beers.java JPA for extra reference
#Entity
#Table(name = "beers")
#SecondaryTables({
#SecondaryTable(name = "categories"),
#SecondaryTable(name = "styles")})
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Beers.findAll", query = "SELECT b FROM Beers b"),
#NamedQuery(name = "Beers.findById", query = "SELECT b FROM Beers b WHERE b.id = :id"),
#NamedQuery(name = "Beers.findByLikeName", query = "SELECT b FROM Beers b WHERE b.name LIKE CONCAT('%',:name,'%')"),
#NamedQuery(name = "Beers.findByBreweryId", query = "SELECT b FROM Beers b WHERE b.breweryId = :breweryId"),
#NamedQuery(name = "Beers.findByName", query = "SELECT b FROM Beers b WHERE b.name = :name"),
#NamedQuery(name = "Beers.findByCatId", query = "SELECT b FROM Beers b WHERE b.catId = :catId"),
#NamedQuery(name = "Beers.findByStyleId", query = "SELECT b FROM Beers b WHERE b.styleId = :styleId"),
#NamedQuery(name = "Beers.findByAbv", query = "SELECT b FROM Beers b WHERE b.abv = :abv"),
#NamedQuery(name = "Beers.findByIbu", query = "SELECT b FROM Beers b WHERE b.ibu = :ibu"),
#NamedQuery(name = "Beers.findBySrm", query = "SELECT b FROM Beers b WHERE b.srm = :srm"),
#NamedQuery(name = "Beers.findByAddUser", query = "SELECT b FROM Beers b WHERE b.addUser = :addUser"),
#NamedQuery(name = "Beers.findByLastMod", query = "SELECT b FROM Beers b WHERE b.lastMod = :lastMod"),
#NamedQuery(name = "Beers.findByBuyPrice", query = "SELECT b FROM Beers b WHERE b.buyPrice = :buyPrice"),
#NamedQuery(name = "Beers.findBySellPrice", query = "SELECT b FROM Beers b WHERE b.sellPrice = :sellPrice")})
public class Beers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "brewery_id")
private int breweryId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Column(name = "cat_id")
private int catId;
#Basic(optional = false)
#NotNull
#Column(name = "style_id")
private int styleId;
#Basic(optional = false)
#NotNull
#Column(name = "abv")
private float abv;
#Basic(optional = false)
#NotNull
#Column(name = "ibu")
private float ibu;
#Basic(optional = false)
#NotNull
#Column(name = "srm")
private float srm;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Column(name = "add_user")
private int addUser;
#Basic(optional = false)
#NotNull
#Column(name = "last_mod")
#Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "image")
private String image;
#Basic(optional = false)
#NotNull
#Column(name = "buy_price")
private double buyPrice;
#Basic(optional = false)
#NotNull
#Column(name = "sell_price")
private double sellPrice;
#Column(table = "categories", name = "cat_name")
private String catName;
#Column(table = "styles", name = "style_name")
private String styleName;
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
public Beers() {
}
public Beers(Integer id) {
this.id = id;
}
public Beers(Integer id, int breweryId, String name, int catId, int styleId, float abv, float ibu, float srm, String description, int addUser, Date lastMod, String image, double buyPrice, double sellPrice, String catName) {
this.id = id;
this.breweryId = breweryId;
this.name = name;
this.catId = catId;
this.styleId = styleId;
this.abv = abv;
this.ibu = ibu;
this.srm = srm;
this.description = description;
this.addUser = addUser;
this.lastMod = lastMod;
this.image = image;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
this.catName = catName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getBreweryId() {
return breweryId;
}
public void setBreweryId(int breweryId) {
this.breweryId = breweryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCatId() {
return catId;
}
public void setCatId(int catId) {
this.catId = catId;
}
public int getStyleId() {
return styleId;
}
public void setStyleId(int styleId) {
this.styleId = styleId;
}
public float getAbv() {
return abv;
}
public void setAbv(float abv) {
this.abv = abv;
}
public float getIbu() {
return ibu;
}
public void setIbu(float ibu) {
this.ibu = ibu;
}
public float getSrm() {
return srm;
}
public void setSrm(float srm) {
this.srm = srm;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAddUser() {
return addUser;
}
public void setAddUser(int addUser) {
this.addUser = addUser;
}
public Date getLastMod() {
return lastMod;
}
public void setLastMod(Date lastMod) {
this.lastMod = lastMod;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getBuyPrice() {
return buyPrice;
}
public void setBuyPrice(double buyPrice) {
this.buyPrice = buyPrice;
}
public double getSellPrice() {
return sellPrice;
}
public void setSellPrice(double sellPrice) {
this.sellPrice = sellPrice;
}
#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 Beers)) {
return false;
}
Beers other = (Beers) 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 "brewery.src.model.Beers[ id=" + id + " ]";
}
}
below is my attempt at using #manytoone annotation
Beers.java
#Entity
#Table(name = "beers")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Beers.findAll", query = "SELECT b FROM Beers b"),
#NamedQuery(name = "Beers.findById", query = "SELECT b FROM Beers b WHERE b.id = :id"),
#NamedQuery(name = "Beers.findByLikeName", query = "SELECT b FROM Beers b WHERE b.name LIKE CONCAT('%',:name,'%')"),
#NamedQuery(name = "Beers.findByBreweryId", query = "SELECT b FROM Beers b WHERE b.breweryId = :breweryId"),
#NamedQuery(name = "Beers.findByName", query = "SELECT b FROM Beers b WHERE b.name = :name"),
#NamedQuery(name = "Beers.findByCatId", query = "SELECT b FROM Beers b WHERE b.catId = :catId"),
#NamedQuery(name = "Beers.findByStyleId", query = "SELECT b FROM Beers b WHERE b.styleId = :styleId"),
#NamedQuery(name = "Beers.findByAbv", query = "SELECT b FROM Beers b WHERE b.abv = :abv"),
#NamedQuery(name = "Beers.findByIbu", query = "SELECT b FROM Beers b WHERE b.ibu = :ibu"),
#NamedQuery(name = "Beers.findBySrm", query = "SELECT b FROM Beers b WHERE b.srm = :srm"),
#NamedQuery(name = "Beers.findByAddUser", query = "SELECT b FROM Beers b WHERE b.addUser = :addUser"),
#NamedQuery(name = "Beers.findByLastMod", query = "SELECT b FROM Beers b WHERE b.lastMod = :lastMod"),
#NamedQuery(name = "Beers.findByBuyPrice", query = "SELECT b FROM Beers b WHERE b.buyPrice = :buyPrice"),
#NamedQuery(name = "Beers.findBySellPrice", query = "SELECT b FROM Beers b WHERE b.sellPrice = :sellPrice")})
public class Beers implements Serializable {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="styleId")
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "brewery_id")
private int breweryId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Column(name = "cat_id")
private int catId;
#Basic(optional = false)
#NotNull
#Column(name = "style_id")
private int styleId;
#Basic(optional = false)
#NotNull
#Column(name = "abv")
private float abv;
#Basic(optional = false)
#NotNull
#Column(name = "ibu")
private float ibu;
#Basic(optional = false)
#NotNull
#Column(name = "srm")
private float srm;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Column(name = "add_user")
private int addUser;
#Basic(optional = false)
#NotNull
#Column(name = "last_mod")
#Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "image")
private String image;
#Basic(optional = false)
#NotNull
#Column(name = "buy_price")
private double buyPrice;
#Basic(optional = false)
#NotNull
#Column(name = "sell_price")
private double sellPrice;
#Column(table = "categories", name = "cat_name")
private String catName;
#Column(table = "styles", name = "style_name")
private String styleName;
public Beers() {
}
public Beers(Integer id) {
this.id = id;
}
public Beers(Integer id, int breweryId, String name, int catId, int styleId, float abv, float ibu, float srm, String description, int addUser, Date lastMod, String image, double buyPrice, double sellPrice) {
this.id = id;
this.breweryId = breweryId;
this.name = name;
this.catId = catId;
this.styleId = styleId;
this.abv = abv;
this.ibu = ibu;
this.srm = srm;
this.description = description;
this.addUser = addUser;
this.lastMod = lastMod;
this.image = image;
this.buyPrice = buyPrice;
this.sellPrice = sellPrice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getBreweryId() {
return breweryId;
}
public void setBreweryId(int breweryId) {
this.breweryId = breweryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCatId() {
return catId;
}
public void setCatId(int catId) {
this.catId = catId;
}
public int getStyleId() {
return styleId;
}
public void setStyleId(int styleId) {
this.styleId = styleId;
}
public float getAbv() {
return abv;
}
public void setAbv(float abv) {
this.abv = abv;
}
public float getIbu() {
return ibu;
}
public void setIbu(float ibu) {
this.ibu = ibu;
}
public float getSrm() {
return srm;
}
public void setSrm(float srm) {
this.srm = srm;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAddUser() {
return addUser;
}
public void setAddUser(int addUser) {
this.addUser = addUser;
}
public Date getLastMod() {
return lastMod;
}
public void setLastMod(Date lastMod) {
this.lastMod = lastMod;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public double getBuyPrice() {
return buyPrice;
}
public void setBuyPrice(double buyPrice) {
this.buyPrice = buyPrice;
}
public double getSellPrice() {
return sellPrice;
}
public void setSellPrice(double sellPrice) {
this.sellPrice = sellPrice;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
#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 Beers)) {
return false;
}
Beers other = (Beers) 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 "brewery.src.model.Beers[ id=" + id + " ]";
}
catgories.java
#Entity
#Table(name = "categories")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Categories.findAll", query = "SELECT c FROM Categories c"),
#NamedQuery(name = "Categories.findById", query = "SELECT c FROM Categories c WHERE c.id = :id"),
#NamedQuery(name = "Categories.findByCatName", query = "SELECT c FROM Categories c WHERE c.catName = :catName"),
#NamedQuery(name = "Categories.findByLastMod", query = "SELECT c FROM Categories c WHERE c.lastMod = :lastMod")})
public class Categories implements Serializable {
#OneToMany(mappedBy = "beer")
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "cat_name")
private String catName;
#Basic(optional = false)
#NotNull
#Column(name = "last_mod")
#Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
public Categories() {
}
public Categories(Integer id) {
this.id = id;
}
public Categories(Integer id, String catName, Date lastMod) {
this.id = id;
this.catName = catName;
this.lastMod = lastMod;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public Date getLastMod() {
return lastMod;
}
public void setLastMod(Date lastMod) {
this.lastMod = lastMod;
}
#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 Categories)) {
return false;
}
Categories other = (Categories) 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 "brewery.src.model.Categories[ id=" + id + " ]";
}
}
styles.java
#Entity
#Table(name = "styles")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Styles.findAll", query = "SELECT s FROM Styles s"),
#NamedQuery(name = "Styles.findById", query = "SELECT s FROM Styles s WHERE s.id = :id"),
#NamedQuery(name = "Styles.findByCatId", query = "SELECT s FROM Styles s WHERE s.catId = :catId"),
#NamedQuery(name = "Styles.findByStyleName", query = "SELECT s FROM Styles s WHERE s.styleName = :styleName"),
#NamedQuery(name = "Styles.findByLastMod", query = "SELECT s FROM Styles s WHERE s.lastMod = :lastMod")})
public class Styles implements Serializable {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="catId")
#OneToMany(mappedBy = "beer")
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "cat_id")
private int catId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "style_name")
private String styleName;
#Basic(optional = false)
#NotNull
#Column(name = "last_mod")
#Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
public Styles() {
}
public Styles(Integer id) {
this.id = id;
}
public Styles(Integer id, int catId, String styleName, Date lastMod) {
this.id = id;
this.catId = catId;
this.styleName = styleName;
this.lastMod = lastMod;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getCatId() {
return catId;
}
public void setCatId(int catId) {
this.catId = catId;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
public Date getLastMod() {
return lastMod;
}
public void setLastMod(Date lastMod) {
this.lastMod = lastMod;
}
#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 Styles)) {
return false;
}
Styles other = (Styles) 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 "brewery.src.model.Styles[ id=" + id + " ]";
}
}
500 error root cause
Exception
org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.ExceptionInInitializerError
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1006)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.ExceptionInInitializerError
brewery.src.controller.beerService.getAllBeers(beerService.java:26)
brewery.src.controller.beerController.getBeers(beerController.java:39)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Root Cause
javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [taste_PU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-93] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The table [categories] is not present in this descriptor.
Descriptor: RelationalDescriptor(brewery.src.model.Beers --> [DatabaseTable(beers)])
Exception [EclipseLink-41] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A non-read-only mapping must be defined for the sequence number field.
Descriptor: RelationalDescriptor(brewery.src.model.Beers --> [DatabaseTable(beers)])
I'm really stuck here and I'd love to get some help right about now.
Everytime I try to deploy, it keeps saying that it failed.
EDIT:
Okay so I've realized that the main issue seems to be:
Caused by: Exception [EclipseLink-7154] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The attribute [productCollection] in entity class [class entity.Category] has a mappedBy value of [category] which does not exist in its owning entity class [class entity.Product]. If the owning entity class is a #MappedSuperclass, this is invalid, and your attribute should reference the correct subclass.
The entity classes are as follows:
Category.java
#Entity
#Table(name = "category")
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
#NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Short id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private Collection<Product> productCollection;
public Category() {
}
public Category(Short id) {
this.id = id;
}
public Category(Short id, String name) {
this.id = id;
this.name = name;
}
public Short getId() {
return id;
}
public void setId(Short id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Product> getProductCollection() {
return productCollection;
}
public void setProductCollection(Collection<Product> productCollection) {
this.productCollection = productCollection;
}
#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 Category)) {
return false;
}
Category other = (Category) 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 "entity.Category[id=" + id + "]";
}
}
Product.java
#Entity
#Table(name = "product")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"),
#NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id"),
#NamedQuery(name = "Product.findByName", query = "SELECT p FROM Product p WHERE p.name = :name"),
#NamedQuery(name = "Product.findByPrice", query = "SELECT p FROM Product p WHERE p.price = :price"),
#NamedQuery(name = "Product.findByDescription", query = "SELECT p FROM Product p WHERE p.description = :description"),
#NamedQuery(name = "Product.findByLastUpdate", query = "SELECT p FROM Product p WHERE p.lastUpdate = :lastUpdate")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "price")
private BigDecimal price;
#Size(max = 255)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Column(name = "last_update")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
#JoinColumn(name = "category_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Category categoryId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<OrderedProduct> orderedProductCollection;
public Product() {
}
public Product(Integer id) {
this.id = id;
}
public Product(Integer id, String name, BigDecimal price, Date lastUpdate) {
this.id = id;
this.name = name;
this.price = price;
this.lastUpdate = lastUpdate;
}
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 BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Category getCategoryId() {
return categoryId;
}
public void setCategoryId(Category categoryId) {
this.categoryId = categoryId;
}
#XmlTransient
public Collection<OrderedProduct> getOrderedProductCollection() {
return orderedProductCollection;
}
public void setOrderedProductCollection(Collection<OrderedProduct> orderedProductCollection) {
this.orderedProductCollection = orderedProductCollection;
}
#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 Product)) {
return false;
}
Product other = (Product) 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 "entity.Product[ id=" + id + " ]";
}
}
Please help me as soon as possible.
Thank you.
I figured out the solution.
All i had to do was change:
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
to
#OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
Because in my Product.java, the category is mentioned as:
public Category getCategoryId() {
return categoryId;
}
I have a java web application using JPA. My problem seems simple but has stumped me for a day now.
I have two tables in my database, Book and Author.
Both input fields in the view for these tables are in the same form.
What's weird is when I update (mrege()) the edited record the book will update but the author does not. I've debugged and followed the author object as far as netbeans will let me and when I merge() my new book record, only the Book table/object are effected.
The Book is a Many-To-One
The Author is a One-To-Many
Controller
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
String action = request.getParameter("action");
if (action != null) {
List<String> values;
try {
values = new ArrayList<>();
switch (action) {
case "save": // Ecompasses Save and Update
Book book = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date;
String bookAuthorID = request.getParameter("authorID");
String bookID = request.getParameter("bookID");
String title = request.getParameter("title");
String userEnteredDate = request.getParameter("datePublished");
Author author = null;
if (bookID.matches("\\d+")) { // Update
book = bookService.find(new Integer(bookID));
book.setTitle(title);
book.setDatePublished(sdf.parse(userEnteredDate));
author = authorService.find(new Integer(bookAuthorID));
author.setAuthorFirstName(request.getParameter("authorFirstName"));
author.setAuthorLastName(request.getParameter("authorLastName"));
book.setAuthorID(author);
bookService.edit(book);
}
}
Author Entity
#Entity
#Table(name = "Author")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Author.findAll", query = "SELECT a FROM Author a"),
#NamedQuery(name = "Author.findByAuthorID", query = "SELECT a FROM Author a WHERE a.authorID = :authorID"),
#NamedQuery(name = "Author.findByAuthorFirstName", query = "SELECT a FROM Author a WHERE a.authorFirstName = :authorFirstName"),
#NamedQuery(name = "Author.findByAuthorLastName", query = "SELECT a FROM Author a WHERE a.authorLastName = :authorLastName")})
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "AuthorID")
private Integer authorID;
#Size(max = 50)
#Column(name = "AuthorFirstName")
private String authorFirstName;
#Size(max = 50)
#Column(name = "AuthorLastName")
private String authorLastName;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "authorID")
private Collection<Book> bookCollection;
public Author() {
}
public Author(Integer authorID) {
this.authorID = authorID;
}
public Integer getAuthorID() {
return authorID;
}
public void setAuthorID(Integer authorID) {
this.authorID = authorID;
}
public String getAuthorFirstName() {
return authorFirstName;
}
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
#XmlTransient
public Collection<Book> getBookCollection() {
return bookCollection;
}
public void setBookCollection(Collection<Book> bookCollection) {
this.bookCollection = bookCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (authorID != null ? authorID.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 Author)) {
return false;
}
Author other = (Author) object;
if ((this.authorID == null && other.authorID != null) || (this.authorID != null && !this.authorID.equals(other.authorID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "edu.wctc.asp.bookwebapp.bookservice.Author[ authorID=" + authorID + " ]";
}
}
Book Entity
#Entity
#Table(name = "Book")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b"),
#NamedQuery(name = "Book.findByBookID", query = "SELECT b FROM Book b WHERE b.bookID = :bookID"),
#NamedQuery(name = "Book.findByTitle", query = "SELECT b FROM Book b WHERE b.title = :title"),
#NamedQuery(name = "Book.findByDatePublished", query = "SELECT b FROM Book b WHERE b.datePublished = :datePublished")})
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "BookID")
private Integer bookID;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "title")
private String title;
#Column(name = "DatePublished")
#Temporal(TemporalType.DATE)
private Date datePublished;
#JoinColumn(name = "AuthorID", referencedColumnName = "AuthorID")
#ManyToOne(optional = false)
private Author authorID;
public Book() {
}
public Book(Integer bookID) {
this.bookID = bookID;
}
public Book(Integer bookID, String title) {
this.bookID = bookID;
this.title = title;
}
public Integer getBookID() {
return bookID;
}
public void setBookID(Integer bookID) {
this.bookID = bookID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDatePublished() {
return datePublished;
}
public void setDatePublished(Date datePublished) {
this.datePublished = datePublished;
}
public Author getAuthorID() {
return authorID;
}
public void setAuthorID(Author authorID) {
this.authorID = authorID;
}
#Override
public int hashCode() {
int hash = 0;
hash += (bookID != null ? bookID.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 Book)) {
return false;
}
Book other = (Book) object;
if ((this.bookID == null && other.bookID != null) || (this.bookID != null && !this.bookID.equals(other.bookID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "edu.wctc.asp.bookwebapp.bookservice.Book[ bookID=" + bookID + " ]";
}
}
Apply CascadeType.MERGE:
#JoinColumn(name = "AuthorID", referencedColumnName = "AuthorID")
#ManyToOne(optional = false, cascade=CascadeType.MERGE)
private Author authorID;
I have a service rest from database generated in netbeans. This creates entity classes for each table .
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll",
query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findById",
query = "SELECT u FROM Users u WHERE u.id = :id"),
#NamedQuery(name = "Users.findByName",
query = "SELECT u FROM Users u WHERE u.name = :name"),
#NamedQuery(name = "Users.findByTelephone",
query = "SELECT u FROM Users u WHERE u.telephone = :telephone"),
#NamedQuery(name = "Users.findByYear",
query = "SELECT u FROM Users u WHERE u.year = :year")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 25)
#Column(name = "name")
private String name;
#Column(name = "telephone")
private Integer telephone;
#Column(name = "year")
private Integer year;
public Users() {
}
public Users(Integer id) {
this.id = id;
}
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 Integer getTelephone() {
return telephone;
}
public void setTelephone(Integer telephone) {
this.telephone = telephone;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
#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 Users)) {
return false;
}
Users other = (Users) 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 "glee.Users[ id=" + id + " ]";
}
How I can query the db with this class from another? ?
For example do a select : select name from bb.users;
and save it in an array eg
Thanks
#NamedQuery(name,query) annotation is used to hard code the Queries
into the Persistence class. You can retrieve the query using the
name attribute specified.
When using hibernate session, you can use getNamedQuery to
get the query.
When used with EntityManager you can use
createNamedQuery.
Both of this will retrieve the query and and you can execute the query with basic query operations.
List Users =
session.getNamedQuery("Users.findById").setParameter("id",
"1").list();
I have a table Post and Post_Image
#Entity
#Table(name = "post")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Post.findAll", query = "SELECT p FROM Post p"),
#NamedQuery(name = "Post.findByPostId", query = "SELECT p FROM Post p WHERE p.postId = :postId"),
#NamedQuery(name = "Post.findByTitle", query = "SELECT p FROM Post p WHERE p.title = :title"),
#NamedQuery(name = "Post.findByCreatedDatetime", query = "SELECT p FROM Post p WHERE p.createdDatetime = :createdDatetime")})
public class Post implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "post_id")
private Integer postId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "content")
private String content;
#Column(name = "created_datetime")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDatetime;
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
#ManyToOne(optional = false)
private User userId;
#JoinColumn(name = "post_type_id", referencedColumnName = "post_type_id")
#ManyToOne(optional = false)
private PostType postTypeId;
public Post() {
Date date = new Date();
this.createdDatetime =new Date(date.getTime());
}
public Post(Integer postId) {
this.postId = postId;
}
public Post(Integer postId, String title, String content) {
this.postId = postId;
this.title = title;
this.content = content;
}
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreatedDatetime() {
return createdDatetime;
}
public void setCreatedDatetime(Date createdDatetime) {
this.createdDatetime = createdDatetime;
}
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public PostType getPostTypeId() {
return postTypeId;
}
public void setPostTypeId(PostType postTypeId) {
this.postTypeId = postTypeId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postId != null ? postId.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 Post)) {
return false;
}
Post other = (Post) object;
if ((this.postId == null && other.postId != null) || (this.postId != null && !this.postId.equals(other.postId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Post[ postId=" + postId + " ]";
}
}
and
#Entity
#Table(name = "post_image")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "PostImage.findAll", query = "SELECT p FROM PostImage p"),
#NamedQuery(name = "PostImage.findByPostImageId", query = "SELECT p FROM PostImage p WHERE p.postImageId = :postImageId"),
#NamedQuery(name = "PostImage.findByPath", query = "SELECT p FROM PostImage p WHERE p.path = :path"),
#NamedQuery(name = "PostImage.findByTitle", query = "SELECT p FROM PostImage p WHERE p.title = :title")})
public class PostImage implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "post_image_id")
private Integer postImageId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "path")
private String path;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 500)
#Column(name = "title")
private String title;
#JoinColumn(name = "post_id", referencedColumnName = "post_id")
#ManyToOne(optional = false)
private Post postId;
public PostImage() {
}
public PostImage(Integer postImageId) {
this.postImageId = postImageId;
}
public PostImage(Integer postImageId, String path, String title) {
this.postImageId = postImageId;
this.path = path;
this.title = title;
}
public Integer getPostImageId() {
return postImageId;
}
public void setPostImageId(Integer postImageId) {
this.postImageId = postImageId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post getPostId() {
return postId;
}
public void setPostId(Post postId) {
this.postId = postId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (postImageId != null ? postImageId.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 PostImage)) {
return false;
}
PostImage other = (PostImage) object;
if ((this.postImageId == null && other.postImageId != null) || (this.postImageId != null && !this.postImageId.equals(other.postImageId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.PostImage[ postImageId=" + postImageId + " ]";
}
}
i want to get collection of images for particular post like
Collection objPostImage = objPost.getPostImageCollection()
but manytoone relationship do not provide this functionality to me how can i convert it to one to many or how can i get Image Collection for a post.?
I am new to java so any help and suggestion will be appreciated
thanx in advance...
You can add a java.util.Set of PostImages in your Post object, and use the Hibernate mapping to provide the relationship. This site has a great example of setting up One to Many relationships.
So, for example, you would want to add something like the following to your Post class:
private Set<PostImage> postImages = new HashSet<PostImage>();
#OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
public Set<PostImage> getPostImages() {
return this.postImages;
}
public void setPostImages(Set<PostImage> postImages) {
this.postImages= postImages;
}
Then, in your PostImage class, add a reference to a Post object:
private Post post;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "POST_ID", nullable = false)
public Stock getPost() {
return this.post;
}
public void setPost(Post post) {
this.post= post;
}
After adding that, you will be able to call the getPostImages() method on your Post object.
Try this:
#Entity
#Table(name = "post")
public class Post
{
//....
#OneToMany(mappedBy = "post")
private Set<PostImage> images;
//....
}
#Entity
#Table(name = "post_image")
public class PostImage
{
//....
#JoinColumn(name = "post_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Post post;
//....
}
The reason why Seth's answer didn't work is because EclipseLink uses fields to access persistence data. (Hibernate uses properties IIRC.) You can specify per class how a JPA provider should access this data.
Using fields:
#Entity
#Access(AccessType.FIELD)
public class SomeEntity
{
#Id
private Long id;
//....
}
Using properties:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
//....
#Id
public Long getId()
{
return id;
}
}
However when using #Access(AccessType.PROPERTY) fields are also used (at least in EclipseLink) so something like this is possible:
#Entity
#Access(AccessType.PROPERTY)
public class SomeEntity
{
private Long id;
#Column(name = "text")
private String someText;
//....
#Id
public Long getId()
{
return id;
}
}