Solved

Hibernate with native SQL

Posted on 2009-03-31
5
1,129 Views
Last Modified: 2013-11-24
i need to regularly update a timestamp attribute in a mysql table, while that table is not a hibernate-mapped entity class.

the SQL is something like
UPDATE mytable SET tstamp = NOW() where attr1 = val1 AND attr2 = val2

i don't want to introduce a new hibernate mapped entity just for this single statement. how can i use native SQL within a hibernate query/transaction (that updates other, hibernate-mapped tables)?
0
Comment
Question by:thomers1
  • 2
  • 2
5 Comments
 
LVL 14

Assisted Solution

by:racek
racek earned 100 total points
ID: 24036399
0
 
LVL 10

Accepted Solution

by:
mahome earned 400 total points
ID: 24036575
As far as I know you can't do updates with native SQL, only selects. You can use the connection of the session and use normal JDBC style.

Or if you have access to the dataSource you can get the connection from the datasource

Connection connection = session.connection();

Statement statement = connection.createStatement();

statement.execute("UPDATE mytable SET tstamp = NOW() where attr1 = val1 AND attr2 = val2");
 

or
 

dataSource.getConnection()

...

Open in new window

0
 
LVL 24

Expert Comment

by:Tomas Helgi Johannsson
ID: 24037297
      Hi!

Here is an example on how to use HQL
http://www.java2s.com/Code/Java/Hibernate/UpdateHQL.htm

Regards,
   Tomas Helgi

Ps. I posted this comment it in the other (duplicate) message by mistake.
0
 
LVL 10

Expert Comment

by:mahome
ID: 24037845
@TomasHelgi
That only works with a mapping
0
 
LVL 24

Expert Comment

by:Tomas Helgi Johannsson
ID: 24038081
This works with or without mapping.

Regards,
   Tomas Helgi
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Foreword In the years since this article was written, numerous hacking attacks have targeted password-protected web sites.  The storage of client passwords has become a subject of much discussion, some of it useful and some of it misguided.  Of cou…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now