I'm using JavaEE to build a very simple Java full stack app, so I'm using JSF with Prime Faces 6.2 to render an xthml in the frontend and EJB, JPA with Hibernate and postgresql in the backend, however, When I set rowKey="#{person.id}" from a dataTable component from Prime Faces. Next exception is thrown.
"00:13:36,307 ERROR [io.undertow.request] (default task-55) UT005023: Exception handling request to /javaee-app/faces/listPersons.xhtml: javax.servlet.ServletException ... Caused by:java.lang.NullPointerException"
listPersons.xhtml
Prime Faces DataTable Component(opening tag and its attributes)
<p:dataTable id="persons"
value="#{personBean.persons}"
var="person"
editable="true"
rowKey="#{person.id}"
selection="#{personBean.personSelected}"
selectionMode="single">
The exception thrown that appears when trying to render the page is this.
However, if I set rowKey="#{person.name}" or even rowKey="#{person.email}" in stead of rowKey="#{person.id}" the problem disappears and xthml page is rendered correctly.
<p:dataTable id="persons"
value="#{personBean.persons}"
var="person"
editable="true"
rowKey="#{person.name}"
selection="#{personBean.personSelected}"
selectionMode="single">
with rowKey="#{person.name}" or rowKey="#{person.email}" xhtml page is rendered correctly"
Postgresql Database person
MODEL/ENTITY
#Entity
#Table(name = "person")
#NamedQueries({
#NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
#NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p
WHERE p.id = :id")
, #NamedQuery(name = "Person.findByName", query = "SELECT p FROM
Person p WHERE p.name = :person_name")
, #NamedQuery(name = "Person.findByLastname", query = "SELECT p FROM
Person p WHERE p.lastname = :lastname")
, #NamedQuery(name = "Person.findByEmail", query = "SELECT p
FROM Person p WHERE p.email = :email")
, #NamedQuery(name = "Person.findByPhone", query = "SELECT p
FROM Person p WHERE p.phone = :phone")})
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 60)
#Column(name = "person_name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 60)
private String lastname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 60)
private String email;
#Size(max = 60)
private String phone;
#OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
private List<Users> users;
public Person() { }
public Person(Integer id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<Users> getUsers() {
return users;
}
public void setUsers(List<Users> users) {
this.users = users;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof Person)) {
return false;
}
Person other = (Person) 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 "Person [id = " + id + ", name=" + name
+ ", lastName=" + lastname + " email=" + email + ", phone=" + phone + "]";
}
Any idea to solve this problem guys? Thanks in advance
I'm also adding the images of the errors generated in the application server, in my case Wildfly 8.2
picture1 Wildfly 8.2
picture2 Wildfly 8.2
The id is of type Integer:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
Where as the getter returns int:
public int getId() {
return id;
}
Change getId to return Integer.
Related
In the service class, I am adding data to 2 tables from one form submission, it adds the data to the Breweries table fine but when the data goes to the Brewerie_Geocodes table, it duplicates the row. I think my code is pretty logical but I must be forgetting something.
the method in the service class is
public void addAnBreweries(Breweries brewerie) {
EntityManager em = DBUtil.getEMF().createEntityManager();
EntityTransaction trans = em.getTransaction();
Date date = new Date();
brewerie.setLastMod(date);
try {
trans.begin();
em.persist(brewerie);
trans.commit();
BreweriesGeocode bg = new BreweriesGeocode();
bg.setBreweryId((Integer) brewerie.getId());
bg.setLongitude((float)brewerie.getLongitude());
bg.setLatitude((float)brewerie.getLatitude());
trans.begin();
em.persist(bg);
trans.commit();
} catch (Exception ex) {
System.out.println(ex);
} finally {
em.close();
}
}
the data that I am getting in the table is
the code for the Breweries is
#Entity
#Table(name = "breweries")
#SecondaryTable(name = "breweries_geocode")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Breweries.findAll", query = "SELECT b FROM Breweries b"),
#NamedQuery(name = "Breweries.findById", query = "SELECT b FROM Breweries b WHERE b.id = :id"),
#NamedQuery(name = "Breweries.findByName", query = "SELECT b FROM Breweries b WHERE b.name = :name"),
#NamedQuery(name = "Breweries.findByAddress1", query = "SELECT b FROM Breweries b WHERE b.address1 = :address1"),
#NamedQuery(name = "Breweries.findByAddress2", query = "SELECT b FROM Breweries b WHERE b.address2 = :address2"),
#NamedQuery(name = "Breweries.findByCity", query = "SELECT b FROM Breweries b WHERE b.city = :city"),
#NamedQuery(name = "Breweries.findByState", query = "SELECT b FROM Breweries b WHERE b.state = :state"),
#NamedQuery(name = "Breweries.findByCode", query = "SELECT b FROM Breweries b WHERE b.code = :code"),
#NamedQuery(name = "Breweries.findByCountry", query = "SELECT b FROM Breweries b WHERE b.country = :country"),
#NamedQuery(name = "Breweries.findByPhone", query = "SELECT b FROM Breweries b WHERE b.phone = :phone"),
#NamedQuery(name = "Breweries.findByWebsite", query = "SELECT b FROM Breweries b WHERE b.website = :website"),
#NamedQuery(name = "Breweries.findByImage", query = "SELECT b FROM Breweries b WHERE b.image = :image"),
#NamedQuery(name = "Breweries.findByAddUser", query = "SELECT b FROM Breweries b WHERE b.addUser = :addUser"),
#NamedQuery(name = "Breweries.findByLastMod", query = "SELECT b FROM Breweries b WHERE b.lastMod = :lastMod"),
#NamedQuery(name = "Breweries.findByCreditLimit", query = "SELECT b FROM Breweries b WHERE b.creditLimit = :creditLimit"),
#NamedQuery(name = "Breweries.findByEmail", query = "SELECT b FROM Breweries b WHERE b.email = :email")})
public class Breweries 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 = 255)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "address1")
private String address1;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "address2")
private String address2;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "city")
private String city;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "state")
private String state;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 25)
#Column(name = "code")
private String code;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "country")
private String country;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "phone")
private String phone;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "website")
private String website;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "image")
private String image;
#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
#Column(name = "credit_limit")
private double creditLimit;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "email")
private String email;
#Column(table = "breweries_geocode")
private float latitude;
#Column(table = "breweries_geocode")
private float longitude;
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public Breweries() {
}
public Breweries(Integer id) {
this.id = id;
}
public Breweries(Integer id, String name, String address1, String address2, String city, String state, String code, String country, String phone, String website, String image, String description, int addUser, Date lastMod, double creditLimit, String email) {
this.id = id;
this.name = name;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.state = state;
this.code = code;
this.country = country;
this.phone = phone;
this.website = website;
this.image = image;
this.description = description;
this.addUser = addUser;
this.lastMod = lastMod;
this.creditLimit = creditLimit;
this.email = email;
}
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 getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
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 double getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(double creditLimit) {
this.creditLimit = creditLimit;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#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 Breweries)) {
return false;
}
Breweries other = (Breweries) 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 "lit.sd4.model.Breweries[ id=" + id + " ]";
}
}
the code for BreweriesGeocode is
#Entity
#Table(name = "breweries_geocode")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "BreweriesGeocode.findAll", query = "SELECT b FROM BreweriesGeocode b"),
#NamedQuery(name = "BreweriesGeocode.findById", query = "SELECT b FROM BreweriesGeocode b WHERE b.id = :id"),
#NamedQuery(name = "BreweriesGeocode.findByBreweryId", query = "SELECT b FROM BreweriesGeocode b WHERE b.breweryId = :breweryId"),
#NamedQuery(name = "BreweriesGeocode.findByLatitude", query = "SELECT b FROM BreweriesGeocode b WHERE b.latitude = :latitude"),
#NamedQuery(name = "BreweriesGeocode.findByLongitude", query = "SELECT b FROM BreweriesGeocode b WHERE b.longitude = :longitude")})
public class BreweriesGeocode 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
#Column(name = "latitude")
private float latitude;
#Basic(optional = false)
#NotNull
#Column(name = "longitude")
private float longitude;
public BreweriesGeocode() {
}
public BreweriesGeocode(Integer id) {
this.id = id;
}
public BreweriesGeocode(Integer id, int breweryId, float latitude, float longitude) {
this.id = id;
this.breweryId = breweryId;
this.latitude = latitude;
this.longitude = longitude;
}
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 float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
#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 BreweriesGeocode)) {
return false;
}
BreweriesGeocode other = (BreweriesGeocode) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
In your first class Breweries you already define a secondary table.
#Entity
#Table(name = "breweries")
#SecondaryTable(name = "breweries_geocode")
public class Breweries { ... }
Then later in your class you're stating that some fields will be stored into the secondary table, as shown at these lines:
#Column(table = "breweries_geocode")
private float latitude;
#Column(table = "breweries_geocode")
private float longitude;
But you declare another class BreweriesGeocode also as an Entity associated to a table:
#Entity
#Table(name = "breweries_geocode")
public class BreweriesGeocode { ... }
By doing that the EntityManager and JPA2 implementation will assume there are two very different entities. Therefore calling the first persist() will already generate a record in the breweries_geocode table and the second one will also persist a (brand-new) entity to the same table.
I think a valid simple example is well explained here: JPA SecondaryTable Annotation
To make it better you may start by removing the #Entity annotation from the other class or use it as a Delegate. You could also tell the EntityManager (but its a different topic) to retrieve the previously handled entity and update its state (context-based with some caching, etc). In the latest case it would recognize that its the same entity for example and not persist a new one but just update it.
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 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 am using Eclipselink v2.3.3
I am getting this error
Error compiling the query [Credential.updateExistingCredentialNoPW: UPDATE Credential c SET c.active = :active, c.employee.address.streetAddress = :stadd, c.employee.address.city = :city, c.employee.address.province = :prov, c.employee.address.zip = :zip WHERE c.id = :id], line 1, column 46: invalid navigation expression [c.employee], cannot navigate association field [employee] in the SET clause target.
when I try to run my code.
Here are the affected named queries that prevents running my code
#NamedQuery(name = "Credential.updateExistingCredentialNoPW",
query = "UPDATE Credential c "
+ "SET c.active = :active, "
+ "c.employee.address.streetAddress = :stadd, "
+ "c.employee.address.city = :city, "
+ "c.employee.address.province = :prov, "
+ "c.employee.address.zip = :zip "
+ "WHERE c.id = :id"),
#NamedQuery(name = "Credential.updateExistingCredential",
query = "UPDATE Credential c "
+ "SET c.password = :pw, "
+ "c.active = :active, "
+ "c.employee.address.streetAddress = :stadd, "
+ "c.employee.address.city = :city, "
+ "c.employee.address.province = :prov, "
+ "c.employee.address.zip = :zip "
+ "WHERE c.id = :id"),
#NamedQuery(name = "Credential.updateSalary",
query = "UPDATE Credential c "
+ "SET c.employee.salary.value = :val WHERE c.id = :id")
Here is the class where I put all the named queries specified above
public class Credential implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "CRED_GEN", strategy = GenerationType.IDENTITY)
#Column(name = "CREDENTIAL_ID")
private long id;
// unique & not nullabe username
#Column(nullable = false, unique = true)
private String username;
#Column(nullable = false, name = "USER_KEY")
private String password;
#Column(nullable = false)
private boolean active;
#Column(nullable = false)
private int userLevel;
#OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Employee employee;
public Credential() {
}
public Credential(String username, String password, boolean active,
int userLevel, Employee employee) throws NoSuchAlgorithmException {
this.username = username;
this.setPassword(password);
this.active = active;
this.userLevel = userLevel;
this.employee = employee;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getUserLevel() {
return userLevel;
}
public void setUserLevel(int userLevel) {
this.userLevel = userLevel;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public String getPassword() {
return password;
}
public void setPassword(String password) throws NoSuchAlgorithmException {
this.password = Cryptography.getHash(password);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
Am I doing it wrong?
It is not possible to update multiple tables with single sql query.
See https://forums.oracle.com/forums/thread.jspa?threadID=2223393.
So it's also not possible with Eclipselink.
You'll have to split this it two queries, or better use setters.
You can't. Either use a SQL query, or use Java code:
Credential c = em.find(Credential.class, credentialId);
c.setActive(active);
c.getEmployee().getAddress().setStreet(street);
...
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 + " ]";
}
}