KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > xpetstore > domain > catalog > dao > ProductDAO


1 package xpetstore.domain.catalog.dao;
2
3 import java.sql.Connection JavaDoc;
4 import java.sql.PreparedStatement JavaDoc;
5 import java.sql.ResultSet JavaDoc;
6 import java.sql.SQLException JavaDoc;
7
8 import java.util.ArrayList JavaDoc;
9
10 import xpetstore.util.Page;
11
12 import xpetstore.domain.catalog.ejb.Product;
13
14
15 /**
16  * This is a DAO class for complex db queries that can't be
17  * resolved by finders
18  *
19  * @author <a HREF="mailto:tchbansi@sourceforge.net">Herve Tchepannou</a>
20  */

21 public class ProductDAO
22 {
23     //~ Static fields/initializers ---------------------------------------------
24

25     private static final String JavaDoc SQL_FIND_BY_KEY = "SELECT productId,name,description FROM T_PRODUCT WHERE (productId LIKE ?) OR (name LIKE ?) OR (description LIKE ?)";
26
27     //~ Instance fields --------------------------------------------------------
28

29     private Connection JavaDoc _cnn;
30
31     //~ Constructors -----------------------------------------------------------
32

33     public ProductDAO( Connection JavaDoc cnn )
34     {
35         _cnn = cnn;
36     }
37
38     //~ Methods ----------------------------------------------------------------
39

40     public Page findByKey( String JavaDoc key,
41                            int start,
42                            int count )
43         throws SQLException JavaDoc
44     {
45         PreparedStatement JavaDoc stmt = null;
46         ResultSet JavaDoc rs = null;
47         try
48         {
49         stmt = _cnn.prepareStatement( SQL_FIND_BY_KEY, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
50
51         stmt.setString( 1, key );
52         stmt.setString( 2, key );
53         stmt.setString( 3, key );
54
55         rs = stmt.executeQuery( );
56
57         return toPage( rs, start, count );
58         }
59         finally
60         {
61             if ( stmt != null )
62             {
63                 stmt.close();
64             }
65             if ( rs != null )
66             {
67                 rs.close();
68             }
69         }
70     }
71
72     private Page toPage( ResultSet JavaDoc rs,
73                          int start,
74                          int count )
75         throws SQLException JavaDoc
76     {
77         int i;
78         int size;
79         int imax = start + count;
80         ArrayList JavaDoc lst = new ArrayList JavaDoc( );
81
82         for ( i = size = 0; rs.next( ); i++, size++ )
83         {
84             if ( ( i >= start ) && ( i < imax ) )
85             {
86                 lst.add( new Product( rs.getString( 1 ), rs.getString( 2 ), rs.getString( 3 ) ) );
87             }
88         }
89
90         return new Page( lst, start, ( start + count ) < size );
91     }
92 }
93
Popular Tags