I have a category table.In which first 5 are main category and
others are sub category.
I need to fetch the sub categories of first 5 main category so i have found the sql query
SELECT m.category_id,m.category_name AS 'Parent',
e.category_name AS 'Sub'
FROM category e
INNER JOIN category m ON m.category_id = e.parent_category_id
ORDER BY Parent
The query is joining the same table itself.and am getting the result given below
Result
How can i convert the SQL query to HQL and return the data like above image to user in
standard json format ?
FetchSubCategory
import java.io.Serializable;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "category")
public class FetchSubCategory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "category_name")
private String categoryName;
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "parent_category_id")
private FetchSubCategory parent;
#OneToMany(mappedBy = "parent")
private Set<FetchSubCategory> subCategory;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public FetchSubCategory getParent() {
return parent;
}
public void setParent(FetchSubCategory parent) {
this.parent = parent;
}
public Set<FetchSubCategory> getSubCategory() {
return subCategory;
}
public void setSubCategory(Set<FetchSubCategory> subCategory) {
this.subCategory = subCategory;
}
}
Method
public Set<FetchSubCategory> fetchSubCategory() throws SQLException, ClassNotFoundException, IOException {
Set<FetchSubCategory> groupList = null;
try {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("SELECT m.categoryName AS 'Parent', e.categoryName AS 'Sub' FROM FetchSubCategory e INNER JOIN FetchSubCategory m ORDER BY Parent");
groupList = (Set<FetchSubCategory>) query.list();
} catch (Exception e) {
e.printStackTrace();
}
return groupList;
}
Can any one please correct my mistake and tell me how to fetch result like above image?
This stuff will solve your problem
#Entity
#Table(name = "category")
public class FetchSubCategory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "category_name")
private String categoryName;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne
#JsonIgnore
#JoinColumn(name = "parent_category_id")
private FetchSubCategory mainCategory;
#JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)//Avoiding empty json arrays.objects
#OneToMany(mappedBy = "mainCategory", fetch = FetchType.EAGER)
private List<FetchSubCategory> subCategory;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public FetchSubCategory getMainCategory() {
return mainCategory;
}
public void setMainCategory(FetchSubCategory mainCategory) {
this.mainCategory = mainCategory;
}
public List<FetchSubCategory> getSubCategory() {
return subCategory;
}
public void setSubCategory(List<FetchSubCategory> subCategory) {
this.subCategory = subCategory;
}
Get your sub categories
public List<FetchSubCategory> fetchSubCategory() throws SQLException, ClassNotFoundException, IOException {
List<FetchSubCategory> groupList = null;
try {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select distinct e FROM FetchSubCategory e INNER JOIN e.subCategory m ORDER BY m.mainCategory");
groupList = query.list();
} catch (Exception e) {
e.printStackTrace();
}
return groupList;
}
For self join as in your case, below will work for you.
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name = "parent_category_id")
private FetchSubCategory parent;
#OneToMany(mappedBy = "parent")
private Set<FetchSubCategory> subCategory;
FetchSubCategory entity class, we defined two attributes: FetchSubCategory parent and Set<FetchSubCategory> subCategory. Attribute parent is mapped with #ManyToOne annotation and subordinates is mapped with #OneToMany. Also within #OneToMany attribute we defined mappedBy="parent" making parent as the relationship owner and thus which manages the foreign relationship within table.
Also the annotation #JoinColumn is defined on parent making it the relationship owner. #JoinColumn defines the joining column which in our case is parent_category_id.
Related
I have something similar to this:
#Entity
#Table(name = "claim", schema = "test")
public class Claim implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idClaim", unique = true, nullable = false)
private Integer idClaim;
#OneToOne(mappedBy = "claim", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonManagedReference
private ClaimReturnInfo claimReturnInfo;
#Column(name = "notes")
private String notes;
// Getters and setters
}
#Entity
#Table(name = "claim_returninfo", schema = "test")
public class ClaimReturnInfo implements Serializable {
#Id
#Column(name = "Claim_idClaim")
private Integer id;
#MapsId("Claim_idClaim")
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Claim_idClaim")
#JsonBackReference
private Claim claim;
#Column(name = "description")
private String description;
// Getters and setters
}
ClaimReturnInfo Id is not autogenerated because we want to propagate the Id from its parent (Claim). We are not able to do this automatically and we are getting this error: ids for this class must be manually assigned before calling save() when 'cascade' is executed in ClaimReturnInfo .
Is it possible to map Claim Id into ClaimReturnInfo Id or should we do this manually?
Even if we set this ID manually on claimReturnInfo and we can perform updates, we still get this error when trying to create a new Claim:
// POST -> claimRepository.save() -> Error
{
"notes": "Some test notes on a new claim",
"claimReturnInfo": {
"description": "Test description for a new claimReturnInfo"
}
}
In the ServiceImplemetation:
#Override
#Transactional
public Claim save(Claim claim) throws Exception {
if(null != claim.getClaimReturnInfo()) {
claim.getClaimReturnInfo().setId(claim.getIdClaim());
}
Claim claimSaved = claimRepository.save(claim);
return claimSaved;
}
I have tried using the following mappings and from your comments it was apparent that Json object is populated correctly.
I have noticed that the annotation #MapsId is the culprit.If you check the documentation of #MapsId annotation it says
Blockquote
The name of the attribute within the composite key
* to which the relationship attribute corresponds. If not
* supplied, the relationship maps the entity's primary
* key
Blockquote
If you change #MapsId("Claim_idClaim") to #MapsId it will start persisting your entities.
import javax.persistence.*;
#Entity
#Table(name = "CLAIM")
public class Claim {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idClaim", unique = true, nullable = false)
private Long idClaim;
#Column(name = "notes")
private String notes;
#OneToOne(mappedBy = "claim", cascade = CascadeType.ALL, optional = false)
private ClaimReturnInfo claimReturnInfo;
public Long getIdClaim() {
return idClaim;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public ClaimReturnInfo getClaimReturnInfo() {
return claimReturnInfo;
}
public void setClaimReturnInfo(ClaimReturnInfo claimReturnInfo) {
if (claimReturnInfo == null) {
if (this.claimReturnInfo != null) {
this.claimReturnInfo.setClaim(null);
}
} else {
claimReturnInfo.setClaim(this);
}
this.claimReturnInfo = claimReturnInfo;
}
}
package com.hiber.hiberelations;
import javax.persistence.*;
#Entity
#Table(name = "CLAIM_RETURN_INFO")
public class ClaimReturnInfo {
#Id
#Column(name = "Claim_idClaim")
private Long childId;
#Column(name = "DESCRIPTION")
private String description;
#MapsId
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Claim_idClaim")
private Claim claim;
public Long getChildId() {
return childId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Claim getClaim() {
return this.claim;
}
public void setClaim(Claim claim) {
this.claim = claim;
}
}
I'm facing a difficulty in developing a server in Spring (+ Hibernate + JPA) for a project.
The structure of the server (the part of interest in this case) is composed of catalogs composed of products that can have some related feedbacks.
Here I share the 3 entities:
Catalog.java
#Entity
#Data
#Table(name = "catalog")
public class Catalog {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false, unique = true)
private String name;
private String description;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "catalog_user_id", nullable = false)
private User user;
#ManyToMany(cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.REFRESH})
#JoinTable(name = "catalog_product",
joinColumns = {#JoinColumn(name = "catalog_id")},
inverseJoinColumns = {#JoinColumn(name = "product_id")}
)
private List<Product> products;
public Catalog() {}
}
Product.java
#Entity
#Data
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(nullable = false, unique = true)
private String name;
private String description;
#Column(nullable = false, length = 1)
#MapKeyEnumerated(EnumType.ORDINAL)
private Category category;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "product_user_id", nullable = false)
private User user;
public Product() {}
}
Feedback.java
#Entity
#Data
#Table(name = "feedback")
public class Feedback {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "feedback_user_id", nullable = false)
private User user;
#Column(nullable = false, length = 1)
#MapKeyEnumerated(EnumType.ORDINAL)
private Rating rating;
private String text;
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "product_id", nullable = false)
private Product product;
public Feedback() {}
}
The problem occurs when I try to delete some entities. What I want is:
when I delete a catalog also the catalog references in the "catalog_product" join table should be deleted (but the product linked with the catalog should not be deleted);
when I delete a product also the product references in the "catalog_product" join table and the feedbacks related to that product should be deleted;
when I delete a feedback nothing happens.
In the business layer I have this operations:
CatalogServiceImpl.java
#Service
public class CatalogServiceImpl implements CatalogService {
#Autowired
private CatalogDAO catalogDAO;
#Autowired
private ModelMapper mapper;
public CatalogDTO findById(Long id) {
Catalog catalog = catalogDAO.findById(id);
return mapper.map(catalog, CatalogDTO.class);
}
public CatalogDTO findByName(String name) {
Catalog catalog = catalogDAO.findByName(name);
return mapper.map(catalog, CatalogDTO.class);
}
public List<CatalogDTO> findByUserId(Long id) {
List<Catalog> catalogs = catalogDAO.findByUserId(id);
Type listCatalogsType = new TypeToken<List<CatalogDTO>>() {}.getType();
return mapper.map(catalogs, listCatalogsType);
}
public List<CatalogDTO> findAll() {
List<Catalog> catalogs = catalogDAO.findAll();
Type listCatalogsType = new TypeToken<List<CatalogDTO>>() {}.getType();
return mapper.map(catalogs, listCatalogsType);
}
public CatalogDTO createCatalog(CatalogDTO catalogDTO) {
Catalog catalog = mapper.map(catalogDTO, Catalog.class);
Catalog catalogFromDB = catalogDAO.save(catalog);
return mapper.map(catalogFromDB, CatalogDTO.class);
}
public CatalogDTO updateCatalog(CatalogDTO catalogDTO) {
Catalog catalog = mapper.map(catalogDTO, Catalog.class);
Catalog catalogFromDB;
if(catalogDAO.exists(catalog.getId())) {
catalogFromDB = catalogDAO.save(catalog);
} else {
catalogFromDB = null;
}
return mapper.map(catalogFromDB, CatalogDTO.class);
}
public void deleteCatalog(Long id) {
Catalog catalog = catalogDAO.findById(id);
if(catalog != null) {
catalogDAO.delete(catalog.getId());
}
}
}
ProductServiceImpl.java
#Service
public class ProductServiceImpl implements ProductService {
#Autowired
private ProductDAO productDAO;
#Autowired
private ModelMapper mapper;
public ProductDTO findById(Long id) {
Product product = productDAO.findById(id);
return mapper.map(product, ProductDTO.class);
}
public ProductDTO findByName(String name) {
Product product = productDAO.findByName(name);
return mapper.map(product, ProductDTO.class);
}
public ProductDTO findByCategory(Category category) {
Product product = productDAO.findByCategory(category);
return mapper.map(product, ProductDTO.class);
}
public List<ProductDTO> findByUserId(Long id) {
List<Product> products = productDAO.findByUserId(id);
Type listProductsType = new TypeToken<List<ProductDTO>>() {}.getType();
return mapper.map(products, listProductsType);
}
public List<ProductDTO> findAll() {
List<Product> products = productDAO.findAll();
Type listProductsType = new TypeToken<List<ProductDTO>>() {}.getType();
return mapper.map(products, listProductsType);
}
public ProductDTO createProduct(ProductDTO productDTO) {
Product product = mapper.map(productDTO, Product.class);
Product productFromDB = productDAO.save(product);
return mapper.map(productFromDB, ProductDTO.class);
}
public ProductDTO updateProduct(ProductDTO productDTO) {
Product product = mapper.map(productDTO, Product.class);
Product productFromDB;
if(productDAO.exists(product.getId())) {
System.out.println(product.toString());
productFromDB = productDAO.save(product);
} else {
productFromDB = null;
}
return mapper.map(productFromDB, ProductDTO.class);
}
public void deleteProduct(Long id) {
Product product = productDAO.findById(id);
if(product != null) {
productDAO.delete(product.getId());
}
}
}
Now, when I try performing the operations of deletion of catalog or product an error of constraint key fail is triggered. For example trying to delete a product which has a reference in the catalog_product join table:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`e01`.`catalog_product`, CONSTRAINT `FKdx5j7bcx77t7h0hjw6tvoxmp1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`))
I don't understand if there's a way to set the relations between entities to make what I want in an automatic way with Spring, or if I have to remove records with reference manually before the deletion of the catalog/product.
Thanks a lot in advance to everyone!
Luca
Below is my code have one-to-many relation that is between parent and student.
My requirement is:
When I give a student's class_name then respective parents information should be display
If I enter reference id of parent to delete then respective child of that parent should deleted
i have left coding in test classes because i dont know how to write query to get out like example select operation. please let me know and if there is any error in DTO classes
select operation query:
select pt.P_MOBILE,pt.P_EMAIL,st.S_FIRSTNAME,st.REF_ID
from parent_info pt join student_info st on pt.REF_ID = st.REF_ID
where st.S_CLASS_TO_JOIN= ?;
Parent class:
#Table(name = "parent_info")
public class ParentDTO {
#Id
#GenericGenerator(name = "j", strategy = "increment")
#GeneratedValue(generator = "j")
#Column(name = "P_ID")
private int p_id;
#Column(name = "P_NAME")
private String p_name;
#Column(name = "P_PHONE")
private String p_phone;
#Column(name = "P_EMAIL")
private String p_email;
#Column(name = "REF_ID")
private String ref_id;
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="parent_id")
private List<StudentDTO> students;
//getters and setters
}
Student class:
#Table(name = "student_info")
public class StudentDTO {
#Id
#GenericGenerator(name = "j", strategy = "increment")
#GeneratedValue(generator = "j")
#Column(name = "S_ID")
private int s_id;
#Column(name = "S_NAME")
private String s_name;
#Column(name = "S_PHONE")
private String s_phone;
#Column(name = "S_EMAIL")
private String s_email;
#Column(name = "REF_ID")
private String ref_id;
#Column(name = "S_CLASS_NAME")
private String s_class_name;
#ManyToOne
#JoinColumn(name="parent_id")
private ParentDTO parent;
//getters and settrs
}
Test class to select query:
Tried this now: unexpected token: th near line 1, column 90 [select s from com.pradeepdemo.StudentDTO s join fetch s.parent where s.s_class_name = 10th]
public class Test {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
List<StudentDTO> groupList = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createQuery("select s from StudentDTO s join fetch s.parent where s.s_class_name = 10th");
groupList = query.list();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.close();
}
}
}
Test class to delete query:
public class Test {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.close();
}
}
}
You can annotate your model classes with #Entity everything should sort itself out. Hibernate is supposed to work the basic CRUD operations on its own, without having to write HQL.
http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm
Try to read examples on this link to have an idea about how to use HQL:
Hibernate - Query Language & Hibernate Query examples (HQL)
EDIT 1
As you can read in Docs : Forms of join syntax
HQL supports two forms of association joining: implicit and explicit.
Working Code
First Mapping between two entities like below
Parent
#Entity
#Table(name="PARENT")
public class ParentDTO {
#Id
#GeneratedValue
#Column(name="ID")
private Long parentId;
#Column(name="firstname")
private String parentName;
#Column(name="ParentPhone")
private Long parentPhone;
#Column(name="ParentEMail")
private String parentEMail;
#Column(name="ReferenceID")
private String referenceID;
#OneToOne(mappedBy="parent", cascade=CascadeType.ALL)
private Student student;
public ParentDTO() {
}
public ParentDTO(Long parentId, String parentName, Long parentPhone,
String parentEMail, String referenceID, Student student) {
super();
this.parentId = parentId;
this.parentName = parentName;
this.parentPhone = parentPhone;
this.parentEMail = parentEMail;
this.referenceID = referenceID;
this.student = student;
}
//getters and setters
}
Student
#Entity
#Table(name = "STUDENT")
public class StudentDTO {
#Id
#Column(name="ID", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="parent"))
private Long id;
#Column(name = "StudentName")
private String studentName;
#Column(name = "StudentClass")
private int studentClass;
#Column(name = "ReferenceID")
private String referenceID;
#OneToOne
#PrimaryKeyJoinColumn
private ParentDTO parent;
public Student() {
}
public Student(Long id, String studentName, int studentClass,
String referenceID, ParentDTO parent) {
super();
this.id = id;
this.studentName = studentName;
this.studentClass = studentClass;
this.referenceID = referenceID;
this.parent = parent;
}
//getters and setters
}
Select query
public void select()
{
Session session = null;
Transaction tx = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
String hql = "from ParentDTO as p, StudentDTO as s where p.referenceID=s.referenceID and s.referenceID='ReferencID-1'";
List<?> list = session.createQuery(hql).list();
for(int i=0; i<list.size(); i++) {
Object[] row = (Object[]) list.get(i);
ParentDTO parent = (ParentDTO)row[0];
Student student = (Student)row[1];
System.out.println(parent.getParentEMail());
System.out.println(student.getStudentName());
}
tx.commit();
} catch (HibernateException he) {
he.printStackTrace();
tx.rollback();
}
}
I have Class Customer ,User , Customer has property manager of user class
Class Customer {
/** The manager. */
#ManyToOne(optional = false, cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
#JoinColumn(name = "MANAGER")
#JsonSerialize(using = EntitySerializer.class)
#JsonDeserialize(using = UserDeserializer.class)
private User manager;
}
-------------------------------------
Class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = User.TABLE_NAME + "_SEQUENCE")
#SequenceGenerator(name = User.TABLE_NAME + "_SEQUENCE", sequenceName = User.TABLE_NAME + "_SEQ")
#Column(name = FIELD_ID, nullable = false)
#SuppressWarnings("PMD.ShortVariable")
private Integer id;
#Override
public Integer getId() {
return id;
}
#Override
public void setId(final Integer newId) {
//System.out.println("setID");
id = newId;
}
}
Now when i am trying to create criteria
final Criteria criteria = getSession().createCriteria(Customer.class);
criteria.add(Restrictions.ilike("manager", "%"+searchTerm+"%"))
It throwing Error :-
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.User.id
Caused by:
java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.User.id to java.lang.String
**Id field is integer **
Could you please change the following:
final Criteria criteria = getSession().createCriteria(Customer.class); criteria.add(Restrictions.ilike("manager", "%"+searchTerm+"%"))
by the following:
final Criteria criteria = getSession().createCriteria(Customer.class); criteria.add(Restrictions.ilike("manager.name", "%"+searchTerm+"%"))
LIKE clause is applicable to text column only.
this code to used
return this.sessionFactory.getCurrentSession()
.createCriteria(UserTraining.class)
.add(Restrictions.eq("userProfile.userId", userId))
.list();
You used this annotation to error remove
#Table(name="user_training")
#Entity
public class UserTraining {
#Id
#GeneratedValue
#Column(name="id")
private int id;
//Generate getter setter of id
/*
#Column(name="user_id")
private int userId;
*/
#JsonIgnore
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "user_id")
private UserProfile userProfile;
public UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
#OneToOne
#JoinColumn(name = "training_id")
private Training training;
#Column(name="view_count")
private int viewCount;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Training getTraining() {
return training;
}
public void setTraining(Training training) {
this.training = training;
}
public int getViewCount() {
return viewCount;
}
public void setViewCount(int viewCount) {
this.viewCount = viewCount;
}
}
I have two entity class Category and Events.I need to join both the tables and fetch all records which matching the given condition
My sql query for this
SELECT * FROM category c inner join `events` e on e.category_i=c.category_id where c.parent_category_id=1;
How i can convert this sql query to hql and fetch the data ? I tried below but not getting the result ? Am very new to hibernate
Events entity class for hibernate mapping
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
/**
* The persistent class for the user database table.
*
*/
#Entity
#Table(name = "events")
public class Events implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "event_id")
private int eventId;
#Column(name = "event_name")
private String eventName;
#Column(name = "event_description")
private String eventDescription;
#Column(name = "category_i")
private Integer categoryI;
public Integer getCategoryI() {
return categoryI;
}
public void setCategoryI(Integer categoryI) {
this.categoryI = categoryI;
}
#Column(name = "is_trending_event")
private Integer isTrendingEvent;
#Column(name = "image_url")
private String imageUrl;
private Integer status;
#Column(name = "created_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date createdDate;
#Column(name = "last_updated_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date lastUpdatedDate;
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public int getEventId() {
return eventId;
}
public void setEventId(int eventId) {
this.eventId = eventId;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getEventDescription() {
return eventDescription;
}
public void setEventDescription(String eventDescription) {
this.eventDescription = eventDescription;
}
public Integer getIsTrendingEvent() {
return isTrendingEvent;
}
public void setIsTrendingEvent(Integer isTrendingEvent) {
this.isTrendingEvent = isTrendingEvent;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
Category entity
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
/**
* The persistent class for the user database table.
*
*/
#Entity
#Table(name = "category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private int categoryId;
#Column(name = "category_name")
private String categoryName;
#Column(name = "parent_category_id")
private Integer parentCategoryId;
#Column(name = "created_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date createdDate;
#Column(name = "last_updated_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date lastUpdatedDate;
#ManyToOne
#JoinTable(name="events", joinColumns = #JoinColumn(name="category_i"))
private Events events;
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Integer getParentCategoryId() {
return parentCategoryId;
}
public void setParentCategoryId(Integer parentCategoryId) {
this.parentCategoryId = parentCategoryId;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
}
Fetch category method
public List<Object[]> getCategoryList(int id) throws SQLException, ClassNotFoundException, IOException {
List<Object[]> groupList = null;
try {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select e from Category e inner join e.events where e.parentCategoryId=1");
//query.setParameter("id", id);
groupList = query.list();
} catch (Exception e) {
}
return groupList;
}
You need to think in terms of Java objects when using ORM tools.
From your question I think the query that you're trying to write will look something like:
public List<Category> getCategoryList(int id) {
List<Category> groupList;
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("select c from Category c join fetch c.events where c.parentCategory.categoryId = 1");
//query.setParameter("id", id);
groupList = query.list();
return groupList;
}
One of the benefits of using an ORM is that it works out the full join query for you.
For this to work you need to update your class model as follows:
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name = "events")
public class Event implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "event_id")
private int eventId;
#Column(name = "event_name")
private String eventName;
#Column(name = "event_description")
private String eventDescription;
#ManyToOne
#JoinColumn(name = "category_i")
private Category category;
#Column(name = "is_trending_event")
private Integer isTrendingEvent;
#Column(name = "image_url")
private String imageUrl;
private Integer status;
#Column(name = "created_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date createdDate;
#Column(name = "last_updated_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date lastUpdatedDate;
...
}
and
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name = "category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private int categoryId;
#Column(name = "category_name")
private String categoryName;
#ManyToOne
#JoinColumn(name="parent_category_id")
private Category parentCategory;
#Column(name = "created_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date createdDate;
#Column(name = "last_updated_date")
#Temporal(javax.persistence.TemporalType.DATE)
private Date lastUpdatedDate;
#OneToMany(mappedBy="category")
private List<Event> events;
...
}
Hibernate is about mapping objects and the relations, however you are mapping simple id fields.
In your Events class you have the followingL
#Entity
#Table(name = "events")
public class Events implements Serializable {
#Column(name = "category_i")
private Integer categoryI;
}
However it should be a Category instead of an Integer.
#Entity
#Table(name = "events")
public class Events implements Serializable {
#ManyToOne
#Column(name = "category_i")
private Category category;
}
Then in your Category you should add the mappedBy field to the #ManyToOne on the events field and remove the #JoinColumn.
#Entity
#Table(name = "category")
public class Category implements Serializable {
#OneToMany(mappedBy="category")
private Events events;
}
The same applies to the parentCategoryId of the Category class.
Now that you have your mapping corrected you should be able to write the query as you wanted to.
This query should do the job:
from Category as c
inner join c.events as e
where c.parentCategoryId = 1
Plus you seem to have a typo (missing "d" at the end) here:
#JoinColumn(name="category_i"))
Ty this below code
public List<Object[]> getCategoryList(int id) throws SQLException, ClassNotFoundException, IOException {
Session session = sessionFactory.getCurrentSession();
return session.createCriteria(Catagory.class)
.setFetchMode("events", FetchMode.JOIN)
.add(Restrictions.eq("parentCatagoryId", 1))
.list();
}
Hope this stuff works.