Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get superior terror checking of MySQL queries

Tags:

java

mysql

orm

jdbc

I just started using MySQL and I just can see myself woking with strings! I mean the compiler can't catch errors like this and it's just a mess! Is there a wrapper or some kind of class I can add that does something as simple as making a function that adds a table and asks for args?

I'm sure there is a tool like that but I can't find it or know its name.

like image 513
kalix Avatar asked Jun 02 '10 11:06

kalix


2 Answers

You're basically looking for an Object Relational Mapper. Hibernate is one of the pioniers in this area. JPA is a new and well-established Java EE standard in this area, formed by the guy behind Hibernate. Hibernate and EclipseLink offers JPA implementations.

There exist IDE tools to autogenerate Java classes based on database models and vice versa, such as Hibernate Tools for "good old" Hibernate and Eclipse Dali for JPA.

If you don't want to use an ORM and/or don't want to autogenerate model objects, then you just have to make sure that you design the right model objects for the database model. I.e. use a Long property for a BIGINT field, a BigDecimal property for a DECIMAL field, etcetera. You can find an overview of the default mappings in this page.

In "plain vanilla" JDBC you should at least use PreparedStatement methods to compose the SQL query rather than concatenating as String. There are a lot of setXXX() methods for the specific datatype, such as setLong(), setBigDecimal(), etcetera. The PreparedStatement not only eases setting fullworthy Java objects like Date and InputStream in a SQL query, but it also prevents the code from SQL injection attacks. You can learn more about PreparedStatement in the Sun JDBC tutorial and you can find a basic kickoff DAO tutorial in this article.

like image 69
BalusC Avatar answered Sep 28 '22 07:09

BalusC


You can use an object-relational mapper like Hibernate. See also What Java ORM do you prefer, and why?.

like image 42
Matthew Flaschen Avatar answered Sep 28 '22 08:09

Matthew Flaschen