There is no truly automated way to do this, since the mechanism
for unique value generation differs by DB product. However, there is a
good approach if you can get a value from the DB without actually
inserting the row (like the Sequence in Oracle, *not* the auto-increment
in MySQL). The way is to write some manual JDBC in ejbCreate. ejbCreate
gets called *before* the CMP insert, so you can fetch the value
there. However, you must add a data source reference to your
ejb-jar.xml and jboss.xml in order for this to work - normally for CMP
you only specify the data source in jaws.xml. Let me try to whip up an
example - I know I've done this before.
Ahh:
public ReminderKey ejbCreate(String username) throws CreateException {
this.username = username;
try {
id = createPrimaryKey();
} catch(SQLException e) {
throw new CreateException(e.getMessage());
}
return null;
}
private int createPrimaryKey() throws SQLException {
Connection conn = null;
try {
int result = -1;
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/"+
CONNECTION_POOL);
conn = ds.getConnection();
String sql = "SELECT REMINDER_SEQ.NEXTVAL FROM DUAL";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
result = rs.getInt(1);
}
rs.close();
ps.close();
if(result < 0)
throw new SQLException("ReminderBean didn't get a value "+
"from the sequence!");
return result;
} catch(NamingException e) {
System.out.println("ReminderBean unable to look up "+
"DataSource: "+e);
throw new SQLException(e.getMessage());
} finally {
if(conn != null)
try {conn.close();}catch(SQLException e) {}
}
}
Aaron
On Wed, 27 Sep 2000, Christian Bourque wrote:
> Hi !
>
> I want my ejb to use an automatically generated primary key. So when i
> call create in the home interface, i dont want to pass in the primary
> key, i want the container to automatically fill this in (such as an
> auto-increment column in MS-SQL or a sequence in oracle).
>
> Is there any way to make a CMP entity EJB use a automatic value as its
> primary key, so that in the create method you dont have to pass it the
> primary key value ?
>
> If anyone has any idea I would really appreciate !
>
> Christian
>
>
>
>
> --
> --------------------------------------------------------------
> To subscribe: [EMAIL PROTECTED]
> To unsubscribe: [EMAIL PROTECTED]
> Problems?: [EMAIL PROTECTED]
>
--
--------------------------------------------------------------
To subscribe: [EMAIL PROTECTED]
To unsubscribe: [EMAIL PROTECTED]
Problems?: [EMAIL PROTECTED]