views:

348

answers:

3

Hi guys,

How do I do a low_priority or delayed insert into a MySQL table with Hibernate?

In my logging routine I want to insert the log info to a table in my database for further analysis. But I don't care about how long it takes for the insert to be done, so usually I would say INSERT LOW_PRIORITY INTO LogEntry (level, title, full) VALUES ('Info', 'Title here', 'Full log'); If I have an entity LogEntry, how do I write or wire up my LogEntryDAO to do LOW_PRIORITY or DELAYED inserts and updates?

Cheers

Nik

+1  A: 

I would say that a better solution would be to have a Log4J appender write that message to a queue and a MessageListener pick it up and INSERT it into the database.

Your app is decoupled from the database that way, and you won't care how long it takes. If your database goes down, your persistent queue can accumulate messages until you're able to bring it back up again.

Be sure to use an XA JDBC driver and a transaction manager so the queue and database can be one single transaction.

duffymo
Note that XA doesn't always work as advertised. No XA so far handles the case when any of the participants dies between PREPARE and COMMIT properly. In this case, you can get anything from data corruption to data loss and/or deadlocks.
Aaron Digulla
Indeed, this is probably also a very good way to solve the problem. So there's no low_priority or delayed options in Hibernate?
niklassaers
They don't sound portable to me, so if you find those features only in MySQL I'd say the answer is "no". Not that I know of.
duffymo
+1  A: 

Use an org.hibernate.Interceptor. It will get a copy of the SQL to execute to modify.

See the docs for details.

Aaron Digulla
Ok, so no way to do it in plain Hibernate? If not, this seems like a good way to go, except that now I'll be dependent on my db dialect again
niklassaers
Since MySQL is the only DB which supports INSERT LOW_PRIORITY, Hibernate doesn't offer support for it.
Aaron Digulla
+1  A: 

There is a much simpler solution.

Annotate my entity class with @SQLInsert(sql="INSERT LOW_PRIORITY INTO LogEntry (level, title, full) VALUES (?, ?,?)")

Nice and elegant :-)

niklassaers
Also not portable. But hey, whatever works :)
laura