Hibernate DAO doesn't insert row into database MyEclipse - java

I'm trying to insert a new object into my database. I followed a step-by-step tutorial but it seems it doesn't work for me. In the tutorial there was the following line :
Transaction tx = dao.GetSession().beginTransaction();
The GetSession doesn't pop up, i get the error "GetSession() is not visible from DaoHibernateSupport".
I replaced the line with the following :
Transaction tx = dao.getSessionFactory().getCurrentSession().beginTransaction();
but then i got a null Exception on the currentSession.
I read online and added the current_session_context property, set as "thread".
Everything seems to work now, i don 't get any Exception but still no rows are inserted into my MySql database. The table is InnoDB.
Here is my final code:
Banner banner = new Banner();
banner.setUrl(url);
banner.setCategorie(categorie);
banner.setCuvinteCheie(cuvinte_cheie);
banner.setMaxCpc(cpc);
banner.setPath(cale);
banner.setPaththumb(caleThumb);
banner.setAdvertiserId(Integer.parseInt(session.getAttribute("UserID").toString()));
BannerDAO dao = new BannerDAO();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
dao.setSessionFactory(sessionFactory);
Transaction tx = dao.getSessionFactory().getCurrentSession().beginTransaction();
dao.save(banner);
tx.commit();
dao.getSessionFactory().getCurrentSession().close();
So no exceptions raised here, but when i access the database there are no rows in the table.
Can you please help me ?
Thank you!

You may try
Transaction tx = dao.getSessionFactory().openSession().beginTransaction();
instead of
Transaction tx = dao.getSessionFactory().getCurrentSession().beginTransaction();

I figured it out. When i used reverse engineering in MyEclipse i created a SpringDAO instead of BasicDAO. Now the method getSession() works fine.

Related

Doesn't session.get() in hibernate always hit the database?

Theoretically, session.get() method is supposed to hit the database always, no matter whether the entity is stored in the cache or not. But whenever I use session.get() or session.load(), both doesn't hit the database second time.
Session session = factory.openSession();
tx = session.beginTransaction();
Customer cust = (Customer)session.get(Customer.class,2);
System.out.println(cust.getCid()+","+cust.getFirstName()+","+cust.getLastName()+","+cust.getPhone());
Customer cust2 = (Customer)session.get(Customer.class,2);
System.out.println(cust2.getCid()+","+cust2.getFirstName()+","+cust2.getLastName()+","+cust2.getPhone());
tx.commit();
session.close();
and this is the output,
Hibernate: select customer0_.cid as cid1_1_0_, customer0_.firstName as firstNam2_1_0_, customer0_.lastName as lastName3_1_0_, customer0_.email as email4_1_0_, customer0_.phone as phone5_1_0_, customer0_.aid as aid6_1_0_ from mycustomers customer0_ where customer0_.cid=?
2,Sam,pp,9799999999
2,Sam,pp,9799999999
Select query is executed only once and next time, it's retrieved from the cache. Same output if I use session.load() method also.
Am I missing something here? Please clarify.
Here's what's happening here:
The first query on console
It will always return a “proxy”. For example if you do session.load(Customer.class, 2), it will return a proxy object. Proxy object just have an identifier value and nothing else. You can imagine it to be somewhat like this.
customer.id = 2;
customer.fname = null;
customer.lname = null;
customer.address = null;
//rest all properties are null
It will Hit the database whenever you'll access the properties. In your case you're immediately calling ust.getCid() so it will immediately hit the database to fetch those queries. So the first query that you see in your console will appear for both the cases (i.e., session.get() and session.load())
Try doing this and see what your console looks like:
Session session = factory.openSession();
tx = session.beginTransaction();
Customer cust = (Customer)session.get(Customer.class,2);
//do not call any getter.
You'll see the difference on your console.
 
Why is second query not appearing
Hibernate Second Level Cache
You're trying to access the same object that you've accessed previously. Hibernate will then (instead of fetching it from database again) fetch it from second level cache.
You'll find detailed example of this scenario on this page : Hibernate Second Level Cache.
(just see the last example, it's similar to what you're getting)

Hibernate's SQLQuery executeUpdate function starts, but does not fully execute

Working on a Spring application that uses Hibernate, and in my DAO layer we are running an UPDATE statement to update some values in an Oracle database.
To make sure I'm not crazy, I ran the statement in SQL Developer to make sure it works properly. Here is part of my DAO code:
public void updateObjectInMyTable(SomeClassA objectOfSomeClassA) {
Session session = getCurrentSession();
String sql = "UPDATE SCHEMA_NAME.TABLE_XYZ SET FIRST_NAME=:firstName, LAST_NAME=:lastName, ADDRESS=:address, CITY=:city, ZIPCODE=:zipcode WHERE ID_NUMBER = :idNumber";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("firstName", objectOfSomeClassA.getFirstName());
query.setParameter("lastName", objectOfSomeClassA.getLastName());
query.setParameter("address", objectOfSomeClassA.getAddress());
query.setParameter("city", objectOfSomeClassA.getCity());
query.setParameter("zipcode", objectOfSomeClassA.getZipcode());
query.setParameter("idNumber", objectOfSomeClassA.getIdNumber());
query.executeUpdate();
}
(Excuse the poor variables names used for substitutions of the real ones.) I did debug on the server and I do not see any errors with query.executeUpdate() It gets to that line, and doesn't pass on to the next statement I have in my service layer.
Anything I'm doing wrong?
Where's your transaction ?!
Use :
session.beginTransaction().commit();
add this in the end line of your code.
I hope this helps you.

hibernate hbm: automatic (unwanted) update found

In my project I use hibernate hbm and spring,i run an sql query to update a single column,
Query sql = getSession().createSQLQuery("update HISTORIQUE_DETAIL_APPELS set token_otp = '"+historiqueDetailAppelsVO.getCodeOtp()+"' where id = '"+historiqueDetailAppelsVO.getId()+"'");
try {
sql.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
I found that another query is executed and update the table in data base,
Hibernate: update HISTORIQUE_DETAIL_APPELS set token_otp = '14d3fc' where id = '150017'
Hibernate: update HISTORIQUE_DETAIL_APPELS set cod_cent=?, adresse_ip=?, id_conseiller=?, type_piece=?, num_piece_ident=?, msisdn=?, mois1_detail=?, mois2_detail=?, mois3_detail=?, date_demande=?, no_ticket_caisse=?, date_ticket=?, cod_user=?, dat_maj=?, flag_imp_data=?, date_imp_data=?, token_otp=?, send_mail=?, client_mail=?, date_debut=?, date_fin=? where id=?
where does the origin of the second update ?
I faced the same issue before, and after some research i found :
When user update any record by using direct query based operation, it is directly updated to database.
But, if the same record(previous copy) is already present in current session(that is previously read by user in current session) then, there is a difference occurs between database record(that is updated by query based operation) and current session record, due to this, hibernate again runs update query to update session record during either flushing of session or on transaction completion.
To avoid the second execution executed by hibernate either during flushing of session or on transaction completion.
I wish it will help you.
Thanks
I solve this probleme by adding : dynamic-update="true" in hbm.xml file
I found the solution here:
"The dynamic-update attribute tells Hibernate whether to include
unmodified properties in the SQL UPDATE statement."

Hibernate save SQL exception

Hi guys I am trying to save an object to a MySQL data base via Hibernate. if I execute following code
User user = new User();
user.setData_1("my data 5");
user.setFirstname("Freddy");
user.setLastname("Bob");
user.setId(5);
session.save(user);
session.getTransaction().commit();
I get a
'com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'xxx.my_table_1' doesn't exist'
exception. However, querying from the same table using the same config works just fine.
What could be the issue?
Check your connection string in the configuration something like hibernate.connection.url = jdbc:postgresql://localhost/mydatabase You may be missing the schema name in the url(mydatabase).
So, after some trial and error, I came to find out that the issue with the .get() (and apparently .save() too) was that I did not have a hibernate.default_schema set in config. Looks like it is used to create the 'dynamic' SQL for .save() and .get(), but if you use .createSQLQuery(), it just uses what ever String you pass as an argument for the SQL, and therefor works with out needing to have hibernate.default_schema set.

Insert Sql query not working with HQL

I am trying to make a simple insert into a DB with HQlL by using native SQL code.
It doesn't give any error, it just doesn't work. Any help is appreciated.
Thanks.
public void AddMedicament(Medicament medicament) {
System.out.println(medicament.getName());
// open a database connection
Session session = FarmacieHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
// prepare SQL insert command
session.createSQLQuery("insert into Medicament(name) values('test')");
// close the database connection
session.close();
}
You need to call
session.executeUpdate()
transaction.commit();
before closing session.
I am not familar with Hibernate, but i dont see you sre running your command. You just create query and close session
I think you need some statement to execute it.
If you use createSQLQuery this throw a native sql instruction
Your object table name is Medicament too?
session.saveOrUpdate(medicament);
tx.commit();
then it will insert if u r not setting the Primarykey, if u r setting the PK in the domain object then it will be updated.
no need to executeQuery in hibernate if you are using the Spring ORM.

Categories