org.hibernate.hql.internal.ast.QuerySyntaxException Invalid path - java

I devised category and subcategory form in jsf. When I select any category, subcategory related with this category are shown in dropdown. I have a issue how to write hql file. Category and Subcategory is depended on onetomany and vice versa.
Here is the subcategory dao below.
public List getAllSubCategoriesSelectItemName(String name) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getSessionFactory().openSession();
try {
List<Category> liste = session.createQuery("Select S.SubName from SubCategory S left join SC.category scc where scc.name='"+name+"'").list();
return liste;
} catch (Exception e) {
e.printStackTrace();
}finally {
session.close();
}
return null;
}
#Entity
#Table(name="CATEGORY",schema="DEMO")
public class Category implements Serializable{
#Id
#SequenceGenerator(name="catseq",sequenceName="seqCatSEQ",allocationSize=1)
#GeneratedValue(generator="catseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="NAME")
private String name;
#Column(name="CAT_DESC")
private String catDesc;
#OneToMany(cascade = { CascadeType.PERSIST },mappedBy="category")
private Set<SubCategory> subcategories = new HashSet();
public Category() {
super();
// TODO Auto-generated constructor stub
}
public Category(String name, String catDesc) {
super();
this.name = name;
this.catDesc = catDesc;
}
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 getCatDesc() {
return catDesc;
}
public void setCatDesc(String catDesc) {
this.catDesc = catDesc;
}
public Set<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(Set<SubCategory> subcategories) {
this.subcategories = subcategories;
}
}
package entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="SUBCATEGORY",schema="DEMO")
public class SubCategory implements Serializable{
#Id
#SequenceGenerator(name="subcatseq",sequenceName="seqSubCatSEQ",allocationSize=1)
#GeneratedValue(generator="subcatseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="SUBNAME")
private String SubName;
#Column(name="SUBNAME_DESC")
private String SubNameDes;
#ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
#JoinColumn(name = "CAT_ID")
private Category category;
#ManyToMany(cascade=CascadeType.PERSIST,mappedBy="subcategories")
Set<Product> products = new HashSet<Product>();
public SubCategory() {
super();
// TODO Auto-generated constructor stub
}
public SubCategory(String subName, String subNameDes) {
super();
SubName = subName;
SubNameDes = subNameDes;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSubName() {
return SubName;
}
public void setSubName(String subName) {
SubName = subName;
}
public String getSubNameDes() {
return SubNameDes;
}
public void setSubNameDes(String subNameDes) {
SubNameDes = subNameDes;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}

Select S.SubName from SubCategory S left join SC.category
There is nothing aliased with SC in that query.The only existing alias is S. So SC.category is incorrect.

Related

Adding foreign key and composite primary key in jpa?

I have 3 tables in my database: Professors, Disciplines and Courses.
From Professors and Disciplines to Courses it is many to one relationship.
I have tried to put foreign keys, but it does not work.
Course class:
package com.licenta.ascourses.model;
import java.io.Serializable;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="Courses")
#AssociationOverrides({
#AssociationOverride(name = "pk.discipline",
joinColumns = #JoinColumn(name = "IDDISCIPLINE")),
#AssociationOverride(name = "pk.professor",
joinColumns = #JoinColumn(name = "IDPROFESSOR")) })
public class Course implements Serializable {
private CourseId idCourse=new CourseId();
private int year;
private int semester;
public Course()
{
}
public Course(CourseId idCourse, int idDiscipline, int idProfessor,int year, int semester) {
super();
this.idCourse = idCourse;
this.year = year;
this.semester = semester;
}
#EmbeddedId
public CourseId getIdCourse() {
return idCourse;
}
public void setIdCourse(CourseId idCourse) {
this.idCourse = idCourse;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getSemester() {
return semester;
}
public void setSemester(int semester) {
this.semester = semester;
}
}
CourseId class for composite primary key:
package com.licenta.ascourses.model;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Embeddable
public class CourseId implements Serializable{
#ManyToOne
#JoinColumn(name="IDDISCIPLINE")
private int idDiscipline;
#ManyToOne
#JoinColumn(name="IDPROFESSOR")
private int idProfessor;
private String courseNo;
public int getIdDiscipline() {
return idDiscipline;
}
public void setIdDiscipline(int idDiscipline) {
this.idDiscipline = idDiscipline;
}
public int getIdProfessor() {
return idProfessor;
}
public void setIdProfessor(int idProfessor) {
this.idProfessor = idProfessor;
}
public String getCourseNo() {
return courseNo;
}
public void setCourseNo(String courseNo) {
this.courseNo = courseNo;
}
public boolean equals(Object o) {
return true;
}
public int hashCode() {
return 1;
}
}
Discipline class:
package com.licenta.ascourses.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Disciplines")
public class Discipline implements Serializable {
private int idDiscipline;
#Id
private String name;
private String description;
private int an;
private int semestru;
public Discipline()
{
}
public Discipline(int idDiscipline, String name, String description, int an, int semestru) {
super();
this.idDiscipline = idDiscipline;
this.name = name;
this.description = description;
this.an = an;
this.semestru = semestru;
}
public Discipline(int idDiscipline, String name, String description, int an, int semestru, Set<Course> courses) {
super();
this.idDiscipline = idDiscipline;
this.name = name;
this.description = description;
this.an = an;
this.semestru = semestru;
}
public int getIdDiscipline() {
return idDiscipline;
}
public void setIdDiscipline(int idDiscipline) {
this.idDiscipline = idDiscipline;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAn() {
return an;
}
public void setAn(int an) {
this.an = an;
}
public int getSemestru() {
return semestru;
}
public void setSemestru(int semestru) {
this.semestru = semestru;
}
}
And this is how my Course table is made by Hibernate:
create table Courses (
courseNo varchar2(255 char) not null,
idDiscipline number(10,0) not null,
idProfessor number(10,0) not null,
semester number(10,0) not null,
year number(10,0) not null,
primary key (courseNo, idDiscipline, idProfessor)
)
So, the foreign keys does not appear. Please help me
Try to change this:
#ManyToOne
#JoinColumn(name="IDDISCIPLINE")
private int idDiscipline;
#ManyToOne
#JoinColumn(name="IDPROFESSOR")
private int idProfessor;
private String courseNo;
to this:
#ManyToOne
#JoinColumn(name="idDiscipline")
private Discipline discipline;
#ManyToOne
#JoinColumn(name="idProfessor")
private Professor professor;
private String courseNo;

Use of #OneToMany or #ManyToMany targeting an unmapped class (Category,SubCategory,Product)

I devised Category,SubCategory and Product entities for JSF project and I had an issue about mapping between SubCategory and Product with ManytoMany relation. Here are Category,SubCategory and Products below. How can I solve out this mapping excepiton. Thks.
#Entity
#Table(name="CATEGORY",schema="DEMO")
public class Category implements Serializable{
#Id
#SequenceGenerator(name="catseq",sequenceName="seqCatSEQ",allocationSize=1)
#GeneratedValue(generator="catseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="NAME")
private String name;
#Column(name="CAT_DESC")
private String catDesc;
#OneToMany(cascade = { CascadeType.PERSIST },mappedBy="category")
private Set<SubCategory> subcategories = new HashSet();
public Category() {
super();
// TODO Auto-generated constructor stub
}
public Category(String name, String catDesc) {
super();
this.name = name;
this.catDesc = catDesc;
}
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 getCatDesc() {
return catDesc;
}
public void setCatDesc(String catDesc) {
this.catDesc = catDesc;
}
public Set<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(Set<SubCategory> subcategories) {
this.subcategories = subcategories;
}
}
SubCategory:
package entities;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="SUBCATEGORY",schema="DEMO")
public class SubCategory implements Serializable{
#Id
#SequenceGenerator(name="subcatseq",sequenceName="seqSubCatSEQ",allocationSize=1)
#GeneratedValue(generator="subcatseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="SUBNAME")
private String SubName;
#Column(name="SUBNAME_DESC")
private String SubNameDes;
#ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
#JoinColumn(name = "CAT_ID")
private Category category;
#ManyToMany(cascade=CascadeType.PERSIST,mappedBy="subcategories")
Set<Product> products = new HashSet<Product>();
public SubCategory() {
super();
// TODO Auto-generated constructor stub
}
public SubCategory(String subName, String subNameDes) {
super();
SubName = subName;
SubNameDes = subNameDes;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSubName() {
return SubName;
}
public void setSubName(String subName) {
SubName = subName;
}
public String getSubNameDes() {
return SubNameDes;
}
public void setSubNameDes(String subNameDes) {
SubNameDes = subNameDes;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Product:
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name="PRODUCTS",schema="DEMO")
public class Product implements Serializable{
#Id
#SequenceGenerator(name="proseq",sequenceName="proSEQ",allocationSize=1)
#GeneratedValue(generator="proseq",strategy=GenerationType.SEQUENCE)
#Column(name="ID")
private Integer id;
#Column(name="NAME")
private String productName;
#Column(name="QUANTITY")
private Integer quantity;
#Column(name="PRICE")
private Double price;
#Column(name="PRODUCT_DESC")
private String productDes;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="PRODUCT_SUBCATEGORY",
joinColumns={#JoinColumn(name="PRODUCT_ID")},
inverseJoinColumns={#JoinColumn(name="SUBCATEGORY_ID")}
)
Set<SubCategory> subcategories = new HashSet<SubCategory>();
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(String productName, Integer quantity, Double price, String productDes,
Set<SubCategory> subcategories) {
super();
this.productName = productName;
this.quantity = quantity;
this.price = price;
this.productDes = productDes;
this.subcategories = subcategories;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getProductDes() {
return productDes;
}
public void setProductDes(String productDes) {
this.productDes = productDes;
}
public Set<SubCategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(Set<SubCategory> subcategories) {
this.subcategories = subcategories;
}
}
First mappedby is defined as It refers to the field who owns the relationship, By other meaning mapped by refers to the table class which has the foreign key
So we have two mappedBy that are suspiecous lets take them one by one :
1-
#OneToMany(cascade = { CascadeType.PERSIST },mappedBy="category")
private Set<SubCategory> subcategories = new HashSet();
That means that subcategory table and class owns the relationship field so subcategory table is the one who have the foreign key and from SubCategory class the foreign key name is CAT_ID so this one is OK.
2-
#ManyToMany(cascade=CascadeType.PERSIST,mappedBy="subcategories")
Set<Product> products = new HashSet<Product>();
Ok this one shows that there is a field called subcategories in Product class this one owns the relationship BAM this is not true since this is ManyToMany the owner of the relationship should be a third table exists on database and have to be logically understood by hibernate
So this is the issue mappedBy refers to the the field which is not the owner of the relationship and since the owner is some anonymous entity
this have to be like this :
#ManyToMany(cascade=CascadeType.PERSIST)
#JoinTable(name="PRODUCT_SUBCATEGORY",
joinColumns={#JoinColumn(name="SUBCATEGORY_ID")},
inverseJoinColumns={#JoinColumn(name="PRODUCT_ID")}
Set<Product> products = new HashSet<Product>();
Note Your PRODUCT_SUBCATEGORY table should only have two primary keys and should be primary so that hibernate understands that this is ManyToMany relationship

hql join could not resolve property; use two tables mapping

I have 2 tables prod (goods) with
> id, catid(category), name, price
And cat
> with id, catname.
I wanna select like this in SQL
> select * from cat join prod on cat.id=prod.catid where
> cat.name='catname';
My query is;
Query query = session.createQuery("from prod pr join pr.cat ct with pr.catid=ct.id where ct.name=?");
I have
could not resolve property: cat of: goods.prod [from goods.prod pr
join pr.cat ct with pr.catid=ct.id where ct.name=?]
error
and in indexservice.java i have import goods.cat unused. But why? If i wrote function to use goods.prod that imports goods.cat.
Ok. that was with no mapping. I add this in cat.java
**cat.java**
package goods;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import goods.prod;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="cat")
public class cat implements Serializable {
private Integer id;
#Id #GeneratedValue
#Column(name="id")
#OneToMany
#JoinColumn(name="catid", referencedColumnName="id")
private List<prod> prods;
private static final long serialVersionUID = -4147058093508047162L;
private String Name;
public cat() {
}
public cat(int id, String Name) {
this.id = id;
this.Name = Name;
}
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;
}
}
prod.java
package goods;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import goods.cat;
import java.io.Serializable;
#Entity
#Table(name = "prod")
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name = "catid")
private Long id;
private Integer catid;
private String name;
private Integer price;
public prod() {
}
public prod(Long id, Integer catid, String name, Integer price) {
this.id = id;
this.catid = catid;
this.name = name ;
this.price = price;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
public Integer getcatid() {
return catid;
}
public void setcatid(Integer catid) {
this.catid = catid;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Integer getprice() {
return price;
}
public void setprice(Integer price) {
this.price = price;
}
}
IndexService.java
import goods.prod;
import goods.cat;
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
Query query = session.createQuery("from prod pr join pr.cat ct with pr.catid=ct.id where ct.name=?");
//Query query = session.createQuery("from prod pr join pr.cat ct with pr.catid=ct.id where ct.name=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}
In your prod class (defined in prod.java) you have not mapped a field cat (as object type cat), you have mapped only catId as integer.
So you can't use a join like yours.
You can re-write your query like this:
FROM prod pr, cat ct
WHERE pr.catid = ct.id
AND ct.name = ?
manytoone
another variant
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name = "catid")
#ManyToOne
#JoinColumn(name="cat", referencedColumnName="id")
// private Integer catid;
private Long id;
private cat cat;
private String name;
private Integer price;
#Column(s) not allowed on a #ManyToOne property: goods.prod.id

Join in hibernate with annotaion

I am trying to perform join in hibernate and i am using struts2.
I am working with hibernate using annotaions. Now i am unable to perform join between two tables.My first table is "studentprojects" which contain pid and email.Second table is "initialprojectdetials" which contains pid,name,description... similarly some other fields.I have to get the data of second table by performing join around pid of first table.
For this am using this query:
String hql="from InitialProjectDTO I join I.projectId S where I.projectId=:id";
Query query=session.createQuery(hql);
query.setParameter("id", id);
mail =query.list();
where mail is the arraylist of InitialProjectDTO.
And my InitialProjectDTO is:
package edu.pma.dto;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="initialprojectdetail")
public class InitialProjectDTO {
#Id
#Column(name="projectId")
#OneToMany(cascade=CascadeType.ALL)
#JoinTable(name="studentprojects",joinColumns=#JoinColumn(name="projectId"))
int projectId;
#Column(name="name")
String name;
#Column(name="description")
String description;
#Column(name="technology")
String technology;
#Column(name="guide")
String guide;
#Column(name="duration")
int duration;
#Column(name="status")
String status;
#Column(name="report")
String report;
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
public String getGuide() {
return guide;
}
public void setGuide(String guide) {
this.guide = guide;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
my SudentProjectDTO is:
package edu.pma.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="studentprojects")
public class StudentProjectDTO {
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
#Id
#Column(name="email")
String email;
#Column(name="projectId")
int projectId;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
This is the error which i am getting:
Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: edu.pma.dto.InitialProjectDTO.projectId
Method "execute" failed for object edu.pma.actions.LoginAction#1096a56
File: org/hibernate/cfg/annotations/CollectionBinder.java
You should try to use different models
#Entity
public class InitialProjectDTO {
#OneToMany(mappedBy = "project")
private Collection<StudentProjectDTO> students;
}
#Entity
public class StudentProjectDTO {
#ManyToOne
private InitialProjectDTO project;
}
And with the proper model it shuld be easy to write hql, you might want to look here for examples https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html.
Also I would suggest to look here for example of models. http://viralpatel.net/blogs/hibernate-one-to-many-annotation-tutorial/
See following example might its help to you
#Entity
#Table(name="initialprojectdetail")
public class InitialProjectDTO {
private Integer initialProjectDTOId;
private Set<StudentProjectDTO > studentProjectDTO = new HashSet<StudentProjectDTO >(0);
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "initial_projectDTO_id", unique = true, nullable = false)
public Integer getInitialProjectDTOId() {
return this.initialProjectDTOId;
}
public void setInitialProjectDTOId(Integer initialProjectDTOId) {
this.initialProjectDTOId = initialProjectDTOId;
}
#OneToMany(mappedBy = "studentprojects", cascade = CascadeType.ALL, fetch=FetchType.LAZY)
public Set<StudentProjectDTO> getUserRole() {
return this.studentProjectDTO;
}
public void setUserRole(Set<StudentProjectDTO> studentProjectDTO) {
this.studentProjectDTO = studentProjectDTO;
}
}
#Entity
#Table(name="studentprojects")
public class StudentProjectDTO {
private InitialProjectDTO project;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "initial_projectDTO_id", nullable = false)
public User getProject() {
return this.project;
}
public void setProject(InitialProjectDTO project) {
this.project = project;
}
}
your Query shoud be something like this
String hql="SELECT ip from InitialProjectDTO ip JOIN ip.studentProjectDTO sp WHERE sp.projectId = :id";
Query query=session.createQuery(hql);
query.setParameter("id", id);
mail =query.list();

Mapped Entity null on #OneToOne with #JoinColumn

I get the mapped entity always null but, FetchType.EAGER is set already. I have a Booking entity class that maps to two other entities - Slot and Subscriber. Both the entities are null when I fetch the booking entity
Booking class
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name = "BOOKING")
public class Booking {
public Booking(){
}
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "descr")
private String desc;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "slotid",insertable = false, updatable = false)
private Slot slot;
private Integer slotid;
private Integer subscriberid;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "subscriberid",insertable = false, updatable = false)
private User subscriber;
#Column(name = "created")
#Temporal(TemporalType.TIMESTAMP)
private Date created;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "slotid",referencedColumnName="slotid")
public Slot getSlot() {
return slot;
}
public void setSlot(Slot slot) {
this.slot = slot;
}
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "subscriberid",referencedColumnName="userid")
public User getSubscriber() {
return subscriber;
}
public void setSubscriber(User subscriber) {
this.subscriber = subscriber;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Integer getSlotid() {
return slotid;
}
public void setSlotid(Integer slotid) {
this.slotid = slotid;
}
public Integer getSubscriberid() {
return subscriberid;
}
public void setSubscriberid(Integer subscriberid) {
this.subscriberid = subscriberid;
}
}
Slot class
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name="SLOT")
public class Slot {
public Slot(){
}
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="slotid")
private Integer id;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="ownerid",insertable = false, updatable = false)
private User user;
#Column(name="startdate")
private Date startdate;
#Column(name="enddate")
private Date enddate;
#Column(name="status")
private String status;
private Integer ownerid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false, updatable=false)
#Version
private Date created;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return this.user;
}
public void setUser(User owner) {
this.user = owner;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOwnerid() {
return ownerid;
}
public void setOwnerid(Integer ownerid) {
this.ownerid = ownerid;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
}
Subscriber - User class
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="users")
public class User {
public User(){
}
#Id#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="userid")
private Integer userid = 0;
#Column(name = "name")
private String name;
#Column(name = "mobile")
private String mobile;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "type")
private String userType;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="cityid",insertable = false, updatable = false)
private City city;
private String cityid;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="specialityid",insertable = false, updatable = false)
private Speciality speciality;
private Integer specialityid;
#Column(name="medregno")
private String regno;
#Column(name="refcode")
private String referalcode;
public String getRegno() {
return regno;
}
public void setRegno(String regno) {
this.regno = regno;
}
public String getReferalcode() {
return referalcode;
}
public void setReferalcode(String referalcode) {
this.referalcode = referalcode;
}
#Column(name = "gender")
private String gender;
#Column(name = "active")
private boolean active;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated")
private Date updated;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created")
private Date created;
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userid != other.userid)
return false;
return true;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
public Speciality getSpeciality() {
return speciality;
}
public void setSpeciality(Speciality speciality) {
this.speciality = speciality;
}
public Integer getSpecialityid() {
return specialityid;
}
public void setSpecialityid(Integer specialityid) {
this.specialityid = specialityid;
}
}
booking.getSlot() and booking.getSubscriber() returns null
Please let me know if i miss some configuration while mapping
EDIT1
Added code how the entity is getting loaded
public Booking addBooking(String title,String desc,int slotid,int subscriberid,Session session){
Booking booking = new Booking();
booking.setTitle(title);
booking.setDesc(desc);
booking.setSlotid(slotid);
booking.setSubscriberid(subscriberid);
booking.setCreated(new Date());
Integer bookingid = (Integer) session.save(booking);
session.flush();
Booking bookingEntity = (Booking) session.createQuery("From Booking where id = ?").
setParameter(0, bookingid).list().get(0);
return bookingEntity;
}
I am saving the entity and reloading it.
It's not working because Hibernate is retuning the same instance it has already in its 1st level cache, which doesn't have a reference to any of the 2 other entities.
To fix this, you have to do a session.refresh(booking) rather than executing a query.
In your code :
booking.setSlotid(slotid);
booking.setSubscriberid(subscriberid);
You're just setting Integer values and not objects. Instead of this, try to set objects :
booking.setSlot(new Slot(slotid));
booking.setSubscriber(new Subscriber(subscriberid));
But as #Augusto said, the associations you're having in the session (Slot and Subscriber) are not full objects they contain only their ids. That's why you can't get other fields of these objects.

Categories