how to prevent my website from doing sql injection in it
I am working using Struts 2 , DB MY sql .
The best way I think is to not re-invent the wheel and use the tools already available. For a small project I would recommend to simply use prepared statements when querying your database.
http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
You could also look into using an ORM like Hybernate. But make sure to use it as intended. Even HQL can be susceptible to injection. See: how much safe from SQL-Injection if using hibernate
The important thing is to not write your own native queries by concatenating query strings with values from untrusted sources.
Related
I need to execute some T-SQL code in Java. I would be glad if it was possible in Spring.
I have an ERP system, that is a little bit old, and some tasks we need to perform some T-SQL code, call a lot of procedures etc. The codes has about 200 lines. We want to automate it.
Can I execute native SQL lines in Java. I mean just pass SQL statements that I execute in SQL Management Studio. I read about JdbcTestUtils, but it's deprecated.
Isn't it any other solution for that?
Two thoughts come to mind. JdbcTemplates and Native Queries.
Spring provides an abstraction over JDBC called JdbcTemplates. With JdbcTemplates, you can execute any arbitrary SQL and organize the results into lists and objects. This is not really tied to JPA though.
Within JPA, you can use Native Queries. This is slightly more oriented to marshalling data back into Entities so if that what you are interested in, it might be a better choice. And you can execute named queries with the same EntityManager that JPA provides.
I am working on a project which uses Activiti1 Library and, for these reason, I am using MyBatis API to execute some native queries against Activiti data base.
The problem is: For some builds I am using Oracle and, for other, MySQL database then, as the dialect of this two data bases is different, it would be necessary to use the MyBatis multi vendor support, however, I didn't like it, because I have to deal with specific statments of each type of data base which makes the maintance a hard task, mainly if necessary to add another data base in the future.
So I would like to know if somehow it is possible to use HQL together with MyBatis or if there are another generic SQL engine that can be used in this case.
Or if someone know a free Java API that converts MySQL queries to Oracle queries. I tried to use Hibernate translation, however it didn't work, because Activiti classes is not using JPA, so it is not mapped :(.
Thanks in advance!
Sandro
In Activiti, we do use the multi-vendor support of MyBatis. However, there are only a few cases where we really needed. Do you have that much 'special' queries?
I'm working on an app which uses hard coded sql statements to retrieve data from a database and then populate this data into pojo's. Spring jdbc template is being used so dont need to worry about opening/closing connections. Using hard-coded sql statements seems wrong ?
Is there a design pattern or library I can use to abstact the sql statements ?
Look at MyBatis (formly iBatis).
It let's you extract hardcoded SQLs into XML files (or even annotations),
It integrates with Spring container, and can use Spring Transaction.
and many more.
Using JdbcTemplate, your application code still has the responsibility to provide sql and the JdbcTemplate can then execute SQL query or updates, iterate over ResultSets and catch JDBC exceptions. If you want to get away with writing hard-coded sql statements, you need to look into an ORM tools like Hibernate, iBatisetc
Here's a good previous discussion of some of the issues surrounding the choice between using raw SQL or an ORM tool:
Hibernate, iBatis, Java EE or other Java ORM tool
There is nothing inherently wrong with having SQL inside Java classes (although it's a bit controversial). If you want to externalize SQL queries you can:
use MyBatis which is very mature
put SQL in your applicationContext.xml Spring configuration file and inject it to POJOs (poor man's MyBatis)
hide SQL behind DAO pattern (interface SomeDao and class SqlSomeDao having SQL encapsulated)
...going for full ORM like JPA if you already have SQLs is not the best idea
Also check out Spring Data JDBC generic DAO - small DAO implementation on top of JdbcTemplate and RowMapper<T>. Disclaimer: I'm an author of this library.
A simple question: what is the more efficient way to access a db in Java/JDBC?
I'm a web developper and I'd like to write some reusable and scalable code. What is interesting for me is the use of tools like the ResultSupport: is it too expansive in terms of resource usage?
What can you suggest?
Not just JDBC specific, just general SQL stuff
If you have to rerun a query multiple times, use PreparedStatement. Use stored procedure if it is available. This is obviously not portable so YMMV.
Always close your ResultSet or Statement if you are not using it. Closing a Statement will auto close all ResultSet associated with the Statement. Still it is a good habit to close the ResultSet.
Try to restrict what can be queried eg. select * from orders where order_date between XXX and yyy. In MySQL the query may either be a full table scan or 'range' depending on how much data is returned. So deciding a how 'flexible' you want your queries to be
If you are using MySQL, use explain to optimize your query. If you are using JPA, then you don't get to see the SQL generated. (This is not strictly JDBC) You might want to enable logging on the ORM manager to display the SQL statement used. Then use explain to optimize that. You may want to use #NamedNativeQuery if the ORM generates a really convoluted query
If your JDBC driver supports batch update then use that. Batch updates is supported in PreparedStatement and ResultSet.
You can also control the commit. Good idea to turn it off if you are performing lots of updates. The call commit() yourself.
Best answer to this simple question is: "it depends".
There are many API's you can use for database access. Nearly all of them will use the JDBC API as their means to communicate with the database. So in theory, nothing can beat raw low level JDBC (just as machine code is in theory always faster than higherlevel programming languages).
But as you also like to write reusable code, I suggest you look into JPA. It's the Java standard for object persistence to relational databases. It’s performance is quite good and it’s very portable.
As JPA is just a specification, you can choose you’re own implementation: Hibernate, OpenJPA or any compliant Java EE server.
It is very important to use always a connection pool DataSource such as c3p0.
There is a project that maps java objects to mysql databases. Azirt.
Use connection pooling (either the one from your container or a standalone connection pool like c3p0 or DBCP) and something like DBUtils or Spring's JdbcTemplate.
I think the easiest and most common way is to use Spring and their JDBCTemplate.
The best approach likely depends on the stack you are using to create your web app. If you're starting afresh then Spring is a good way to go.
I am starting out writing java code and interacting with databases for my "nextbigthing" project. Can someone direct me towards the best way to deal with adding/updating tables/records to databases? Here is my problem. There is too much repitition when it comes to DB code in java. I have to create the tables first (I use mysql). I then create classes in Java for each table. Then I create a AddRow, DeleteRow, UpdateRow and Search* depending on my need. For every table, every need creating this huge ass sql statement and the classes all seems like a huge waste of my time. There has to be a better, easier, more efficient way of doing things. Is there something out there that I do not know that will let me just tell Java what the table is and it automatically generate the queries and execute them for me? Its simple SQL that can be auto generated if it knows the column names and DB table inter dependencies. Seems like a very reasonable thing to have.
Check out Hibernate - a standard Java ORM solution.
User hibernate for mapping your classes to Database.
Set its hbm2ddl.auto to update to avoid writing DDL yourself. But note that this is not the most optimal way to take it to production.
Consider using Hibernate:
https://www.hibernate.org/
It can create java classes with regular CRUD methods from existing database schema.
Of course there is a much better way !
You really want to learn some bits of Java EE, and in particular JPA for database access.
For a complete crash course on Java EE, check out the Sun the Java EE 5 tutorial.
http://java.sun.com/javaee/5/docs/tutorial/doc/
Part 4 - Enterprise Beans
Part 5 - Persistence (JPA)
Then you want to try Hibernate (for instance) which has an implementation of JPA.
This is for Java 5 or later.
If you are still in Java 2, you might want to try Hibernate or iBatis.
You can also try iBatis, if you want control over SQL. Else JPA is good.
You can also try using Seam Framework. It has good reverse-engineering tools.
There is also torque (http://db.apache.org/torque/) which I personally prefer because it's simpler, and does exactly what I need.
With torque I can define a database with mysql(Well I use Postgresql, but Mysql is supported too) and Torque can then query the database and then generate java classes for each table in the database. With Torque you can then query the database and get back Java objects of the correct type.
It supports where clauses (Either with a Criteria object or you can write the sql yourself) and joins.
It also support foreign keys, so if you got a User table and a House table, where a user can own 0 or more houses, there will be a getHouses() method on the user object which will give you the list of House objects the user own.
To get a first look at the kind of code you can write, take a look at
http://db.apache.org/torque/releases/torque-3.3/tutorial/step5.html which contains examples which show how to load/save/query data with torque. (All the classes used in this example are auto-generated based on the database definition).
Or, if Hibernate is too much, try Spring JDBC. It eliminates a lot of boilerplate code for you.
iBatis is another good choice, intermediate between Spring JDBC and Hibernate.
It's just a matter of using the right tools. Use an IDE with tools to autogenerate the one and other.
If you're using Eclipse for Java EE and decide to head to JPA, then I can recommend to take benefit of the builtin Dali plugin. There's a nice PDF tutorial out at Eclipse.org.
If you're using Eclipse for Java EE and decide to head to "good ol" Hibernate, then I can recommend to take benefit of the Hibernatetools plugin. There's good reference guide out at Hibernate.org.
Both tools are capable of reverse-engineering from a SQL table to fullworthy Javabeans/entities and/or mapping files. It really takes most of boilerplate pains away. The DAO pattern is slightly superflous when grabbing JPA. In case of Hibernate you can consider to use a Generic DAO.