I’ve done all my database development for the past few years in Ruby, mostly using ActiveRecord. Now I’m stuck using Java for a project, and it feels so verbose and hamfisted, I’m wondering if I’m doing things wrong.
In an ORM paradigm, if I want to insert into related tables, I’d so something like
# Joe Bob got a new car
p = Person.find_or_create_by_name("Joe Bob");
Car.new({:make=>"Toyota", :plate=>"ABC 123", :owner=>p});
In Java, at least using JDBC directly, I’m going to have to do the Person lookup by hand, insert if it doesn’t exist, then create the Car entry.
Of course, in real life, it’s more than just 2 tables and the pain scales exponentially. Surely there’s a better way?
The better way is learn SQL! The ORM you like so much writes SQL for you behind the scenes.
So you can make a quick helper function that tries to select the record, and if it doesn’t exist creates it for you.
In MySQL you can use
INSERT IGNORE .....which will insert the row only if it doesn’t exist.And here is a special bit of SQL you may like (MySQL only):
This tries to insert the record, if it doesn’t exist it returns the auto_increment like usual that you retrieve in your program.
But: If it does exist then it updates it – (only c is set to update in that case), but the cool part is it sets the
LAST_INSERT_ID()just like it would on an insert.So either way you get the ID field. And all in a single bit of SQL.
SQL is a very nice language – you should learn it and not rely on the psudo-language of orm.