Can't cast the result of query to entity - java

everyone. I'm new to Hibernate. And I'm making desktop application. I have 2 tables: Worker and Ceh (i.e. Department). Relation between them: many-to-one, i.e. 1 Ceh may contain many workers.
I run hql query with inner join to show info about all workers including name of the department and want to show the results in JTable.
The hql query:
private static String query_All_Workers="select W.fio, W.nomer, W.salary, C.name from Worker W Inner Join W.ceh C;
The method that runs query:
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery(hql);
List resultList = q.list();
displayResult(resultList);
session.getTransaction().commit();
} catch (HibernateException he) {
he.printStackTrace();
}
The method displayResult(List resultList):
Vector<String> tableHeaders = new Vector<>();
tableHeaders.add("FIO");
tableHeaders.add("Nomer");
tableHeaders.add("Salary");
tableHeaders.add("Ceh");
Vector tableData = new Vector();
for(Object o : resultList) {
Worker worker = (Worker)o;
Vector<Object> oneRow = new Vector<Object>();
oneRow.add(worker.getFio());
oneRow.add(worker.getNomer());
oneRow.add(worker.getSalary());
oneRow.add(worker.getCeh());
tableData.add(oneRow);
}
resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));
And the exception occurs like this:
"java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
workers.entity.Worker"
It happens because the list contains objects which are results of inner join query. So I don't know how I can correctly cast the object to Worker entity in order to use its getters.

You’re getting the “java.lang.ClassCastException” because you are trying to cast object of type java.lang.Object to custom class Worker:
Worker worker = (Worker)o;
There’s nothing wrong with what you’re trying to do just make sure that the result set returns actually Worker, which is not the case. In your example you are returning resultSet of Objects, because you’re writing regular JDBC select SQL statement.
In order to fix that you will need to checkout Hibernate’s Query Language (HQL) syntax and write HQL query instead of regular JDBC one.
Quick tutorial here http://www.tutorialspoint.com/hibernate/hibernate_query_language.htm
I will advise you do to so from now on, because you will gain the following benefits:
When you write select statements (or any other for that matter) with HQL you think and use Java objects, not DB tables (it helps a lot with table foreign key mappings);
HQL returns whole Java object back since Hibernate will do the necessary conversion for you.
In your case you just need to replace the query_All_Workers with this: “from Worker”. Yup, that’s it! Looks weird but as I said before, Hibernate is taking care of all conversions;
Once you’ve done that, and assuming that your Java class is properly mapped to Hibernate entity, resultSet will contain Workers this time, from which you can easily extract Ceh’s name by using Java getter method:
worker.getCeh.getName();
Also using HQL you will not need to make a second select to Ceh table, just to get the name, like you need to do right now.
Hope that helps.

Related

when is criteria better than HQL or nativeSQL Query?

In my Case after getting a certain list I need to to iterate that list to set some other fields of the POJO class.
if (transportHeaderList.get(i) instanceof TransportHeaderIiss){
transHeadIiss=(TransportHeaderIiss)transportHeaderList.get(i);
customerVendor= tOManagementDAO.getVendorCode(transHeadIiss.getCustVendUid());
}
if(customerVendor!=null){
transHeadIiss.setVendorCode(customerVendor.getCustVendCode());
}
The Above code calls getVendorCode method to get custVendorCode value from the database. The code for getVendorCode is as follows
public CustomerVendorIiss getVendorCode(Long custVendUid) {
List list=new ArrayList();
/* Criteria criteria = sessionFactory.getCurrentSession().createCriteria(CustomerVendorIiss.class);
criteria.add(Restrictions.eq("companyCode",user.getDefaultCompany().getCompanyCode()));
if(custVendUid!=null && custVendUid.intValue()>0)
{
criteria.add(Restrictions.eq("custVendUid",custVendUid));
}
list=criteria.list();*/
UsersIiss user= ApplicationContextProvider.getLoggedInUser();
String sqlQuery="select custVendCode as custVendCode from CustomerVendorIiss where companyCode ='"+ user.getDefaultCompany().getCompanyCode() +"' and custVendUid= "+custVendUid;
Query query = sessionFactory.getCurrentSession().createQuery(sqlQuery);
query.setResultTransformer(Transformers.aliasToBean(CustomerVendorIiss.class));
list=query.list();
if(list.size()>0){
return (CustomerVendorIiss)list.get(0);
}else{
return null;
}
}
When I executed above code with criteria, it took a lot time to get the values from table and set it to POJO class and sometimes I would get java.lang.OutOfMemoryError: Java heap space error . I guess that's because I am not de-allocating the criteria object.
when I executed the above code using createQuery() method I did not run into that issue and all that process of getting and setting was faster.
I want to understand what is that I am doing wrong here?
it would be great to know how and when criteria is better or HQL is better ?
Thank you !!
Actually these queries are different. The second one has an additional restriction
companyCode ='"+ user.getDefaultCompany().getCompanyCode() +"'
So try to add the same to the criteria
criteria.add(Restrictions.eq("companyCode",user.getDefaultCompany().getCompanyCode()));
Also it's not god to concate strings this way to get the query. SQL injection is possible. Use parameters instead.
Criteria and HQL is better than SQL in one case - you need DB independent logic to swap DB when necessary without rewriting code.

How to return hibernate collection entities without returning root entity

I would like to get elements of a collection (Set<SheetConfig>) for a set of objects (WorkbookConfig) from Hibernate without getting the primary objects(WorkbookConfig).
The underlying tables look like this:
workbook_config -> workbook_config_sheet_join <- sheet_config
If I just run it in my SQL utility, a successful SQL statement looks like this:
SELECT DISTINCT sheet_config_id FROM sheet_config AS sc
LEFT JOIN workbook_config_sheet_join AS wcsj
ON sc.sheet_config_id = wcsj.sheet_config_id
LEFT JOIN workbook_config AS wc
ON wc.workbook_config_id = wcsj.workbook_config_id
WHERE wc.group_id ="1"
ORDER BY sheet_name;
I would like to do this properly without using HQL.
My UNSUCCESSFUL attempt has resulted in this:
#SuppressWarnings("unchecked")
public List<SheetConfig> findAllForUser() {
List<SheetConfig> sheetConfigs = null;
Session session = getSession();
Criteria crit = session.createCriteria(WorkbookConfig.class)
.add(Restrictions.in(GROUP, getGroupsForUser()))
.setFetchMode(SHEET_CONFIGS, FetchMode.JOIN);
sheetConfigs = (List<SheetConfig>) crit.list();
return sheetConfigs;
}
This is still giving me WorkbookConfigs, but what I would like to do in a single pass is get SheetConfigs. I have spent the day on the Internet trying to find a coherent explanation of the Hibernate API, and I haven't been able to find what I would think is a solution to a fairly common requirement. I can always back out and just do most of the work in Java, but it seems like I should be able to do this with the Hibernate API. I appreciate any help, and also, if you can recommend a reference that explains not simply querying collections, but returning them, I would be grateful.
Did you look into the setProjection method on Criteria?
Using the setProjection method lets you select properties or objects from the executed query.
Hibernate Criteria documentation

Hibernate returns list of nulls although executed SQL returns values

I'm using hibernate as an ORMapper. I want to execute an actually rather simple hql query:
SELECT a
FROM Foo a
WHERE a.status = :A0status
ORDER BY a.bookingTypeCode ASC,
a.priority ASC
This hql query is then converted into a sql query which looks something like this:
select a.*
from Foo a
where a.status='A'
order by a.bookingtypecode ASC,
a.priority ASC
When I execute the sql on the oracle database using the Oracle SQL Developer I get 17 rows returned. However, when I execute the hql query (using the list method of a Query I get a list of 17 elements that are all null. Although the number of elements is correct, not a single one of the elements is actually loaded.
This is the way I create and execute my query:
// the hql query is stored in the hqlQuery variable;
// the parameter are stored in a Map<String, Object> called params
Query hQuery = hibSession.createQuery(hqlQuery);
for (Entry<String, Object> param : params.entrySet()) {
String key = param.getKey();
Object value = param.getValue();
hQuery.setParameter(key, value);
}
List<?> result = hQuery.list();
Does anyone know what might be the problem here?
Update 1
I've recently upgrade from hibernate 3.2 to 4.3.5. Before the upgrade everything worked fine. After the upgrade I get this error.
I've set the Log level of hibernate to TRACE and found the problem. It was actually a mapping/logic/database error. The primary key consisted of two columns (according to the entity class) and one of these columns was nullable. However a primary key can never be nullable. Therefore hibernate always returned null.
If you have not set a custom (and buggy) ResultTransformer, my second best guess is that your debugger is lying to you. Does you code actually receives a list of null?
Also make sure to test with the code you are showing is. Too many times, people simplify things and the devil is in the details.
This error is happening to me. MySQL query browser works, but in hibernate of 7 columns and only one column always came with all null fields. I checked all the ids and they were not null. The error was in the construction of SQL Native. I had to change the way of writing it. Ai worked.
SELECT c.idContratoEmprestimo as idContratoEmprestimo,
c.dtOperacao as dataOperacao,
p.cpf as cpf,
p.nome as nome,
(Select count(p2.idParcelaEmprestimo) from EMP_PARCELA p2 where p2.valorPago > 0 and p2.dtPagamento is not null
and p2.idContratoEmprestimo = c.idContratoEmprestimo and p2.mesCompetencia <= '2014-08-01') as parcelasPagas, c.numeroParcelas as numeroParcelas,
pe.valorPago as valorParcela
FROM EMP_CONTRATO c inner join TB_PARTICIPANTE_DADOS_PLANO AS pp on pp.idParticipantePlano = c.idParticipantePlano
inner join TB_PARTICIPANTE as p on p.id = pp.idParticipante
inner join TB_PARTICIPANTE_INSTITUIDOR as pi on pi.PARTICIPANTE_ID = p.id
inner join EMP_PARCELA as pe on pe.idContratoEmprestimo = c.idContratoEmprestimo
where c.dtInicioContrato <= '2014-08-01' and pi.INSTITUIDOR_ID = 1
and c.avaliado is true
and pe.mesCompetencia = '2014-08-01'
and c.deferido is true
and c.dtQuitacao is null
and c.dtExclusao is null
and pe.valorPago is not null
group by c.idContratoEmprestimo
order by p.nome

How to use Hibernate to query a MySQL database with indexes

I have an application developed based on MySQL that is connected through Hibernate. I used DAO utility code to query the database. Now I need optimize my database query by indexes. My question is, how can I query data through Hibernate DAO utility code and make sure indexes are used in MySQL database when queries are executed. Any hints or pointers to existing examples are appreciated!
Update: Just want to make the question more understandable a little bit. Following is the code I used to query the MySQL database through Hibernated DAO utility codes. I'm not directly using HQL here. Any suggestions for a best solution? If needed, I will rewrite the database query code and use HQL directly instead.
public static List<Measurements> getMeasurementsList(String physicalId, String startdate, String enddate) {
List<Measurements> listOfMeasurements = new ArrayList<Measurements>();
Timestamp queryStartDate = toTimestamp(startdate);
Timestamp queryEndDate = toTimestamp(enddate);
MeasurementsDAO measurementsDAO = new MeasurementsDAO();
PhysicalLocationDAO physicalLocationDAO = new PhysicalLocationDAO();
short id = Short.parseShort(physicalId);
List physicalLocationList = physicalLocationDAO.findByProperty("physicalId", id);
Iterator ite = physicalLocationList.iterator();
while(ite.hasNext()) {
PhysicalLocation physicalLocation = (PhysicalLocation)ite.next();
List measurementsList = measurementsDAO.findByProperty("physicalLocation", physicalLocation);
Iterator jte = measurementsList.iterator();
while(jte.hasNext()){
Measurements measurements = (Measurements)jte.next();
if(measurements.getMeasTstime().after(queryStartDate)
&& measurements.getMeasTstime().before(queryEndDate)) {
listOfMeasurements.add(measurements);
}
}
}
return listOfMeasurements;
}
Just like with SQL, you don't need to do anything special. Just execute your queries as usual, and the database will use the indices you've created to optimize them, if possible.
For example, let's say you have a HQL query that searches all the products that have a given name:
select p from Product where p.name = :name
This query will be translated by Hibernate to SQL:
select p.id, p.name, p.price, p.code from product p where p.name = ?
If you don't have any index set on product.name, the database will have to scan the whole table of products to find those that have the given name.
If you have an index set on product.name, the database will determine that, given the query, it's useful to use this index, and will thus know which rows have the given name thanks to the index. It willl thus be able to only read a small subset of the rows to return the queries data.
This is all transparent to you. You just need to know which queries are slow and frequent enough to justify the creation of an index to speed them up.

Copying Java ResultSet

I have a java.sql.ResultSet object that I need to update. However the result set is not updatable. Unfortunately this is a constraint on the particular framework I'm using.
What I'm trying to achieve here is taking data from a database, then manipulating a small amount of the data and finally the data is being written to a CSV file.
At this stage I think my best option is to create a new result set object and copy the contents of the original result set into the new one, manipulating the data as I do so.
However, I've hunted high and low on Google and don't seem to be able to determine how to do this or whether it's even possible at all.
I'm new to everything Java so any assistance would be gratefully received.
Thanks for the responses. In the end I found CachedRowSet which is exactly what I needed. With this I was able to disconnect the ResultSet object and update it.
What's more, because CachedRowSet implements the ResultSet interface I was still able to pass it to my file generation method which requires an object that implements ResultSet.
The normal practice would be to map the ResultSet to a List<Entity> where Entity is your own class which contains information about the data represented by a single database row. E.g. User, Person, Address, Product, Order, etcetera, depending on what the table actually contains.
List<Entity> entities = new ArrayList<Entity>();
// ...
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setName(resultSet.getString("name"));
entity.setValue(resultSet.getInt("value"));
// ...
entities.add(entity);
}
// ...
return entities;
Then, you can access, traverse and modify it the usual Java way. Finally, when persisting it back in the DB, use a PreparedStatement to update them in batches in a single go.
String sql = "UPDATE entity SET name = ?, value = ? WHERE id = ?";
// ...
statement = connection.prepareStatement(sql);
for (Entity entity : entities) {
statement.setString(1, entity.getName());
statement.setInt(2, entity.getValue());
statement.setLong(3, entity.getId());
// ...
statement.addBatch();
}
statement.executeBatch();
// ...
Note that some DB's have a limit on the batch size. Oracle's JDBC driver has a limit on around 1000 items. You may want to call executeBatch() every 1000 items then. It should be simple using a counter inside the loop.
See also:
Collections tutorial
PreparedStatement tutorial

Categories