Hibernate: Switched HQL query to SQL query, throws exception: java.lang.ClassCastException - java

In My DaoImpl class I am trying to fetch list of data of Type TBatchEntry(model class)
#Override
public List<TBatchEntry> getBatchListFormQuery(String batchNo) {
session = sessionFactory.openSession();
List<TBatchEntry> batchListFromQuery = new ArrayList<TBatchEntry>();
try {
tx = session.beginTransaction();
batchListFromQuery = session.createSQLQuery("SELECT * FROM pghms.t_batchentry WHERE t_regNo LIKE '2008%'").list();
tx .commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
return batchListFromQuery;
}
In my Controller class I am trying to print value but it is throwing error in commented line:
List<TBatchEntry> batchListFromQuery = new ArrayList<TBatchEntry>();
try{
batchListFromQuery = adminService.getBatchListFormQuery(batchNo);
}catch(Exception e){
e.printStackTrace();
}
Iterator its = batchListFromQuery.iterator();
while(its.hasNext()){
batchFromQuery = (TBatchEntry) its.next(); //This line thorws error
System.out.println(batchFromQuery.getName());
}
This is my entity class
#Entity
#Table(name="t_batchEntry")
public class TBatchEntry {
#Id
#Column(name="t_regNo")
private String regNo;
#Column(name="t_name")
private String name;
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
log of tomcat`root cause
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.sv.pghms.model.TBatchEntry
I'd be really thankful, if somebody could help me.

Try this way just change class name and where condition.It is working for me.
Hope so it will work for you.
List<Book> books = this.sf.getCurrentSession().createSQLQuery("select * from Book where book_id > 3")
.addEntity(Book.class)
.list();
for (Book book : books) {
System.out.println("Book Names are :: " + book.getBookName());
}

Why you are catching TBatchEntry into Object class.You can directly catch into TBatchEntry class.
Change Object[] into TBatchEntry Class, because you are selecting all columns from TBatchEntry table right, try below code i think it will work,
1) From Controller,
List batchListFromQuery = new ArrayList<>();
use foreach loop for displaying records
change return type as below :
#Override
public List<TBatchEntry> getBatchListFormQuery(String batchNo) {
session = sessionFactory.openSession();
List<TBatchEntry> batchListFromQuery = new ArrayList<>();
try {
tx = session.beginTransaction();
batchListFromQuery = session.createSQLQuery("SELECT * FROM pghms.t_batchentry WHERE t_regNo LIKE '2008%'").list();
tx .commit();
}catch(Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
}
return batchListFromQuery;
}

After some study I understood the difference between HQL & SQL query in hibernate.
List<TBatchEntry> batchListFromQuery = new ArrayList<TBatchEntry>();
In case of using HQL query:
batchListFromQuery = session.createQuery(sql).list()
In case of using SQL query:
batchListFromQuery = session.createSQLQuery(sql).addEntity(TBatchEntry.class).list();
Difference is:
.addEntity(TBatchEntry.class)

Related

Hibernate: Not able to update to a new value if some value is present for a field

I'm not able to update the field value to a new value if there is already a value present. Otherwise, if no value is present update is working fine.
Is there anything we need to perform additional to execute an update if there is some value present for the field. And I'm not seeing any error as well.
I'm using Hibernate 5.1 and PostgreSQL
EntityClass
#Setter
#ToString
#Builder(toBuilder = true)
#Getter
#Entity
#NoArgsConstructor(access = AccessLevel.PACKAGE)
#AllArgsConstructor(access = AccessLevel.PACKAGE)
#Table(name = "TableA")
public class TableA {
#Id
#Column(name = "id")
private String id;
#Column(name = "columnA")
private String columnA;
#Column(name = "created_date")
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar createdDate;
#Column(name = "updated_date")
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar updatedDate;
#Column(name = "columnB")
private java.util.Calendar columnB;
#Column(name = "columC")
private String columC;
}
Batch Update method:
public void updateBatchTableAData(List<TableA> tableAList) {
Session session = sessionFactory.openSession();
try {
log.info("Executing batch source Data");
Transaction transaction = session.beginTransaction();
IntStream.range(0, tableAList.size())
.filter(index -> tableAList.get(index) != null)
.forEach(index -> {
session.update(tableAList.get(index));
if (index % 100 == 0) {
session.flush();
session.clear();
}
});
session.flush();
session.clear();
transaction.commit();
} catch (Exception e) {
log.error(
"Exception occurred while saving Batch TableA Data to the DB.", e);
}
session.close();
}
Fetch content Method
public List getTableAData() {
Session session = sessionFactory.openSession();
try {
Criteria criteria = session.createCriteria(TableA.class);
return criteria.list();
} catch (Exception e) {
throw new RuntimeException("Exception occurred while trying to fetch TableA data", e);
}
}
update method
public void executeMethod(){
List<TableA> tableAList = new ArrayList();
getTableAData().forEach(data -> {
TableA tableA = (TableA) data;
tableA.setColumnB(null);
tableA.setColumnC("newmodified_value");
tableAList.add(tableA);
});
updateBatchTableAData(tableAList);
}
SessionFactory
#Provides
#Singleton
public SessionFactory getPostgresqlSessionFactory() {
Configuration configuration = new Configuration();
configuration.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, CURRENT_SESSION_PROPERTY_VALUE);
configuration.setProperty(Environment.DRIVER, SetupConstants.POSTGRES_DRIVER);
configuration.setProperty(Environment.URL,
getDbURL());
configuration.setProperty(Environment.USER, getUsername());
configuration.setProperty(Environment.PASS, getPassword());
configuration.setProperty(Environment.RELEASE_CONNECTIONS, RELEASE_CONNECTIONS_VALUE);
configuration.setProperty(Environment.DIALECT, POSTGRESQL_DIALECT);
configuration.setProperty(Environment.SHOW_SQL, SHOW_SQL_VALUE);
configuration.setProperty(Environment.HBM2DDL_AUTO, HBM2DDL_AUTO_VALUE);
configuration.setProperty(Environment.AUTOCOMMIT, "true");
configuration.setProperty(Environment.STATEMENT_BATCH_SIZE, String.valueOf(BATCH_SIZE));
configuration.setProperty(Environment.ORDER_INSERTS, ORDER_INSERTS_VALUE);
configuration.setProperty(Environment.ORDER_UPDATES, "true");
configuration.setProperty(Environment.BATCH_VERSIONED_DATA, "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
Reflections entityPackageReflections = new Reflections("PACKAGE_NAME");
entityPackageReflections.getTypesAnnotatedWith(Entity.class).forEach(metadataSources::addAnnotatedClass);
Metadata metadata = metadataSources.getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
}
Very unclear calling flow at a question.
My suggestion next time just describe exactly step by step what are you calling at your application.
It looks like you wrote it at reverse order.
For now, I see some silly mistakes at code.
It is difficult to understand if it is a reason to fail. However, you could try it and see the result.
First place:
public List<TableA> getTableAData() {
List<TableA> list = new ArrayLsit<>();
Session session = sessionFactory.openSession();
try {
Criteria criteria = session.createCriteria(TableA.class);
list = criteria.list();
} catch (Exception e) {
throw new RuntimeException("Exception occurred while trying to fetch TableA data", e);
} finally {
if (session.isOpen()) {
session.close();
}
}
return list;
}
Second place:
You don't need to call session.flush() if you will call commit for a transaction later. transactoin.commit() will do it automatically.
I couldn't understand why the following check has done: index % 100?
If it is mandatory please write a comment about why it should be used there.
Also, no idea why do you use IntRange class for iterating through a list? You don't use any methods from IntRange. You can use a stream for iterating through the list.
Much better will be replacing update() with saveOrUpdate(). It should be more logical with functionality which you want to provide -> if no appropriate entity found just save it. Otherwise, update it.
public void updateBatchTableAData(List<TableA> tableAList) {
Session session = sessionFactory.openSession();
try {
log.info("Executing batch source Data");
session.beginTransaction();
tableAList.stream()
.filter(Objects::nonNull)
.forEach(element -> session.saveOrUpdate(element));
session.getTransaction.commit();
} catch (Exception e) {
log.error("Exception occurred while saving Batch TableA Data to the DB.", e);
session.getTransaction().rollback();
} finally {
if (session.isOpen()) {
session.close();
}
}
}
Third place:
Difficult to understand your flow from your code snippets. If I understood from your question that you have a problem when your entity has already set any value.
You could check if this element has already any item or saved to DB. If yes you can use org.springframework.beans.BeanUtils.copyProperties(source, target).
After updating data save it back to DB.

How to fetch data from two tables in hibernate with spring rest api and return in single object to url

I am using Spring restful api with hibernate. And am fetching data from two tables using two entity classes named Employee and Second. I want to get the result in a list from both tables and want to return that in a single json object.
Here is my DAO class
// Method to get the result from employee table
#SuppressWarnings("unchecked")
public List<Employee> getEntityList() throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
List<Employee> employeeList = session.createCriteria(Employee.class)
.list();
tx.commit();
session.close();
return employeeList;
}
// Method to get the result from second table
#SuppressWarnings("unchecked")
public List<Second> getSecondList() throws Exception {
session = sessionFactory.openSession();
tx = session.beginTransaction();
List<Second> secondList = session.createCriteria(Second.class)
.list();
tx.commit();
session.close();
return secondList;
}
My service class
#Autowired
DataDao dataDao;
public List<Employee> getEntityList() throws Exception {
return dataDao.getEntityList();
}
public List<Second> getSecondList() throws Exception {
return dataDao.getSecondList();
}
Here is my RestController
#RequestMapping(value = "/list", method = RequestMethod.GET)
public #ResponseBody
List<Employee> getEmployee() {
List<Employee> employeeList = null;
try {
employeeList = dataServices.getEntityList();
} catch (Exception e) {
e.printStackTrace();
}
return employeeList;
}
Here the data is coming from only one table employee but i want to get data from second table too and want to return that data in employeeList. W
What should i do please suggest me.
Thanx in advance
I think you probably need this kind of example
#RestController
public class EmployeeRestController {
#RequestMapping(value = "/employees")
public Wrapper getEmployees() {
Wrapper wrapper = getWrapper();
return wrapper;
}
public Wrapper getWrapper() {
Wrapper wrapper = new Wrapper();
List<Employee> employees = getEmployee();
List<Organizations> organizations = getOrg();
wrapper.setEmployees(employees);
wrapper.setOrganizations(organizations);
return wrapper;
}
public List<Employee> getEmployee() {
Employee employee1 = new Employee(101, "abc", "abc", "SE");
Employee employee2 = new Employee(102, "def", "def", "SE");
Employee employee3 = new Employee(103, "xyz", "xyz", "SE");
List<Employee> employees = new ArrayList<Employee>();
employees.add(employee1);
employees.add(employee2);
employees.add(employee3);
return employees;
}
public List<Organizations> getOrg() {
Organizations organizations1 = new Organizations();
organizations1.setName("Google");
Organizations organizations2 = new Organizations();
organizations2.setName("Facebook");
Organizations organizations3 = new Organizations();
organizations3.setName("Apple");
List<Organizations> organizations = new ArrayList<Organizations>();
organizations.add(organizations1);
organizations.add(organizations2);
organizations.add(organizations3);
return organizations;
}
}
public class Wrapper {
private List<Employee> employees;
private List<Organizations> organizations;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public List<Organizations> getOrganizations() {
return organizations;
}
public void setOrganizations(List<Organizations> organizations) {
this.organizations = organizations;
}
}
Here Organization and Employee are two bean classes which are set into the wrapper classes.
So in your case, you get those two different object from two table and wrap them up in one Wrapper class and send it back.
I hope this might help you!!
#java developer.
The issue is you cannot collect queries output as a single fetch. You need to create a separate value object class which map to results from both the queries iteratively.
Then you need to map this value object class as a return type for spring rest API. The sample example is shown below:
The client class is composing profile and adviser from two different tables.
Also please take note how parseClientSpreadsheet method is setting clientprofiles and clientadvisors.
public class Client extends ReportModel {
private static final long serialVersionUID = 2292996835674522338L;
private ClientProfile profile;
private List<Advisor> advisor;
public ClientProfile getProfile() {
return profile;
}
public void setProfile(ClientProfile profile) {
this.profile = profile;
}
public List<Advisor> getAdvisor() {
return advisor;
}
public void setAdvisor(List<Advisor> advisor) {
this.advisor = advisor;
}
}
#RequestMapping(method = RequestMethod.GET, value = "/list")
public List<Client> getClients() {
List<Client> clients;
// Call the client service and load client data from the database and
// return the list of clients.
try {
clients = clientService.getClients();
} catch (Exception e) {
file_error_logger.error("Exception while reading clients", e);
throw e;
}
if (logger.isDebugEnabled()) logger.debug("Get client details successful.");
return clients;
}
public List<Client> parseClientSpreadsheet(String clientDetailsFilePath,
int numberOfSheets) throws ClientDataNotFoundException {
List<Client> clientList = new ArrayList<Client>();
// if the row is valid, parse the data
if (isValidRow(row, lastColumn,
ClientDataConstants.CLIENT_REQUIRED_COLUMNS)) {
ClientProfile clientProfile;
List<Advisor> advisorList = new ArrayList<Advisor>();
Client client = new Client();
// Set client profile object values
clientProfile = setClientProfileObject(row);
// set Advisor list
advisorList = setAdvisorList(row, lastColumn);
// set Client object
String[] additionalRecipients = row
.getCell(
Integer.parseInt(reportMailerConfigurationService
.getPropertyValue(ClientDataConstants.ADDITIONAL_RECIPIENTS_CELLNUMBER)))
.toString().split(";");
List<String> additionalRecipientsList = new ArrayList<String>();
// max 4 additional recipients are allowed. So if more are
// found, take 4 in array and ignore the rest
for (int i = 0; i < additionalRecipients.length; i++) {
if (!additionalRecipients[i].isEmpty()) {
additionalRecipientsList.add(additionalRecipients[i]);
if (additionalRecipientsList.size() == 4) {
break;
}
}
}
client.setProfile(clientProfile);
client.setAdvisor(advisorList);
client.setadditional_recipients(additionalRecipientsList);
// add the client in the collection
clientList.add(client);
}
}
return clientList;
}

Hibernate not save Entity to oracle db

I made a small crud app using struts2,spring,hibernate with oracle db.
action class add methos is this.
public String addorgs() throws Exception {
t.setAO_CreatedBy("me");
t.setAO_Name("ok");
orgdao.addOrg(t);
// emplist = empdao.showEmployuee();
return SUCCESS;
}
Entity class for test:
#Entity
#Table(name="test")
public class Test {
#Id
#Column(name = "AO_ID")
#SequenceGenerator(name = "SequenceIdGenerator", sequenceName = "SEQ_AT_ORGANISATION",allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceIdGenerator")
private int AO_ID;
#Column(name = "AO_Name")
private String AO_Name;
#Column(name = "AO_CreatedBy")
private String AO_CreatedBy;
public int getAO_ID() {
return AO_ID;
}
public void setAO_ID(int aO_ID) {
AO_ID = aO_ID;
}
public String getAO_Name() {
return AO_Name;
}
public void setAO_Name(String aO_Name) {
AO_Name = aO_Name;
}
public String getAO_CreatedBy() {
return AO_CreatedBy;
}
public void setAO_CreatedBy(String aO_CreatedBy) {
AO_CreatedBy = aO_CreatedBy;
}
}
DAO method :
public void addOrg(Test t) {
//System.out.println("save : "+org);
Session session = null;
session = sessionfactory.openSession();
try {
System.out.println("before save : "+t.getAO_ID());
session.save(t);
System.out.println("after save : "+t.getAO_ID());
} catch (Exception e) {
e.printStackTrace();
}
I didn't get any errors and data is not go to db. I test this code with mysql and it works fine. I think problem is with sequence.
out put is like this.
before save : 0
Hibernate:
select
SEQ_AT_ORGANISATION.nextval
from
dual
after save : 1
Can you try
public void addOrg(Test t) {
//System.out.println("save : "+org);
Session session = sessionfactory.openSession();
Transaction tx;
try {
tx = session.beginTransaction();
session.save(t);
tx.commit();
System.out.println("after save : "+t.getAO_ID());
} catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}

hibernate join using an

I am trying to do a hibernate join - the query seemingly works but when i try to cast from the object returned into the type i want it to be it doesnt work...im assuming because it has the joined table info too..
#Entity
#Table(name = "PSNG_SMRY")
public class PSNG_SMRY implements Serializable, Comparable<PSNG_SMRY>
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment" , strategy = "increment")
#Printable
public Integer SMRY_ID;
public Integer DEV_ID;
public Integer RPTD_TRN_ID;
#OneToOne(mappedBy="smry", cascade=CascadeType.ALL)
public TRN trn;
}
#Entity
#Table(name = "TRN")
public class TRN implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
public Integer TRN_ID;
public String TRN_SCTN
public String TRN_SYMB;
#OneToOne
#PrimaryKeyJoinColumn
private PSNG_SMRY smry;
}
I found this one to one mapping example here - link
And when I get the Object back from hibernate I try to cast it to PSNG_SMRY and it wont work - how am i am to do a join where i get the PSNG_SMRY info and the TRN_SYMB from the TRN table back using a join?
EDIT:
I get an invalid cast exception - [Ljava.lang.Object; cannot be cast to PSNG_SMRY
query code:
//code from some function that sets up all queries
String qQuery = "FROM PSNG_SMRY P, TRN T WHERE T.TRN_ID = P.RPTD_TRN_ID and P.FIR_AXLE_PASD_DT > sysdate - :timeLimit and P.FIR_AXLE_PASD_DT < sysdate - 1/24 ORDER BY P.FIR_AXLE_PASD_DT";
hqlParamList.add(new HQLParams("timeLimit", timeLimit)); //some list to pass to hibernate and then parameterize the queury
result = queryDatabase(qQuery, q4Query, hqlParamList);
public QueryResult queryDatabase(String qQuery, String q4Query,
List<HQLParams> params) {
QueryResult results = new QueryResult();
jwdsqa = new Connection("JWDSQA");
jwds4qa = new Connection("JWDS4QA");
results.qa = jwdsqa.retrieve(qQuery, params);
results.qa4 = jwds4qa.retrieve(q4Query, params);
return results;
}
EDIT:
This is the connection class - it is just used to get the session information and do all the hibernate stuff such as getting data...
public class Connection {
public static Logger logger = Logger.getLogger(Connection.class);
Session session;
String sessionName;
public Connection(String name){
session = HibernateUtil.getSessionFactory(name).openSession();
sessionName = name;
if(session.isConnected()){
//System.out.println(name + " - Connected");
}
}
public Session getSession(){
return session;
}
#SuppressWarnings("unchecked")
public List<Object> retrieve(String qry, List<HQLParams> paramList)
{
Transaction transaction = null;
List<Object> obj = null;
try {
transaction = session.beginTransaction();
String queryString = qry;
Query query = session.createQuery(queryString);
if(paramList != null)
{
for(HQLParams param: paramList)
{
query.setParameter(param.paramName, param.params);
}
}
List<Object> obj_ = query.list();
obj = obj_;
//session.getTransaction().commit();
} catch (HibernateException ex) {
ex.printStackTrace();
logger.error(ex.getMessage() + "\n" + ex.getStackTrace());
transaction.rollback();
} catch (Exception ex) {
System.err.println(ex.getMessage());
logger.error(ex.getMessage() + "\n" + ex.getStackTrace());
}
finally
{
session.close();
//System.out.println("Closing session " + sessionName);
}
return obj;
}
}
I ended up figuring this out - the reason why I was getting the casting error was hibernate was returning both the PSNG_SMRY and TRN objects back as an Object[] - and not as one Object.
If you want PSNG_SMRY instances you should not have to ask for the TRN table. This is provided for you when you use using JPA mapping
FROM PSNG_SMRY P
WHERE P.FIR_AXLE_PASD_DT > sysdate - :timeLimit
and P.FIR_AXLE_PASD_DT < sysdate - 1/24
ORDER BY P.FIR_AXLE_PASD_DT
If you do not get the TRN for the retrieved PSNG_SMRY objects then it means there is a mapping error because you are telling Hibernate how to retrieve the TRN for a PSNG_SMRY in your annotation
#OneToOne(mappedBy="smry", cascade=CascadeType.ALL)
public TRN trn;

use of entityManager.createNativeQuery(query,foo.class)

I would like to return a List of Integers from a
javax.persistence.EntityManager.createNativeQuery call
Why is the following incorrect?
entityManager.createNativeQuery("Select P.AppID From P", Integer.class);
specifically why do I get "...Unknown entity: java.lang.Integer"
Would I have to create an entity class that has a single field that is an Integer ?
Thanks
What you do is called a projection. That's when you return only a scalar value that belongs to one entity. You can do this with JPA. See scalar value.
I think in this case, omitting the entity type altogether is possible:
Query query = em.createNativeQuery( "select id from users where username = ?");
query.setParameter(1, "lt");
BigDecimal val = (BigDecimal) query.getSingleResult();
Example taken from here.
That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the #Entity annotation on it).
for you you should do the following:
Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();
or if you want to use HQL you can do something like this:
Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();
Regards.
Here is a DB2 Stored Procidure that receive a parameter
SQL
CREATE PROCEDURE getStateByName (IN StateName VARCHAR(128))
DYNAMIC RESULT SETS 1
P1: BEGIN
-- Declare cursor
DECLARE State_Cursor CURSOR WITH RETURN for
-- #######################################################################
-- # Replace the SQL statement with your statement.
-- # Note: Be sure to end statements with the terminator character (usually ';')
-- #
-- # The example SQL statement SELECT NAME FROM SYSIBM.SYSTABLES
-- # returns all names from SYSIBM.SYSTABLES.
-- ######################################################################
SELECT * FROM COUNTRY.STATE
WHERE PROVINCE_NAME LIKE UPPER(stateName);
-- Cursor left open for client application
OPEN Province_Cursor;
END P1
Java
//Country is a db2 scheme
//Now here is a java Entity bean Method
public List<Province> getStateByName(String stateName) throws Exception {
EntityManager em = this.em;
List<State> states= null;
try {
Query query = em.createNativeQuery("call NGB.getStateByName(?1)", Province.class);
query.setParameter(1, provinceName);
states= (List<Province>) query.getResultList();
} catch (Exception ex) {
throw ex;
}
return states;
}
Suppose your query is "select id,name from users where rollNo = 1001".
Here query will return a object with id and name column.
Your Response class is like bellow:
public class UserObject{
int id;
String name;
String rollNo;
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
here UserObject constructor will get a Object Array and set data with object.
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
Your query executing function is like bellow :
public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {
String queryStr = "select id,name from users where rollNo = ?1";
try {
Query query = entityManager.createNativeQuery(queryStr);
query.setParameter(1, rollNo);
return new UserObject((Object[]) query.getSingleResult());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Here you have to import bellow packages:
import javax.persistence.Query;
import javax.persistence.EntityManager;
Now your main class, you have to call this function.
First you have to get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:
#PersistenceContext
private EntityManager entityManager;
UserObject userObject = getUserByRoll(entityManager,"1001");
Now you have data in this userObject.
Here is Imports
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Note:
query.getSingleResult() return a array. You have to maintain the column position and data type.
select id,name from users where rollNo = ?1
query return a array and it's [0] --> id and [1] -> name.
For more info, visit this Answer
Thanks :)
JPA was designed to provide an automatic mapping between Objects and a relational database. Since Integer is not a persistant entity, why do you need to use JPA ? A simple JDBC request will work fine.

Categories

Resources