I have an ObtainedSkill table as well as a Resource table. There is no column in the Resource table for ObtainedSkill. There are only get/set methods. The ObtainedSkill table has a forien key to a Resource Serial Number.
When I call setObtainedSkill() and then update the Resource with the new ObtainedSkills list, it doesn't update. The Resource's ObtainedSkills are still null.
My question is, how do I go about adding ObtainedSkills to my Resource? Do I have to have another column in the Resource table for ObtainedSkills?
Here's my test class:
public static void main(String[] args) throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("XRM_JPA");
ResourcezManager rm = new ResourcezManager(emf);
Resourcez resource = rm.getNewResourcez();
resource = rm.findResourcezBySerialNumber("2G9933");
for (int i = 0; i < resource.getObtainedSkills().size(); i++) {
if (resource.getObtainedSkills().get(i) != null) {
System.out.println(resource.getObtainedSkills().get(i).toString());
}
}
emf.close();
}
I get a NullPointerException when it tries to execute the System.out.
Here are the relevant entities
Skill Entity
package xrm.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the SKILL database table.
*
*/
#Entity
#NamedQueries({#NamedQuery(name = "getSkillBySkillName", query = "SELECT s FROM Skill s WHERE s.skillName = :skillName"),#NamedQuery(name = "getSkillBySkillDescription", query = "SELECT s FROM Skill s WHERE s.skillDescription = :skillDescription"),
#NamedQuery(name = "getSkillBySkillId", query = "SELECT s FROM Skill s WHERE s.skillId = :skillId"),
#NamedQuery(name = "getSkill", query = "SELECT s FROM Skill s")})
public class Skill implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SKILL_ID")
private int skillId;
#Column(name="SKILL_DESCRIPTION")
private String skillDescription;
#Column(name="SKILL_NAME")
private String skillName;
//bi-directional many-to-one association to ObtainedSkill
#OneToMany(mappedBy="skill")
private List<ObtainedSkill> obtainedSkills;
public Skill() {
}
public int getSkillId() {
return this.skillId;
}
public void setSkillId(int skillId) {
this.skillId = skillId;
}
public String getSkillDescription() {
return this.skillDescription;
}
public void setSkillDescription(String skillDescription) {
this.skillDescription = skillDescription;
}
public String getSkillName() {
return this.skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public List<ObtainedSkill> getObtainedSkills() {
return this.obtainedSkills;
}
public void setObtainedSkills(List<ObtainedSkill> obtainedSkills) {
this.obtainedSkills = obtainedSkills;
}
}
Obtained Skill entity
package xrm.model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the OBTAINED_SKILL database table.
*
*/
#Entity
#Table(name="OBTAINED_SKILL")
#NamedQueries({#NamedQuery(name = "getObtainedSkillBySkill", query = "SELECT o FROM ObtainedSkill o WHERE o.skill.skillId = :skill_skillId"),
#NamedQuery(name = "getObtainedSkillByResourcez", query = "SELECT o FROM ObtainedSkill o WHERE o.resourcez.serialNumber = :resourcez_serialNumber"),
#NamedQuery(name = "getObtainedSkillBySkillLevel", query = "SELECT o FROM ObtainedSkill o WHERE o.skillLevel = :skillLevel"),
#NamedQuery(name = "getObtainedSkillByObtainedSkillId", query = "SELECT o FROM ObtainedSkill o WHERE o.obtainedSkillId = :obtainedSkillId"),
#NamedQuery(name = "getObtainedSkill", query = "SELECT o FROM ObtainedSkill o")})
public class ObtainedSkill implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="OBTAINED_SKILL_ID")
private int obtainedSkillId;
#Column(name="SKILL_LEVEL")
private int skillLevel;
//bi-directional many-to-one association to Resourcez
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="SERIAL_NUMBER")
private Resourcez resourcez;
//bi-directional many-to-one association to Skill
#ManyToOne (cascade=CascadeType.DETACH)
#JoinColumn(name="SKILL_ID")
private Skill skill;
public ObtainedSkill() {
}
public int getObtainedSkillId() {
return this.obtainedSkillId;
}
public void setObtainedSkillId(int obtainedSkillId) {
this.obtainedSkillId = obtainedSkillId;
}
public int getSkillLevel() {
return this.skillLevel;
}
public void setSkillLevel(int skillLevel) {
this.skillLevel = skillLevel;
}
public Resourcez getResourcez() {
return this.resourcez;
}
public void setResourcez(Resourcez resourcez) {
this.resourcez = resourcez;
}
public Skill getSkill() {
return this.skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
}
Resource Entity
package xrm.model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the RESOURCEZ database table.
*
*/
#Entity
#NamedQueries({#NamedQuery(name = "getResourcezByUserInformation", query = "SELECT r FROM Resourcez r WHERE r.userInformation.ibmEmailAddress = :userInformation_ibmEmailAddress"),#NamedQuery(name = "getResourcezBySource", query = "SELECT r FROM Resourcez r WHERE r.source.sourceId = :source_sourceId"),
#NamedQuery(name = "getResourcezByRole", query = "SELECT r FROM Resourcez r WHERE r.role.roleId = :role_roleId"),
#NamedQuery(name = "getResourcezByLocation", query = "SELECT r FROM Resourcez r WHERE r.location.locationId = :location_locationId"),
#NamedQuery(name = "getResourcezByMiddleInitial", query = "SELECT r FROM Resourcez r WHERE r.middleInitial = :middleInitial"),
#NamedQuery(name = "getResourcezByLastName", query = "SELECT r FROM Resourcez r WHERE r.lastName = :lastName"),
#NamedQuery(name = "getResourcezByHireDate", query = "SELECT r FROM Resourcez r WHERE r.hireDate = :hireDate"),
#NamedQuery(name = "getResourcezByFirstName", query = "SELECT r FROM Resourcez r WHERE r.firstName = :firstName"),
#NamedQuery(name = "getResourcezByBirthday", query = "SELECT r FROM Resourcez r WHERE r.birthday = :birthday"),
#NamedQuery(name = "getResourcezBySerialNumber", query = "SELECT r FROM Resourcez r WHERE r.serialNumber = :serialNumber"),
#NamedQuery(name = "getResourcez", query = "SELECT r FROM Resourcez r")})
public class Resourcez implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="SERIAL_NUMBER")
private String serialNumber;
#Temporal( TemporalType.DATE)
private Date birthday;
#Column(name="FIRST_NAME")
private String firstName;
#Temporal( TemporalType.DATE)
#Column(name="HIRE_DATE")
private Date hireDate;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="MIDDLE_INITIAL")
private String middleInitial;
//bi-directional many-to-one association to Assignment
#OneToMany(mappedBy="resourcez", cascade=CascadeType.DETACH)
private List<Assignment> assignments;
//bi-directional many-to-one association to ObtainedCertification
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<ObtainedCertification> obtainedCertifications;
//bi-directional many-to-one association to ObtainedSkill
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<ObtainedSkill> obtainedSkills;
//bi-directional many-to-one association to PhoneNumber
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<PhoneNumber> phoneNumbers;
//bi-directional many-to-one association to PrivilegeRequest
#OneToMany(mappedBy="resourcez", cascade=CascadeType.ALL)
private List<PrivilegeRequest> privilegeRequests;
//bi-directional many-to-one association to Location
#ManyToOne
#JoinColumn(name="LOCATION_ID")
private Location location;
//bi-directional many-to-one association to Role
#ManyToOne
#JoinColumn(name="ROLE_ID")
private Role role;
//bi-directional many-to-one association to Source
#ManyToOne
#JoinColumn(name="SOURCE_ID")
private Source source;
//bi-directional many-to-one association to UserInformation
#ManyToOne
#JoinColumn(name="IBM_EMAIL_ADDRESS")
private UserInformation userInformation;
public Resourcez() {
}
public String getSerialNumber() {
return this.serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public Date getBirthday() {
return this.birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getHireDate() {
return this.hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleInitial() {
return this.middleInitial;
}
public void setMiddleInitial(String middleInitial) {
this.middleInitial = middleInitial;
}
public List<Assignment> getAssignments() {
return this.assignments;
}
public void setAssignments(List<Assignment> assignments) {
this.assignments = assignments;
}
public List<ObtainedCertification> getObtainedCertifications() {
return this.obtainedCertifications;
}
public void setObtainedCertifications(List<ObtainedCertification> obtainedCertifications) {
this.obtainedCertifications = obtainedCertifications;
}
public List<ObtainedSkill> getObtainedSkills() {
return this.obtainedSkills;
}
public void setObtainedSkills(List<ObtainedSkill> obtainedSkills) {
this.obtainedSkills = obtainedSkills;
}
public List<PhoneNumber> getPhoneNumbers() {
return this.phoneNumbers;
}
public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public List<PrivilegeRequest> getPrivilegeRequests() {
return this.privilegeRequests;
}
public void setPrivilegeRequests(List<PrivilegeRequest> privilegeRequests) {
this.privilegeRequests = privilegeRequests;
}
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
public Source getSource() {
return this.source;
}
public void setSource(Source source) {
this.source = source;
}
public UserInformation getUserInformation() {
return this.userInformation;
}
public void setUserInformation(UserInformation userInformation) {
this.userInformation = userInformation;
}
}
Skill Table
Obtained Skill Table
Resource Table
The first field is the Serial Number which is a varchar
The other collapsed fields are also varchars Middle and Last name.
Related
I wanted to use anotations in order to keep the code clean but all I get are headaches.
I know the problem has to do with a column's name with an underscore as: rental_rate. If I used #NamedQuery, it is going to throw an error.
Here are the anotations
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
,#NamedQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
})
The anotation that I am struggling with is:
#NamedQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
it throws this error which I believe it has to do with the underscore in the column's name.
Caused by: org.hibernate.HibernateException: Errors in named queries: Film.prices
After some research I found about #NamedNativeQuery in this question and so I decided to change the anotation to:
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
//,#NamedQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
})
#NamedNativeQueries({
#NamedNativeQuery(name = "Film.prices", query = "SELECT f.rental_rate FROM Film f")
})
but then it would be outside the Entity
Caused by: org.hibernate.MappingException: Unknown entity: java.lang.String
How can I manage this issue?
NOTES
Java 8
Netbeans 11
JPA (Hibernate 4.3.1)
EDIT
Full class file
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
,#NamedQuery(name = "Film.prices", query = "SELECT f.rentalRate FROM Film f")
})
/*#NamedNativeQueries({
#NamedNativeQuery(name = "Film.prices", query = "SELECT f.rentalRate FROM Film f")
})*/
public class Film implements Serializable{
#Id
private int filmId;
private String title;
private String Description;
private String releaseYear;
#NaturalId
private int languageId;
#NaturalId
#Column(nullable=true)
private Integer originalLanguageId;
private int rentalDuration;
private float rentalRate;
private int length;
private float replacementCost;
private String rating;
private String specialFeatures;
private Timestamp lastUpdate;
#ManyToMany(cascade = CascadeType.ALL , fetch = FetchType.EAGER)
#JoinTable(
name = "film_category",
joinColumns = { #JoinColumn(name = "film_id") },
inverseJoinColumns = { #JoinColumn(name = "category_id") }
)
private Set<Category> categories = new HashSet<Category>();
#ManyToMany(cascade = CascadeType.ALL , fetch = FetchType.EAGER)
#JoinTable(
name = "inventory",
joinColumns = { #JoinColumn(name = "film_id") },
inverseJoinColumns = { #JoinColumn(name = "inventory_id") }
)
private List<Store> stores = new ArrayList<Store>();
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public String getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(String releaseYear) {
this.releaseYear = releaseYear;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(int languageId) {
this.languageId = languageId;
}
public int getOriginalLanguageId() {
return originalLanguageId;
}
public void setOriginalLanguageId(int originalLanguageId) {
this.originalLanguageId = originalLanguageId;
}
public int getRentalDuration() {
return rentalDuration;
}
public void setRentalDuration(int rentalDuration) {
this.rentalDuration = rentalDuration;
}
public float getRentalRate() {
return rentalRate;
}
public void setRentalRate(float rentalRate) {
this.rentalRate = rentalRate;
}
public int getLenght() {
return length;
}
public void setLenght(int lenght) {
this.length = lenght;
}
public float getReplacementCost() {
return replacementCost;
}
public void setReplacementCost(float replacementCost) {
this.replacementCost = replacementCost;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getSpecialFeatures() {
return specialFeatures;
}
public void setSpecialFeatures(String specialFeatures) {
this.specialFeatures = specialFeatures;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
public Set<Category> getCategories() {
return this.categories;
}
public List<Store> getStores() {
return stores;
}
public void setStores(List<Store> stores) {
this.stores = stores;
}
#Override
public String toString() {
return "Film{" + "filmId=" + filmId + ", title=" + title + ", Description=" + Description + ", releaseYear=" + releaseYear + ", languageId=" + languageId + ", originalLanguageId=" + originalLanguageId + ", rentalDuration=" + rentalDuration + ", rentalRate=" + rentalRate + ", length=" + length + ", replacementCost=" + replacementCost + ", rating=" + rating + ", specialFeatures=" + specialFeatures + ", lastUpdate=" + lastUpdate + ", categories=" + categories + '}';
}
}
You should test if the attribute in File class is something like rentalRate not rental_rate
So in JPA, we use the attributes' names from the class not the columns' names in Database
Update your entity class and use #Column annotation with the name in the database and you can use any name related to java convention and use it in JPA
Check if your id is auto increment use #GeneratedValue annotation if not like PostgreSQL use this one where name_seq is the sequence name
#SequenceGenerator(name="name_seq",
sequenceName="name_seq",
allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator="name_seq")
, Entity
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int filmId;
#Column(name="title")
private String title;
#Column(name="description")
private String Description;
#Column(name="release_year")
private String releaseYear;
#NaturalId
private int languageId;
#NaturalId
#Column(name="original_languageId", nullable=true)
private Integer originalLanguageId;
#Column(name="rental_duration")
private int rentalDuration;
#Column(name="rental_rate")
private float rentalRate;
#Column(name="length")
private int length;
#Column(name="replacement_cost")
private float replacementCost;
#Column
private String rating;
#Column(name="special_features")
private String specialFeatures;
#Column(name="last_update")
private Timestamp lastUpdate;
Update the query to match the attribute names in the Film class, like this:
#Entity
#Table(name="film")
#NamedQueries({
#NamedQuery(name = "Film.findAll", query = "SELECT f FROM Film f")
,#NamedQuery(name = "Film.findById", query = "SELECT f FROM Film f WHERE f.filmId=:filmId")
,#NamedQuery(name = "Film.ratings", query = "SELECT f.rating FROM Film f")
,#NamedQuery(name = "Film.prices", query = "SELECT f.rentalRate FROM Film f")
})
I'm new to JPA and now study on how to join the two tables by manytoone relation. The entity I get are from Database. I have two tables , named Department and Employee. Many employee is belongs to one Department.
Department
#Entity
#Table(name = "DEPARTMENT")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Department.findAll", query = "SELECT d FROM Department d")
, #NamedQuery(name = "Department.findById", query = "SELECT d FROM Department d WHERE d.id = :id")
, #NamedQuery(name = "Department.findByName", query = "SELECT d FROM Department d WHERE d.name = :name")})
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Column(name = "NAME")
private String name;
#OneToMany(mappedBy = "departmentId")
private Collection<Employee> employeeCollection;
public Department() {
}
public Department(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;
}
#XmlTransient
public Collection<Employee> getEmployeeCollection() {
return employeeCollection;
}
public void setEmployeeCollection(Collection<Employee> employeeCollection) {
this.employeeCollection = employeeCollection;
}
#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 Department)) {
return false;
}
Department other = (Department) 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.Department[ id=" + id + " ]";
}
}
Employee
#Entity
#Table(name = "EMPLOYEE")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e")
, #NamedQuery(name = "Employee.findByEid", query = "SELECT e FROM Employee e WHERE e.eid = :eid")
, #NamedQuery(name = "Employee.findByDeg", query = "SELECT e FROM Employee e WHERE e.deg = :deg")
, #NamedQuery(name = "Employee.findByEname", query = "SELECT e FROM Employee e WHERE e.ename = :ename")
, #NamedQuery(name = "Employee.findBySalary", query = "SELECT e FROM Employee e WHERE e.salary = :salary")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "EID")
private Integer eid;
#Column(name = "DEG")
private String deg;
#Column(name = "ENAME")
private String ename;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "SALARY")
private Double salary;
#JoinColumn(name = "DEPARTMENT", referencedColumnName = "ID")
#ManyToOne
private Department department;
public Employee() {
}
public Employee(Integer eid) {
this.eid = eid;
}
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
public String getDeg() {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public int hashCode() {
int hash = 0;
hash += (eid != null ? eid.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 Employee)) {
return false;
}
Employee other = (Employee) object;
if ((this.eid == null && other.eid != null) || (this.eid != null && !this.eid.equals(other.eid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.Employee[ eid=" + eid + " ]";
}
}
ManyToOne
public class ManyToOne {
public static void main(String[] args) {
EntityManagerFactory emfactory = Persistence.
createEntityManagerFactory("JoinTablePU");
EntityManager entitymanager = emfactory.
createEntityManager();
entitymanager.getTransaction().begin();
//Create Department Entity
Department department = new Department();
department.setName("Development");
//Store Department
entitymanager.persist(department);
//Create Employee1 Entity
Employee employee1 = new Employee();
employee1.setEname("Satish");
employee1.setSalary(45000.0);
employee1.setDeg("Technical Writer");
employee1.setDepartment(department);
//Create Employee2 Entity
Employee employee2 = new Employee();
employee2.setEname("Krishna");
employee2.setSalary(45000.0);
employee2.setDeg("Technical Writer");
employee2.setDepartment(department);
//Create Employee3 Entity
Employee employee3 = new Employee();
employee3.setEname("Masthanvali");
employee3.setSalary(50000.0);
employee3.setDeg("Technical Writer");
employee3.setDepartment(department);
//Store Employees
entitymanager.persist(employee1);
entitymanager.persist(employee2);
entitymanager.persist(employee3);
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
Error
Exception Description: The attribute [employeeCollection] in entity class [class entity.Department] has a mappedBy value of [departmentId] which does not exist in its owning entity class [class entity.Employee]. If the owning entity class is a #MappedSuperclass, this is invalid, and your attribute should reference the correct subclass.
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:107)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at jointable.ManyToOne.main(ManyToOne.java:22)
It should be
#OneToMany(mappedBy = "department")
private Collection<Employee> employeeCollection;
The mappedBy = "department" attribute specifies that
the private Department department; field in Employee owns the
relationship (i.e. contains the foreign key for the query to
find all employees for a department.
Here you can find similar example
mappedBy property is used to denote the inverse field in a bidirectional relationship. It identifies that employeeCollection will get automatically populated when the department entity is retrieved from the DB.
In your case , it should be mappedBy = department
Check this link to find the exact representation of your employee-dept model forming a bidirectional relationship and its elaborate description.
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();
How I can to do this query:
#NamedQuery(name = "Scuser.findFriends", query = "SELECT s FROM Scuser s, friends f WHERE f.firstid = :iduser and s.iduser = f.secondid")
in this class:
#Entity
#Table(name = "scuser")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Scuser.findAll", query = "SELECT s FROM Scuser s"),
#NamedQuery(name = "Scuser.findByIduser", query = "SELECT s FROM Scuser s WHERE s.iduser = :iduser"),
#NamedQuery(name = "Scuser.findByUpassword", query = "SELECT s FROM Scuser s WHERE s.upassword = :upassword"),
#NamedQuery(name = "Scuser.findByUname", query = "SELECT s FROM Scuser s WHERE s.uname = :uname"),
#NamedQuery(name = "Scuser.findByTpoints", query = "SELECT s FROM Scuser s WHERE s.tpoints = :tpoints"),
// #NamedQuery(name = "Scuser.findFriends", query = "SELECT s FROM Scuser s, friends f WHERE f.firstid = :iduser and s.iduser = f.secondid"),
#NamedQuery(name = "Scuser.findByUnameUpassword", query = "SELECT s FROM Scuser s WHERE s.uname = :uname and s.upassword = :upassword")})
public class Scuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 2147483647)
#Column(name = "iduser")
private String iduser;
#Size(max = 200)
#Column(name = "upassword")
private String upassword;
#Size(max = 200)
#Column(name = "uname")
private String uname;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "tpoints")
private Double tpoints;
#JoinTable(name = "friends", joinColumns = {
#JoinColumn(name = "firstid", referencedColumnName = "iduser")}, inverseJoinColumns = {
#JoinColumn(name = "secondid", referencedColumnName = "iduser")})
#ManyToMany
private Collection<Scuser> scuserCollection;
#ManyToMany(mappedBy = "scuserCollection")
private Collection<Scuser> scuserCollection1;
#ManyToMany(mappedBy = "scuserCollection")
private Collection<Beach> beachCollection;
public Scuser() {
}
public Scuser(String iduser) {
this.iduser = iduser;
}
public String getIduser() {
return iduser;
}
public void setIduser(String iduser) {
this.iduser = iduser;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Double getTpoints() {
return tpoints;
}
public void setTpoints(Double tpoints) {
this.tpoints = tpoints;
}
#XmlTransient
public Collection<Scuser> getScuserCollection() {
return scuserCollection;
}
public void setScuserCollection(Collection<Scuser> scuserCollection) {
this.scuserCollection = scuserCollection;
}
#XmlTransient
public Collection<Scuser> getScuserCollection1() {
return scuserCollection1;
}
public void setScuserCollection1(Collection<Scuser> scuserCollection1) {
this.scuserCollection1 = scuserCollection1;
}
#XmlTransient
public Collection<Beach> getBeachCollection() {
return beachCollection;
}
public void setBeachCollection(Collection<Beach> beachCollection) {
this.beachCollection = beachCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (iduser != null ? iduser.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 Scuser)) {
return false;
}
Scuser other = (Scuser) object;
if ((this.iduser == null && other.iduser != null) || (this.iduser != null && !this.iduser.equals(other.iduser))) {
return false;
}
return true;
}
#Override
public String toString() {
return "REST.Scuser[ iduser=" + iduser + " ]";
}
}
If I understand correctly, you have the ID of a user, and you want to get the friends of the user identified by this ID. The easiest way is to do
Scuser user = em.find(User.class, userId);
Collection<Scuser> friends = user.getScuserCollection();
If you want to do it using a JPQL query, you just need
select friend from Scuser user
inner join user.scuserCollection friend
where user.id = :userId
Note that your mapping isn't right: scuserCollection1 and beachCollection are both mapped by the same attribute. You should also choose better names for your associations (like friends for example, instead of scuserCollection).
I have an entity :
#Entity
#DiscriminatorValue("News")
public class News extends TVProduction {
private int audience;
private Collection<Reportage> reportages;
public News() {
super();
setAudience(0);
}
#Column(name = "audience")
public int getAudience() {
return audience;
}
public void setAudience(int audience) {
this.audience = audience;
}
#OneToMany
#JoinTable(name = "Reportages_News",
joinColumns = #JoinColumn(name = "news_id"),
inverseJoinColumns = #JoinColumn(name = "reportage_id")
)
public Collection<Reportage> getReportages() {
return reportages;
}
public void setReportages(Collection<Reportage> reportages) {
this.reportages = reportages;
}
}
And Reportage class looks like this:
#Entity
#Table(name = "Reportage")
public class Reportage {
private Long id;
private String subject;
private int version;
private String content;
private Reporter reporter;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
#ManyToOne
#JoinColumn(name = "reporter_fk")
public Reporter getReporter() {
return reporter;
}
public void setReporter(Reporter reporter) {
this.reporter = reporter;
}
}
What I want is to have only the highest versions of Reportages fetched while fetching News. I tried to annotate Reportage with:
#Loader(namedQuery = "fetchFinal")
#NamedNativeQuery(name = "fetchFinal", query = "SELECT t.* FROM" +
"(SELECT id, subject, max(version) maxVersion, content, reporter" +
"FROM reportage GROUP BY id) x" +
"JOIN reportage t ON x.id = t.id AND x.maxVersion = t.version AND t.id = ?"
)
but It doesn't work, saying:
Initial SessionFactory creation failed.org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported
Any idea how to get it done?
How about:
select * from reportage t where t.version = (select max(t2.version) from reportage t2)
UPDATE:
Have not tried this myself:
#NamedNativeQuery(name = "fetchFinal", query = "SELECT t.* FROM" +
"(SELECT id, subject, max(version) maxVersion, content, reporter" +
"FROM reportage GROUP BY id) x" +
"JOIN reportage t ON x.id = t.id AND x.maxVersion = t.version AND t.id = ?",
resultClass=Reportage.class)
= add Resultclass
UPDATE2
If that doesn't work this certainly will (since I've done this myself); using Criteria:
Criteria crit = getSession().createCriteria(Reportage.class);
DetachedCriteria dc = DetachedCriteria.forClass(Reportage.class);
dc.setProjection(Projections.max("version"));
crit.add(Property.forName("version").eq(dc));
return crit.list();