Writing once to DB

I have a method, which link a particular student (studentId) to a number of modules (moduleId) and then call a method, createRegistration, which run the sql insert method.

Once the user has clicked on the 'Register Module' button on the JSP form, the method is called.

I want to make sure that once the information has been written into the database, and the user click on the 'Register Module' button again, that the same information is not written in the database.

private void writeToDataBase()throws SQLException, ClassNotFoundException,

IOException, ServletException, FileNotFoundException

{

moduleVector = (Vector) session.getAttribute( "moduleVector" );

studentBean = (StudentBean) session.getAttribute( "studentBean" );

Iterator i = null;

i = moduleVector.iterator();

session.setAttribute( "register", new Boolean(false));

if ( ! ((Boolean) session.getAttribute( "register" ) ).booleanValue() ) {

while ( i.hasNext() ) {

moduleBean = (ModuleBean) i.next();

srsBean.createRegistration( studentBean.getStudentId(),

moduleBean.getModuleId() );

}

session.setAttribute( "register", new Boolean(true) );

}else{

errorBean.setErrorType( "You have already register for these modules."

+ " Click on back button." );

request.setAttribute("errorBean", errorBean);

display( "Error.jsp" );

}

removeSession( "register" );

}

At the moment, my logic is wrong. Every time the user click the Register Module button, it write it to DB. How do I make sure it is only written once?

[1635 byte] By [Yjavaa] at [2007-9-28 18:32:11]
# 1
Design your table so that it has an index that does not allow duplicate keys. Then the second write will throw an exception.
DrClapa at 2007-7-12 16:31:58 > top of Java-index,Other Topics,Algorithms...
# 2
or do a select before you do your insert, a result null resultset will show that the record is not in the db.
morgalra at 2007-7-12 16:31:58 > top of Java-index,Other Topics,Algorithms...
# 3

if there is no appropriate primary key in the table you're writing to, then avoid the duplicate write in your JSP code itself.

I would assume that each 'studentID' is unique, so create a HashMap, or a similar structure that you add each tupled value to before adding the tuple to the DB. This way you can check which values have been added during this session (slightly more work would have to be done to apply this to solution to future seesions) before going to the DB.

This avoids searching the DB (the select method), and overcomes not having a primary key (which would, if you can do it, be the best solution).

drmadskillsa at 2007-7-12 16:31:58 > top of Java-index,Other Topics,Algorithms...