Bom dia.
Criei um tabela no meu banco de dados chamada
sequence, que possui os seguintes campos:
currentValue INTEGER
name
VARCHAR
incremental INTEGER
E criei a seguinte classe:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.Statement;
import
java.text.MessageFormat;
public class Sequence
{
/** Instru��o SQL. */
private Statement st;
public Sequence(Statement st)
throws Exception
{
this.st = st;
}
/** Executa um sequence, para gera��o de chaves.
*
* @param name Nome da sequence.
* @return Retorna o novo valor da sequence. */
public synchronized int nextValue(String name)
throws SQLException, Exception
{
String queryUpdate =
"update sequence set currentValue = (currentValue + incremental) " +
" where name = {0}{1}{0}";
String querySelect =
"select currentValue from sequence " +
" where name = {0}{1}{0}";
Object[] sequence = { "'" , name.toLowerCase() };
// habilita auto-commit
st.getConnection().setAutoCommit(true);
// incremental.
st.executeUpdate(MessageFormat.format(queryUpdate, sequence));
{
/** Instru��o SQL. */
private Statement st;
public Sequence(Statement st)
throws Exception
{
this.st = st;
}
/** Executa um sequence, para gera��o de chaves.
*
* @param name Nome da sequence.
* @return Retorna o novo valor da sequence. */
public synchronized int nextValue(String name)
throws SQLException, Exception
{
String queryUpdate =
"update sequence set currentValue = (currentValue + incremental) " +
" where name = {0}{1}{0}";
String querySelect =
"select currentValue from sequence " +
" where name = {0}{1}{0}";
Object[] sequence = { "'" , name.toLowerCase() };
// habilita auto-commit
st.getConnection().setAutoCommit(true);
// incremental.
st.executeUpdate(MessageFormat.format(queryUpdate, sequence));
// desabilita auto-commit
st.getConnection().setAutoCommit(false);
// leitura do novo valor.
ResultSet rs = st.executeQuery(MessageFormat.format(querySelect, sequence));
// move o cursor.
rs.next();
return rs.getInt("currentValue");;
}
}
st.getConnection().setAutoCommit(false);
// leitura do novo valor.
ResultSet rs = st.executeQuery(MessageFormat.format(querySelect, sequence));
// move o cursor.
rs.next();
return rs.getInt("currentValue");;
}
}
O que vcs acham dessa solu��o para a cria��o de
chaves prim�rias em meu sistema? � vi�vel e port�vel?
aguardo criticas e sugest�es.
