Fetching data from table using hibernate - java

I am able to persist objects in relational database using hibernate.
please look at following code.
package one;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
#Entity
public class Customer {
#Id
private int customerId;
private String customerName;
private String customerAddress;
private int creditScore;
private int rewardPoints;
public Customer()
{
}
public Customer(int customerId,String customerName,String customerAddress,int creditScore,int rewardsPoints)
{
this.customerId=customerId;
this.customerAddress=customerAddress;
this.creditScore=creditScore;
this.customerName=customerName;
this.rewardPoints=rewardsPoints;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public int getCreditScore() {
return creditScore;
}
public void setCreditScore(int creditScore) {
this.creditScore = creditScore;
}
public int getRewardPoints() {
return rewardPoints;
}
public void setRewardPoints(int rewardPoints) {
this.rewardPoints = rewardPoints;
}
}
Then to save object of this class i used following class. following class creates the object of class Customer and saves that object in database then again retrieves it and prints the CustomerName property of every saved object.
package one;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestCustomer {
public static void main(String args[])
{
Customer cust = new Customer(13,"Sara","Banglore",9000,60);
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(cust);
session.getTransaction().commit();
session.close();
session = factory.openSession();
session.beginTransaction();
List list = session.createQuery("FROM Customer").list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Customer custA = (Customer)iterator.next();
System.out.println("First Name\t"+custA.getCustomerName());
}
session.getTransaction().commit();
session.close();
}
}
I executed above code quite a number of times. code is running fine. it is able to fetch all objects which are saved.
but then i used oracle toad and fired a sql statement as
Insert into Customer(CUSTOMERID,CREDITSCORE,CUSTOMERNAME,REWARDPOINTS,CUSTOMERADDRESS)
VALUES(87,4000,'Saurabh',20,'Kalwa');
record gets stored in the table but when i execute above code, i am not able to fetch this record.
one conclusion i can draw is hibernate only returns persisted objects, but still is there any other way i can get all records ?

Are you sure you have submitted the record after inserting with toad for oracle?(you can open another client and execute a select to make sure it can be fetched from sql client).
If you want to debug, you can enable the sql logging function of hibernate, and then execute the sql which hibernate generates for your query in a sql client to make sure all the records can be fetched correctly.
And some suggestions for using JPA:
Make sure the #Entity has a name value which mapping to your physical table to avoid table mapping confusion.
Use #Column(name="column") for all your fields to mapping to the physical table column to avoid confusion.

Related

Is it possible to invoke methods of entity classes using JPA Criteria API?

package com.surya.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "department")
public class Department {
#Column
#Id
private int dept_id;
#Column
private String dept_name;
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
public String getDept_name() {
return dept_name;
}
public void setDept_name(String dept_name) {
this.dept_name = dept_name;
}
public void sayHelloDepartment() {
System.out.println("Hello Department");
}
}
Is it possible to invoke method sayHelloDepartment() using Criteria API of JPA.
This is a example code and I have a situation where I want to invoke a method inside a entity class from my repository classes using JPA Criteria API.

How internally Hibernate set the generated ID(Primary key) which is in the database into the saved object?

POJO class:
package com.hibernate.POJO;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Entity;
#Entity
#Table(name="Student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private int sId;
#Column(name="NAME")
private String sName;
public Student(){
}
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
}
Test Class:
package com.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.POJO.Student;
public class Client {
public static void main(String[] args) {
Student st=new Student();
st.setsName("Bishal");
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
System.out.println(st.getsId());//Here the O/P is 0
s.save(st);
System.out.println(st.getsId());//Here the O/P is value of Generated ID
s.beginTransaction().commit();
}
}
Console:
0
Hibernate: insert into Student (NAME) values (?)
1
Here my question is that before saving the object we are getting the o/p for System.out.println(st.getsId()); is 0 which is the default value of int. After saving the object into database i.e. s.save(st); returns the generated id of the inserted row. I want to know that after saving how the object i.e. st have the generated id, is hibernate setting the sId value for that object i.e. st? How hibernate gets to know the generated id value which is in the database? Is there any data flow between hibernate and database to get the generated value , if it is then how data flow is happening between Hibernate and Database?

Updating primary key spring boot jpa

i need to update tow columns inside my table (Job this table is joint with two other tables employees and job-history)one of them is the primary key, but i get error, if someone can help!
package com.touati.org.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
#Entity
#Table(name="jobs")
#NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="JOB_ID")
private String jobId;
#Column(name="JOB_TITLE")
private String jobTitle;
#Column(name="MAX_SALARY")
private BigDecimal maxSalary;
#Column(name="MIN_SALARY")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="job")
private List<Employee> employees;
//bi-directional many-to-one association to JobHistory
#OneToMany(mappedBy="job")
private List<JobHistory> jobHistories;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
public List<JobHistory> getJobHistories() {
return this.jobHistories;
}
public void setJobHistories(List<JobHistory> jobHistories) {
this.jobHistories = jobHistories;
}
public JobHistory addJobHistory(JobHistory jobHistory) {
getJobHistories().add(jobHistory);
jobHistory.setJob(this);
return jobHistory;
}
public JobHistory removeJobHistory(JobHistory jobHistory) {
getJobHistories().remove(jobHistory);
jobHistory.setJob(null);
return jobHistory;
}
}
my controller: here when i try to look for all job in the data base it works fine, also if i try to update juste the title of the job it works fine to but in case that i try to set a new primary key for the job table it gives me error here my controller.
package com.touati.org.model;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
#Controller // This means that this class is a Controller
#RequestMapping(path="/project") // This means URL's start with /demo (after Application path)
public class MainController {
#GetMapping(path="/job")
public #ResponseBody Iterable<Job> getAllJob() {
// This returns a JSON or XML with the users
return jobRepository.findAll();
}
#GetMapping(path="/job/{jobId}")
public #ResponseBody String getJob(#PathVariable String jobId) {
Job job = jobRepository.findOne(jobId);
try {
job.setJobTitle("manager");
job.setJobId("test1");
jobRepository.save(job);
}
catch (Exception ex) {
return "Error updating the job: " + ex.toString();
}
return "Job succesfully updated!";
}
i got this error,
Error updating the user: org.springframework.orm.jpa.JpaSystemException: identifier of an instance of com.touati.org.model.Job was altered from test to test1; nested exception is org.hibernate.HibernateException: identifier of an instance of com.touati.org.model.Job was altered from test to test1
Thank you for your help.
Altering the PK of an entity is not permitted - if you really have to do it, you should delete, and recreate it.
Reference (an older question) : JPA Hibernate - changing the primary key of an persisted object

Error in Custome Spring-Jpa

The below query is working fine in mysql.
SELECT * FROM utilization u INNER JOIN sbg s on s.sbg_code=u.sbg_code where u.sbg_code=104
I have written below JPQL query.
#Query("SELECT i FROM Utilization i,i.sbg s where s.sbgCode = :sbgCode")
public ArrayList<Utilization> findUtilization(#Param("sbgCode") int sbgCode);
I am getting below error, please tell how to resolve this error
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: i.sbg is not mapped [SELECT i FROM be.g00glen00b.model.Utilization i,i.sbg s where s.sbgCode = :sbgCode]
Can you please tell me how to write the above sql query to JPQL query?
Please suggest some link to learn JPQL joins because I am new to this.
Below class represents the mapping between two tables
sbg class
#Entity
public class sbg {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int sbgCode;
private String sbgdesc;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="iccode")
#JsonIgnore
private Ic ic;
#OneToMany(mappedBy="sbg1", fetch=FetchType.EAGER)
private List<Utilization> utilization;
public int getSbgCode() {
return sbgCode;
}
public void setSbgCode(int sbgCode) {
this.sbgCode = sbgCode;
}
public String getSbgdesc() {
return sbgdesc;
}
public void setSbgdesc(String sbgdesc) {
this.sbgdesc = sbgdesc;
}
public Ic getIc() {
return ic;
}
public void setIc(Ic ic) {
this.ic = ic;
}
}
utilization class
package be.g00glen00b.model;
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.ManyToOne;
#Entity
public class Utilization {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int asset_type_key;
private String asset_type;
private String Engine_status;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "sbgCode")
private sbg sbg1;
public sbg getSbg1() {
return sbg1;
}
public void setSbg1(sbg sbg1) {
this.sbg1 = sbg1;
}
public int getAsset_type_key() {
return asset_type_key;
}
public void setAsset_type_key(int asset_type_key) {
this.asset_type_key = asset_type_key;
}
public String getAsset_type() {
return asset_type;
}
public void setAsset_type(String asset_type) {
this.asset_type = asset_type;
}
public String getEngine_status() {
return Engine_status;
}
public void setEngine_status(String engine_status) {
Engine_status = engine_status;
}
}
jpa repository
public interface UtilizationRepository extends JpaRepository<Utilization, Integer> {
#Query("SELECT i FROM Utilization i,i.sbg s where s.sbgCode = :sbgCode")
public ArrayList<Utilization> findUtilization(#Param("sbgCode") int sbgCode);
}
You are missing a JOIN in your query.
Your query should look like
SELECT i FROM Utilization i JOIN i.sbg s where s.sbgCode = :sbgCode
When you do queries like this you need to keep in mind that you might get duplicate results back. If you want to get unique results you should use a Set or have a look at this for a way to achieve it with hints and hibernate.

How to save multiple objects via ArrayList in hibernate?

I have a Student entity. My idea is to collect multiple student objects in an ArrayList and save all objects from that list to the database. When do you use #ElementCollection annotation? Does it apply to situations like this?
Student:
package basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public Student(String name) {
this.name = name;
}
}
Runner:
package basic;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Runner {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure("/basic/hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
List<Student> students = new ArrayList<>();
students.add(new Student("Michael"));
students.add(new Student("Dave"));
students.add(new Student("Tom"));
students.add(new Student("Dinesh"));
students.add(new Student("Lakshman"));
students.add(new Student("Cruise"));
session.save(students);
session.getTransaction().commit();
session.close();
}
}
Error
Exception in thread "main" org.hibernate.MappingException: Unknown entity: java.util.ArrayList
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1596)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:668)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:660)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:655)
at basic.Runner.main(Runner.java:27)
You have to do something like this:
for(Student student : students) {
session.save(student);
}
If you want to save entity you should map it. ArrayList<> is not mapped entity. Student has mapping so you should save it separately.
#ElementCollection you should use to define relation between object - here you have nice explenation https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
To save list of object, you need to iterate by objects, something like this -> How to insert multiple rows into database using hibernate?
I would further recommend to use another Hibernate command to avoid an Out Of Memory error...
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
for (int i = 0 ; i < students.size(); i++) {
session.save(students.get(i));
if (i % 100 == 0) {//a batch size for safety
session.flush();
session.clear();
}
}
transaction.commit();
session.close();
sessionFactory.close();

Categories

Resources