Annonceindlæg fra Barco
08. december 2005 - 17:40
#2
Smider lige et eksempel som jeg har kigget lidt på. (Er fra bogen Enterprise JavaBeans) import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ejb.EntityContext; import java.sql.SQLException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.sql.DataSource; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.FinderException; import javax.ejb.ObjectNotFoundException; import java.util.Vector; import java.util.Collection; public class ShipBean implements javax.ejb.EntityBean { public Integer id; public String name; public int capacity; public double tonnage; public EntityContext context; public Integer ejbCreate (Integer id, String name, int capacity, double tonnage) throws CreateException { System.out.println ("ejbCreate() pk="+id+" name="+name); if ((id.intValue () < 1) || (name == null)) throw new CreateException ("Invalid Parameters"); this.id = id; this.name = name; this.capacity = capacity; this.tonnage = tonnage; Connection con = null; PreparedStatement ps = null; try { con = this.getConnection (); ps = con.prepareStatement ("insert into Ship (id, name, capacity, tonnage) values (?,?,?,?)"); ps.setInt (1, id.intValue ()); ps.setString (2, name); ps.setInt (3, capacity); ps.setDouble (4, tonnage); if (ps.executeUpdate () != 1) { throw new CreateException ("Failed to add Ship to database"); } return id; } catch (SQLException se) { throw new EJBException (se); } finally { try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } public void ejbPostCreate (Integer id, String name, int capacity, double tonnage) { // Do something useful with the primary key. } public Integer ejbCreate (Integer id, String name ) throws CreateException { return ejbCreate (id,name,0,0); } public void ejbPostCreate (Integer id, String name) { // Do something useful with the EJBObject reference. } public Integer ejbFindByPrimaryKey (Integer primaryKey) throws FinderException { System.out.println ("ejbFindByPrimaryKey() primaryKey="+primaryKey); Connection con = null; PreparedStatement ps = null; ResultSet result = null; try { con = this.getConnection (); ps = con.prepareStatement ("select id from Ship where id = ?"); ps.setInt (1, primaryKey.intValue ()); result = ps.executeQuery (); // Does ship id exist in database? if (!result.next ()) { throw new ObjectNotFoundException ("Cannot find Ship with id = "+id); } } catch (SQLException se) { throw new EJBException (se); } finally { try { if (result != null) result.close (); } catch (Exception e) {} try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } return primaryKey; } public Collection ejbFindByCapacity (int capacity) throws FinderException { System.out.println ("ejbFindByCapacity() capacity="+capacity); Connection con = null; PreparedStatement ps = null; ResultSet result = null; try { con = this.getConnection (); ps = con.prepareStatement ("select id from Ship where capacity = ?"); ps.setInt (1,capacity); result = ps.executeQuery (); Vector keys = new Vector (); while(result.next ()) { keys.addElement (result.getObject ("id")); } return keys; } catch (SQLException se) { throw new EJBException (se); } finally { try { if (result != null) result.close (); } catch (Exception e) {} try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } public void setEntityContext (EntityContext ctx) { context = ctx; } public void unsetEntityContext () { context = null; } public void ejbActivate () {} public void ejbPassivate () {} public void ejbLoad () { Integer primaryKey = (Integer)context.getPrimaryKey (); System.out.println ("ejbLoad() pk="+primaryKey); Connection con = null; PreparedStatement ps = null; ResultSet result = null; try { con = this.getConnection (); ps = con.prepareStatement ("select name, capacity, tonnage from Ship where id = ?"); ps.setInt (1, primaryKey.intValue ()); result = ps.executeQuery (); if (result.next ()) { id = primaryKey; name = result.getString ("name"); capacity = result.getInt ("capacity"); tonnage = result.getDouble ("tonnage"); } else { throw new EJBException (); } } catch (SQLException se) { throw new EJBException (se); } finally { try { if (result != null) result.close (); } catch (Exception e) {} try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } public void ejbStore () { System.out.println ("ejbStore() pk="+id); Connection con = null; PreparedStatement ps = null; try { con = this.getConnection (); ps = con.prepareStatement ("update Ship set name = ?, capacity = ?, tonnage = ? where id = ?"); ps.setString (1,name); ps.setInt (2,capacity); ps.setDouble (3,tonnage); ps.setInt (4,id.intValue ()); if (ps.executeUpdate () != 1) { throw new EJBException ("ejbStore unable to update table"); } } catch (SQLException se) { throw new EJBException (se); } finally { try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } public void ejbRemove () { System.out.println ("ejbRemove() pk="+id); Connection con = null; PreparedStatement ps = null; try { con = this.getConnection (); ps = con.prepareStatement ("delete from Ship where id = ?"); ps.setInt (1, id.intValue ()); if (ps.executeUpdate () != 1) { throw new EJBException ("ejbRemove unable to remove bean"); } } catch (SQLException se) { throw new EJBException (se); } finally { try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } public String getName () { System.out.println ("getName()"); return name; } public void setName (String n) { System.out.println ("setName()"); name = n; } public void setCapacity (int cap) { System.out.println ("setCapacity()"); capacity = cap; } public int getCapacity () { System.out.println ("getCapacity()"); return capacity; } public double getTonnage () { System.out.println ("getTonnage()"); return tonnage; } public void setTonnage (double tons) { System.out.println ("setTonnage()"); tonnage = tons; } public void ejbHomeMakeDbTable () throws SQLException { PreparedStatement ps = null; Connection con = null; try { con = this.getConnection (); System.out.println("Creating table SHIP..."); ps = con.prepareStatement ("CREATE TABLE SHIP ( " + "ID INT PRIMARY KEY, " + "NAME CHAR(30), " + "TONNAGE DECIMAL (8,2), " + "CAPACITY INT" + ")" ); ps.execute (); System.out.println("...done!"); } finally { try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } public void ejbHomeDeleteDbTable () throws SQLException { PreparedStatement ps = null; Connection con = null; try { con = this.getConnection (); System.out.println("Dropping table SHIP..."); ps = con.prepareStatement ("DROP TABLE SHIP"); ps.execute (); System.out.println("...done!"); } finally { try { if (ps != null) ps.close (); } catch (Exception e) {} try { if (con != null) con.close (); } catch (Exception e) {} } } private Connection getConnection () throws SQLException { try { Context jndiCntx = new InitialContext (); DataSource ds = (DataSource)jndiCntx.lookup ("java:comp/env/jdbc/titanDB"); return ds.getConnection (); } catch (NamingException ne) { throw new EJBException (ne); } } } import javax.ejb.CreateException; import javax.ejb.FinderException; import java.rmi.RemoteException; import java.util.Collection; public interface ShipHomeRemote extends javax.ejb.EJBHome { public ShipRemote create(Integer id, String name, int capacity, double tonnage) throws RemoteException, CreateException; public ShipRemote create(Integer id, String name) throws RemoteException, CreateException; public ShipRemote findByPrimaryKey(Integer primaryKey) throws FinderException, RemoteException; public Collection findByCapacity(int capacity) throws FinderException, RemoteException; // Utility methods for database table creation/deletion // (this is specific to the JBoss workbook to make testing easier) // public void makeDbTable() throws RemoteException; public void deleteDbTable() throws RemoteException; } import java.rmi.RemoteException; public interface ShipRemote extends javax.ejb.EJBObject { public String getName() throws RemoteException; public void setName(String name) throws RemoteException; public void setCapacity(int cap) throws RemoteException; public int getCapacity() throws RemoteException; public double getTonnage() throws RemoteException; public void setTonnage(double tons) throws RemoteException; } !!! Klienten !!!! package com.titan.clients; import com.titan.ship.*; import java.rmi.RemoteException; import javax.naming.InitialContext; import javax.naming.Context; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; public class Client { public static void main (String [] args) { try { Context jndiContext = getInitialContext (); Object ref = jndiContext.lookup ("ShipHomeRemote"); ShipHomeRemote home = (ShipHomeRemote) PortableRemoteObject.narrow (ref,ShipHomeRemote.class); // We check if we have to build the database schema... // if ( (args.length > 0) && args[0].equalsIgnoreCase ("CreateDB") ) { System.out.println ("Creating database table..."); home.makeDbTable (); } // ... or if we have to drop it... // else if ( (args.length > 0) && args[0].equalsIgnoreCase ("DropDB") ) { System.out.println ("Dropping database table..."); home.deleteDbTable (); } else { // ... standard behavior // System.out.println ("Creating Ship 101.."); ShipRemote ship1 = home.create (new Integer (101),"Edmund Fitzgerald"); ship1.setTonnage (50000.0); ship1.setCapacity (300); Integer pk = new Integer (101); System.out.println ("Finding Ship 101 again.."); ShipRemote ship2 = home.findByPrimaryKey (pk); System.out.println (ship2.getName ()); System.out.println (ship2.getTonnage ()); System.out.println (ship2.getCapacity ()); System.out.println ("ship1.equals (ship2) == " + ship1.equals (ship2)); System.out.println ("Removing Ship 101.."); ship2.remove (); } } catch (java.rmi.RemoteException re) { re.printStackTrace (); } catch (javax.naming.NamingException ne) { ne.printStackTrace (); } catch (javax.ejb.CreateException ce) { ce.printStackTrace (); } catch (javax.ejb.FinderException fe) { fe.printStackTrace (); } catch (javax.ejb.RemoveException re) { re.printStackTrace (); } } public static Context getInitialContext () throws javax.naming.NamingException { return new javax.naming.InitialContext (); } }
qp
Nybegynder
09. december 2005 - 00:42
#4
Sorry er først inde og kigge nu og har selv lavet en løsning. Men jeg løste problemet ved at lave en finder metode der retunerede alle posterne. Kode >> package vare; import javax.ejb.*; import java.sql.*; import java.util.*; public class VareBean implements EntityBean, VareRemoteBusiness { private javax.ejb.EntityContext context; private Connection con; private Integer varenummer; private String beskrivelse; private String pris; public void setEntityContext(EntityContext aContext) { context = aContext; } public void ejbActivate() { varenummer = (Integer) context.getPrimaryKey(); } public void ejbPassivate() { varenummer = null; } public void ejbRemove() { } public void unsetEntityContext() { context = null; } public void ejbLoad() { try{ loadRow(); } catch(SQLException e){ throw new EJBException("Somethings wrong !!"); } } public void ejbStore() { } public Integer getVarenummer() { return varenummer; } public String getBeskrivelse() { return beskrivelse; } public String getPris() { return pris; } public Integer ejbFindByPrimaryKey(Integer aKey) throws FinderException { boolean found; try { connect(); String sql_str = "select varenr from vare where varenr=?"; PreparedStatement ps = con.prepareStatement(sql_str); ps.setInt(1, aKey.intValue()); ResultSet rs = ps.executeQuery(); found = rs.next(); rs.close(); ps.close(); disConnect(); } catch(SQLException e) { throw new EJBException(e.getMessage()); } if(found) return aKey; else throw new ObjectNotFoundException(aKey + " not found."); } public java.util.Collection ejbFindAll() throws FinderException, SQLException { ArrayList result = new ArrayList(); connect(); Statement stmt = con.createStatement(); String sql_str = "select * from vare"; ResultSet rs = stmt.executeQuery(sql_str); while(rs.next()) { int varenummer = rs.getInt(1); result.add(new Integer(varenummer)); } rs.close(); stmt.close(); disConnect(); return result; } private void loadRow() throws SQLException { connect(); String sql_str = "select * from vare where varenr=?"; PreparedStatement ps = con.prepareStatement(sql_str); ps.setInt(1, varenummer.intValue()); ResultSet rs = ps.executeQuery(); if(rs.next()) { varenummer = new Integer(rs.getInt(1)); beskrivelse = rs.getString(2); pris = rs.getString(3); } else { throw new NoSuchEntityException("Row not found"); } rs.close(); ps.close(); disConnect(); } private javax.sql.DataSource getDB() throws javax.naming.NamingException { javax.naming.Context c = new javax.naming.InitialContext(); return (javax.sql.DataSource) c.lookup("java:comp/env/jdbc/DB"); } private void connect() { try { con = getDB().getConnection(); } catch(Exception e) { throw new EJBException(e.getMessage()); } } private void disConnect() { try { con.close(); } catch(SQLException e) { throw new EJBException(e.getMessage()); } } } P.s. Det var en opgave der skulle løses og BMP skulle bruges ..