Using database in Enterprise application client module.

In my last post the new Netbeans project type was presented. Today, I would like to use this project and show how a database connection can be developed in Enterprise application client very simple. Let's start to create application that lists customers that are stored in database.
  • Create new Enterprise Application client project
  • Add new JFrame with name DisplayCustomernames in the project. In the form put JTable
  • Open project's properties panel and set this class as main class in the application
  • Open JFrame in source editor. Now, we should inject DataSource and creat table model
  • Injected property should be in Main class and should be static. We will use default JDBC resource in Glassfish that has a name jdbc/__deafult. Add these lines at beginning of the class:
            @Resource(name="jdbc/__default")
            private static DataSource ds;
         
  • Then, create Customer class that represents customer entity in database. This isn't needed in small application. Create new class Customer with id, name and email properties. Create set/get methods for these fields.
  • Create a model for JTable. Add new CustomerTblModel class that implements TableModel. In constructor add method that reads data from database:
          private void readData() {
            Connection conn = null;
            try{
            conn = ds.getConnection();
            PreparedStatement pStmt = 
                 conn.prepareStatement("SELECT CUSTOMER_ID, NAME, EMAIL FROM CUSTOMER");
            ResultSet rs = pStmt.executeQuery();
            while(rs.next()){
                custs.add(new Customer(rs.getInt(1), rs.getString(2), rs.getString(3)));
            }
            }catch(SQLException ex) {
                throw new RuntimeException(ex);
            }finally {
                if(conn != null) {
                    try {
                    conn.close();
                    } catch(SQLException ex) { }
                }
            }
        }
       
  • Don't forget set the table model in JFrame constructor after initComponents method:
          public DisplayCustomerNames() {
            initComponents();
            cstTableModel = new CustomerTableModel(ds);
            jTable1.setModel(cstTableModel);
        }
       
     
  • Run project.
Project sources are here.
Comments:

good done, guy!

Posted by pprun on March 28, 2006 at 08:22 AM CEST #

Post a Comment:
Comments are closed for this entry.
About

pblaha

Search

Categories
Archives
« May 2015
SunMonTueWedThuFriSat
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
      
Today
Bookmarks