Empty collection after hibernate select - java

I want find all records in table 'users' using hibernate but its allways return empty collection (im sure that some users are in db). My searching function looks like this:
public List<Users> findAll() {
DetachedCriteria criteria = DetachedCriteria.forClass(Users.class);
return getHibernateTemplate().findByCriteria(criteria);
}
Why is not working?
hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/intellidom</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<mapping file="mapping/Users.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Users.hbm.xml:
<hibernate-mapping>
<class name="intellidom.entity.Users" table="users" schema="intellidom">
<id column="id" name="id" type="int" >
<generator class="increment"/>
</id>
<property name="login" column="login" type="java.lang.String"/>
<property name="password" column="password" type="java.lang.String"/>
<property name="firstName" column="firstName" type="java.lang.String"/>
<property name="lastName" column="lastName" type="java.lang.String"/>
</class>
</hibernate-mapping>

Related

org.hibernate.InvalidMappingException: Could not parse mapping document from resource User.hbm.xml

As an output I m receiving error:
org.hibernate.InvalidMappingException: Could not parse mapping document from resource User.hbm.xml.
I have tried solving it using links:
Could not parse mapping document from resource Books.hbm.xml
Hibernate and maven: Could not parse mapping document from resource
I'm trying to enter values in database using pojo class
User.hbm.xml
<hibernate-mapping>
<class name="com.program.User" table="user">
<id name="ID" type="int" column="id">
<generator class="increment" />
</id>
<property name="NAME" type="java.lang.String" column="name">
<column name="name" />
</property>
<property name="AGE" type="int" column="age">
<column name="age" />
</property>
</class>
</hibernate-mapping>
Program.java
package com.program;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Program {
public static void main(String[] args) {
try{
System.out.println("hello world");
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();;
Session session = factory.openSession();
session.beginTransaction();
User user = new User();
user.setID(1);
user.setNAME("Toral");
user.setAGE(21);
session.save(user);
session.getTransaction().commit();
session.close();
}catch(Exception e){
System.out.println(e);
}
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>
I think you misplaced actual value for "name" attribute ane "column" attribute.
"name" attribute represents property of your POJO class.
"column" attribute represents column name of your table.
Try this:
<hibernate-mapping>
<class name="com.program.User" table="user">
<id name="id" type="int" column="ID">
<generator class="increment" />
</id>
<property name="name" type="java.lang.String" column="NAME"></property>
<property name="age" type="int" column="AGE"></property>
</class>

how to convert this HQL to SQL

from EmployerCharges r1 where r1.routingCode.routingCode = ? and employer.employerId=?
where the following are the pojo classes
<class name="com.greytip.wps.model.EmployerCharges" table="emp_RoutingCode_Charges" lazy="false">
<id name="id" type="int" unsaved-value="0" >
<generator class="native">
<param name="sequence">emp_RoutingCode_id_seq</param>
</generator>
</id>
<many-to-one name ="employer" class = "com.greytip.wps.model.Employer"/>
<many-to-one name ="routingCode" class = "com.greytip.wps.model.RoutingCode"/>
<property name="charges"/>
</class>
//----------------------------------------
hibernate-mapping package="com.greytip.wps.model">
<class name="com.greytip.wps.model.Employer" table="wps_employer" lazy="false">
<id name="id" type="int" unsaved-value="0" >
<generator class="native">
<param name="sequence">wps_employer_id_seq</param>
</generator>
</id>
<property name="employerId"/>
<property name="name"/>
<property name="contactPerson"/>
<property name="address"/>
<property name="bankAcNo"/>
<property name="email"/>
<property name="licenseNo"/>
<property name="licenseExpiryDate"/>
<property name="active"/>
<many-to-one name ="emirateCode"/>
<many-to-one name ="economicActivity"/>
<many-to-one name ="wpsQueue"/>
<property name="schemaCreated"/>
<property name="code"/>
<many-to-one name ="branch"/>
<property name="bankCharges"/>
<property name="contactNo"/>
<many-to-one name="relationshipManager"/>
<many-to-one name ="employerGroup"/>
<property name="hpsEmployerReference"></property>
<property name="chargeReprocessing"></property>
<property name="restrictAccess"></property>
<property name="bankChargesPerFile"></property>
<property name="enableSalaryCardRequest"></property>
<property name="salaryCardCharges"/>
<property name="ftsBankChargesPerFile"/>
<property name="ftsIntBankChargesPerRecord"/>
<property name="ftsExtBankChargesPerRecord"/>
<property name="ftsExtBankChargesPerBank"/>
<property name="ftsIntBankChargesPerBank"/>
<property name="signature"/>
<property name="scReissueCharges"></property>
<property name="scActivateCharges"></property>
<property name="scCancelCharges"></property>
<property name="scReIssuePinCharges"></property>
<many-to-one name ="employerWorkflow"/>
<many-to-one name ="employerCategory"/>
<property name="poBox"></property>
<property name="bankChargesPerBank"></property>
<property name="bankChargesPerMonth"></property>
<property name="defaultCharges"></property>
<property name="isDeleted"></property>
<property name="monthlyCharges"></property>
<property name="appliedCharge"></property>
</class>
//-----------------------------------------------
<hibernate-mapping package="com.greytip.wps.model">
<class name="com.greytip.wps.model.RoutingCode" table="wps_routingCode" lazy="false">
<id name="id" type="int" unsaved-value="0" >
<generator class="native">
<param name="sequence">wps_routingCode_id_seq</param>
</generator>
</id>
<property name="bankCode"/>
<property name="bankName"/>
<property name="routingCode"/>
<property name="branchName"/>
</class>
Please tell me how to convert the hql to sql... Thank you..
Enable show sql and format sql parameters in hibernate configuration and you can see the queries being fired in the log file.
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
For more information see this question

If i fire 1 HQL query (device) then 51 times it's children are fired in many to one how to fix it, hibernate5

I fire a query for get device object but after fire this HQL query automatically subchild(deviceprofile) details how can i fix using HQL .....
com.zaxxer.hikari.hibernate.HikariConnectionProvider
<property name="hibernate.hikari.dataSource.url">jdbc:mysql://localhost:3306/gpstracking?autoReconnect=true</property>
<property name="hibernate.hikari.dataSource.user">root</property>
<property name="hibernate.hikari.dataSource.password">root</property>
<property name="hibernate.hikari.dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</property>
<property name="hibernate.hikari.maximumPoolSize">50</property>
<property name="hibernate.hikari.idleTimeout">30000</property>
<!-- <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/gpstracking?autoReconnect=true</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property> -->
<property name="hibernate.use_sql_comments">true</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><!--org.hibernate.dialect.MySQLDialect-->
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<!-- <mapping class="Model.ScheduleAlert" /> -->
<mapping resource="Model/ScheduleAlert.hbm.xml"/>
<mapping resource="Model/login.hbm.xml"/>
<mapping resource="Model/device.hbm.xml"/>
<mapping resource="Model/geopath.hbm.xml"/>
<mapping resource="Model/geopath_detail.hbm.xml"/>
<mapping resource="Model/DeviceImage.hbm.xml"/>
<mapping resource="Model/lastTrack.hbm.xml"/>
<mapping resource="Model/Gt06portrequest.hbm.xml"/>
<mapping resource="Model/history.hbm.xml"/>
<mapping resource="Model/historyzero.hbm.xml"/>
<mapping resource="Model/adminMaster.hbm.xml"/>
<mapping resource="Model/Message.hbm.xml"/>
<mapping resource="Model/PortRequests.hbm.xml"/>
<mapping resource="Model/PortParsers.hbm.xml"/>
<mapping resource="Model/Hostname.hbm.xml"/>
<mapping resource="Model/EmailTemplet.hbm.xml"/>
<mapping resource="Model/SelectedTemp.hbm.xml"/>
<mapping resource="Model/SancharnetUser.hbm.xml"/>
<mapping resource="Model/MessageTemplate.hbm.xml"/>
<mapping resource="Model/SelectedMsgTemp.hbm.xml"/>
<mapping resource="Model/Fence.hbm.xml"/>
<mapping resource="Model/FenceDevice.hbm.xml"/>
<mapping resource="Model/tag.hbm.xml"/>
<mapping resource="Model/tagtype.hbm.xml"/>
<mapping resource="Model/AlertMessages.hbm.xml"/>
<mapping resource="Model/MaxSpeed.hbm.xml"/>
<mapping resource="Model/alert/Alert.hbm.xml"/>
<mapping resource="Model/managerSettings.hbm.xml"/>
<mapping resource="Model/MobileParsers.hbm.xml"/>
<mapping resource="Model/SampleLivePath.hbm.xml"/>
<mapping resource="Model/managerMsgSettings.hbm.xml"/>
<mapping resource="Model/KMLFiles.hbm.xml"/>
<mapping resource="Model/DemoKmlFiles.hbm.xml"/>
<mapping resource="Model/DeviceGroup.hbm.xml"/>
<mapping resource="Model/AnalogData.hbm.xml"/>
<mapping resource="Model/PoiPoint.hbm.xml"/>
<mapping resource="Model/deviceprofile.hbm.xml"/>
<mapping resource="Model/DigitalInputAlert.hbm.xml"/>
<mapping resource="Model/AnalogInputAlert.hbm.xml"/>
<mapping resource="Model/POIAlert.hbm.xml"/>
<mapping resource="Model/OverConsumptionAlert.hbm.xml"/>
<mapping resource="Model/Devicemaster.hbm.xml"/>
<mapping resource="Model/analogdigitalparameter.hbm.xml"/>
<mapping resource="Model/ManagerReportMaster.hbm.xml"/>
<mapping resource="Model/ManagerReportChild.hbm.xml"/>
<mapping resource="Model/systemParameter.hbm.xml"/>
<mapping resource="Model/GeopathAlert.hbm.xml"/>
<mapping resource="Model/Drivermanage.hbm.xml"/>
<mapping resource="Model/Drivermaster.hbm.xml"/>
<mapping resource="Model/Usermaster.hbm.xml"/>
<mapping resource="Model/Useralocation.hbm.xml"/>
<mapping resource="Model/Kmllive.hbm.xml"/>
<mapping resource="Model/Payment.hbm.xml"/>
<mapping resource="Model/Locationdata.hbm.xml"/>
<mapping resource="Model/Alertallocationchild.hbm.xml"/>
<mapping resource="Model/Alertallocationmaster.hbm.xml"/>
<mapping resource="Model/Expiryreport.hbm.xml"/>
<mapping resource="Model/Imagedata.hbm.xml"/>
<mapping resource="Model/Convertedimg.hbm.xml"/>
<mapping resource="Model/Antitheftalert.hbm.xml"/>
<mapping resource="Model/OverStayAlert.hbm.xml"/>
<mapping resource="Model/Reseller.hbm.xml"/>
<mapping resource="Model/Client.hbm.xml"/>
<mapping resource="Model/RouteAlert.hbm.xml"/>
<mapping resource="Model/RouteMaster.hbm.xml"/>
<mapping resource="Model/Onediractionfencealert.hbm.xml"/>
<mapping resource="Model/LoginLog.hbm.xml"/>
<mapping resource="Model/MaintainanceMaster.hbm.xml"/>
<mapping resource="Model/MaintainanceType.hbm.xml"/>
<mapping resource="Model/BusScheduleMaster.hbm.xml"/>
<mapping resource="Model/Tcpcommand.hbm.xml"/>
</session-factory>
</hibernate-configuration>
device.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class lazy="false" name="Model.device" table="devicemaster">
<!--<cache usage="read-write"/>-->
<id name="deviceid" type="java.lang.Integer">
<column name="deviceid"/>
<generator class="increment"/>
</id>
<property index="idx_device_managerid" name="managerId" type="java.lang.Integer">
<column name="managerId"/>
</property>
<property name="tcpudpformat" type="java.lang.String">
<column length="50" name="tcpudpformat"/>
</property>
<property index="idx_device_devicename" name="deviceName" type="java.lang.String">
<column length="15" name="deviceName"/>
</property>
<property name="devicedescription" type="java.lang.String">
<column length="15" name="devicedescription"/>
</property>
<property name="flagcondition" type="java.lang.Boolean">
<column name="flagcondition"/>
</property>
<property index="idx_device_imei" name="imei" type="java.lang.String">
<column length="15" name="imei"/>
</property>
<property name="deviceType" type="java.lang.String">
<column length="15" name="deviceType"/>
</property>
<property name="mobileNo" type="java.lang.String">
<column length="15" name="MobileNo"/>
</property>
<property name="gpsFormate" type="java.lang.String">
<column length="50" name="GpsFormate"/>
</property>
<property name="anglePrecision" type="java.lang.Double">
<column default="0.0" name="anglePrecision"/>
</property>
<property name="preDist" type="java.lang.String">
<column length="15" name="PreDist"/>
</property>
<property name="preTime" type="java.lang.String">
<column length="15" name="PreTime"/>
</property>
<property name="viewDist" type="java.lang.String">
<column length="15" name="viewDist"/>
</property>
<property name="viewTime" type="java.lang.String">
<column length="15" name="viewTime"/>
</property>
<property name="driverMobileNo" type="java.lang.String">
<column name="driverMobileNo"/>
</property>
<property name="driverName" type="java.lang.String">
<column name="driverName"/>
</property>
<property name="milage" type="java.lang.Integer">
<column length="10" name="milage"/>
</property>
<property name="devicemodel" type="string">
<column length="15" name="devicemodel"/>
</property>
<property name="addedon" type="java.util.Date">
<column name="addedon"/>
</property>
<many-to-one column="profileId" index="idx_device_profileid" lazy="false" fetch="join" name="deviceProfile" update="true"/>
<many-to-one class="Model.DeviceGroup" column="groupno" index="idx_device_groupno" fetch="join" name="devicegroup" lazy="false"/>
</class>
</hibernate-mapping>
deviceprofile.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class lazy="false" name="Model.DeviceProfile" table="deviceprofile">
<id column="ProfileId" name="profileId" type="java.lang.Integer">
<generator class="increment"/>
</id>
<property column="ProfileName" index="idx_deviceprofile_profilename" length="50" name="profileName" type="java.lang.String">
</property>
<property column="SystemDate" length="30" name="systemDate" type="java.util.Date">
</property>
<property column="Odometer" length="15" name="odometer" type="java.lang.String">
</property>
<property column="digital_1" length="15" name="digital1" type="java.lang.String">
</property>
<property column="digital_1_inverse" name="digital1_inverse" type="java.lang.Boolean">
</property>
<property column="digital_2" length="15" name="digital2" type="java.lang.String">
</property>
<property column="digital_2_inverse" name="digital2_inverse" type="java.lang.Boolean">
</property>
<property column="digital_3" length="15" name="digital3" type="java.lang.String">
</property>
<property column="digital_3_inverse" name="digital3_inverse" type="java.lang.Boolean">
</property>
<property column="digital_4" length="15" name="digital4" type="java.lang.String">
</property>
<property column="digital_4_inverse" name="digital4_inverse" type="java.lang.Boolean">
</property>
<property column="digital_5" length="15" name="digital5" type="java.lang.String">
</property>
<property column="digital_5_inverse" name="digital5_inverse" type="java.lang.Boolean">
</property>
<property column="analog_5" length="15" name="analog5" type="java.lang.String">
</property>
<property column="analog_1_unit" length="15" name="analog1_unit" type="java.lang.String">
</property>
<property column="analog_2_unit" length="15" name="analog2_unit" type="java.lang.String">
</property>
<property column="analog_3_unit" length="15" name="analog3_unit" type="java.lang.String">
</property>
<property column="analog_4_unit" length="15" name="analog4_unit" type="java.lang.String">
</property>
<property column="analog_5_unit" length="15" name="analog5_unit" type="java.lang.String">
</property>
<property column="analog_1_formula" length="25" name="analog1_formula" type="java.lang.String">
</property>
<property column="analog_2_formula" length="25" name="analog2_formula" type="java.lang.String">
</property>
<property column="analog_3_formula" length="25" name="analog3_formula" type="java.lang.String">
</property>
<property column="analog_4_formula" length="25" name="analog4_formula" type="java.lang.String">
</property>
<property column="analog_5_formula" length="25" name="analog5_formula" type="java.lang.String">
</property>
<property column="GPSFormat" length="15" name="gpsformat" type="java.lang.String">
</property>
<property column="Cummulative_Odometer" length="15" name="cummulativeOdometer" type="java.lang.String">
</property>
<set cascade="all" inverse="true" name="analogdatas">
<key column="profileId"/>
<one-to-many class="Model.Analogdata"/>
</set>
<set cascade="all" inverse="true" lazy="false" name="deviceMaster">
<key column="profileId"/>
<one-to-many class="Model.device"/>
</set>
<many-to-one cascade="all" column="ManagerId" name="managerSettings2" update="false">
</many-to-one>
</class>
</hibernate-mapping>
i have already done this project and DAO file so please provide solution.....
Please explain your question properly.
Change deviceprofile.hbm.xml many-to-one mapping as below and check if it help:
<many-to-one cascade="all" column="ManagerId" name="managerSettings2" update="false" lazy="true" fetch="select">

Hibernate - org.hibernate.hql.internal.ast.QuerySyntaxException: Client is not mapped

I'm new to hibernate and I'm trying to solve some problems i cannot understand too well...
For example, I have this query
Query query = session.createQuery("from Client where clientId = "+clientId+")");
List result = query.list();
My Client.hbm.xml is
<class name="it.besmart.models.Client" table="client" catalog="SMARTPARK">
<id name="idClient" type="int">
<column name="id_client" />
<generator class="identity" />
</id>
<property name="nomeClient" type="string">
<column name="nome_client" length="65535" not-null="true" />
</property>
<property name="numPosti" type="int">
<column name="num_posti" not-null="true" />
</property>
<property name="numLuci" type="int">
<column name="num_luci" not-null="true" />
</property>
<property name="inizioPosti" type="int">
<column name="inizio_posti" not-null="true" />
</property>
<property name="inizioLuci" type="int">
<column name="inizio_luci" not-null="true" />
</property>
</class>
</hibernate-mapping>
The table on the DB is called client and the column is client_id
The mapping in hibernate.cfg.xml is
<hibernate-configuration>
<session-factory name="parkserver">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">passwprd</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.3.67:3306/SMARTPARK</property>
<property name="hibernate.connection.username">parkuser</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="it.besmart.models.Client" resource="Client.hbm.xml"/>
<mapping class="it.besmart.models.Illuminazione" resource="Illuminazione.hbm.xml"/>
<mapping class="it.besmart.models.MappaPosti" resource="MappaPosti.hbm.xml"/>
<mapping class="it.besmart.models.Occupazione" resource="Occupazione.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I'm having no problems in another query in the application, but when i try to executer the SELECT query i got this exception
org.hibernate.hql.internal.ast.QuerySyntaxException: Client is not mapped [from Client where clientId = 1)]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:150)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:298)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836)
at it.besmart.parkserver.SocketClientHandler.run(SocketClientHandler.java:83)
at java.lang.Thread.run(Thread.java:744)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Client is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:76)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3678)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3567)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:708)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:564)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
I don't know why Client is not mapped, it's correctly in the cfg file...
Thanks in advance
Try to add the full name of the class in the query:
Query query = session.createQuery("from it.besmart.models.Client where clientId = :c");
query.setString("c", clientId)
List result = query.list();
I also changed to late binding here which is preferable but has nothing to do with your problem.
As Maurice Perry pointed out in comment below:
- You can also specify the default package in the mapping file: <hibernate-mapping package="it.besmart.models">

Why doesn't hibernate load persisted entity from second level cache?

Does hibernate put into second level cache entity which I persist with save method?
My code is :
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Person person = new Person("Volodia", "Levytskyi", "Mykolaiv");
session.save(person);
transaction.commit();
session.close();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Person load = (Person) session.load(Person.class, (long) 1);
System.out.println("load2=" + load);
transaction.commit();
session.close();
I expect hibernate to load from second level cache person but it issues select query to database when
session.load(Person.class, (long) 1);
is running.
My hibernate.cfg.xml:
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernateSimpleDB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="transaction.factory_class">org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.generate_statistics">true</property>
<property name="current_session_context_class">thread</property>
<mapping resource="com/masterhibernate/SimpleHibernateDemo/Person.hbm.xml"
/>
<!-- <mapping class="com.masterhibernate.SimpleHibernateDemo.Person" /> -->
</session-factory>
</hibernate-configuration>
My Person.hbm.xml :
<hibernate-mapping>
<class name="com.masterhibernate.SimpleHibernateDemo.Person"
table="Person">
<cache usage="read-write" />
<id name="id" column="PersonId">
<generator class="native" />
</id>
<property name="name">
<column name="name" length="16" not-null="true" />
</property>
<property name="surname">
<column name="surname" length="36"></column>
</property>
<property name="address">
<column name="address" length="22"></column>
</property>
</class>
</hibernate-mapping>
Why is this?
It seems like you have your database set up to generate primary keys for you. This means that, when you save the entity, it does not yet have an ID, as it will later be assigned by the database. This also means that hibernate cannot store it in the second-level cache, as it doesn't have a key to index it with yet. It should be stored in the second-level cache after retrieving it again from the database though.

Categories

Resources