简体   繁体   中英

Efficient way to fetch data from database

I want to know which query style is better & efficient

I am using jdbc to fetch data from multiple tables(I am having more than 10 tables to fetch data). All data are related with keys

for that I am considering two ways

1) I am using joins to fetch data from database

Query s="select a.*,b.*,c.*......";//fetchin all data using joins in single query

Preparedstatement ps = con.prepareStatement(query);//con is a connection object
ResultSet res = ps.executeQuery();
//fetching data from resultset res
con.close(); 

2)I am taking data from each individual table

Query s="select from table a";
Preparedstatement ps = con.prepareStatement(s);
ResultSet res = ps.executeQuery();
//fetching data from resultset res
Query s1="select from table b";
Preparedstatement ps1 = con.prepareStatement(s1);
ResultSet res1 = ps1.executeQuery();
//fetching data from resultset res1
.............
//continue for all remaining tables
con.close();           

I would like to know if there is any other/better method to it.

EDIT: I am using very large amount of data. What about hibernet other methods

The best way in my opinion is to handle all SQL stuff within one statement. As you proposed as version 1). If this is too complex for you in the Java sources, you could use a stored function in the database (I know only the Oracle/MySQL possibilities) and handle more complex statements in there. In Java you call just the stored function/procedure and handle the results in Java. This works fine for me.

The other possibility is to use ORM like Hibernate or whatever. But for small things this would be overkill :)

With 1), propably combined with stored functions but not really necessary, you let the database cache your statement and get the imho best performance. If you load table after table in your approach 2) and have to process the data and store it. That might be not that efficient.

Are your data actually linked? Or are they distinct conceptual data sets, eg you're loading Products in query1, and say, Sizes, Colours, Towns int queries 2, 3 and 4? If the latter, then distinct queries could well be best, avoiding problems arising from aritificial JOIN constructs.

Edit - if tables are indeed related, then JOINing sounds appropriate, provided you use an efficient query. In your SELECT be sure to pull back only fields you need (ignore "extra" ones) to aid performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM