Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1143
  • Last Modified:

Hibernate with native SQL

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
thomers1
Asked:
thomers1
  • 2
  • 2
2 Solutions
 
racekCommented:
0
 
mahomeCommented:
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
 
Tomas Helgi JohannssonCommented:
      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
 
mahomeCommented:
@TomasHelgi
That only works with a mapping
0
 
Tomas Helgi JohannssonCommented:
This works with or without mapping.

Regards,
   Tomas Helgi
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now