Jfinal can remove the primary key after saving the object, even if the primary key is the database self-growing.
Today, I inadvertently found that jfinal save the object can be removed from the primary key, my database table primary keys are self-increment. Like what
Blog blog = getmodel (blog.class);//There is no ID stored here
Blog.save ();
System.out.println (Blog.getint ("id"));//It can be taken out here.
Today the study of half a day, finally in the help of everyone finally understand how to achieve. The source code of the model class is as follows:
public Boolean Save () {
Config config = getconfig ();
Table table = GetTable ();
StringBuilder sql = new StringBuilder ();
List<object> paras = new arraylist<object> ();
Config.dialect.forModelSave (table, Attrs, SQL, paras);
if (paras.size () = = 0) return false; The SQL "INSERT into TableName () values ()" works fine, so delete this line
// --------
Connection conn = null;
PreparedStatement PST = NULL;
int result = 0;
try {
conn = Config.getconnection ();
if (Config.dialect.isOracle ())
PST = conn.preparestatement (sql.tostring (), New String[]{table.getprimarykey ()});
Else
PST = conn.preparestatement (sql.tostring (), Statement.return_generated_keys);
Config.dialect.fillStatement (PST, paras);
result = Pst.executeupdate ();
getgeneratedkey (PST, table);
Getmodifyflag (). Clear ();
return result >= 1;
} catch (Exception e) {
throw new Activerecordexception (e);
} finally {
Config.close (PST, conn);
}
}
According to the general direction of the wave, the red Bold code is the key to take out the primary key after saving, and the green bold part is the concrete implementation process. After viewing the API, this method is to create a default PreparedStatement
object that gets the auto-generated keys. The given constant tells the driver whether the auto-generated key can be obtained. If the SQL statement is not a INSERT
statement, or if the SQL statement can return an auto-generated key (the list of such statements is vendor-specific), this parameter is ignored as "the exact words of the JDK Chinese document".
Source code for the Green bold section:
/**
* Get ID after save method.
*/
private void Getgeneratedkey (PreparedStatement PST, table table) throws SQLException {
String PKey = Table.getprimarykey ();
if (get (pKey) = = NULL | | getconfig (). Dialect.isoracle ()) {
ResultSet rs = Pst.getgeneratedkeys ();
if (Rs.next ()) {
Class Coltype = Table.getcolumntype (PKey);
if (Coltype = = Integer.class | | coltype = = int.class)
Set (PKey, Rs.getint (1));
else if (Coltype = = Long.class | | coltype = = long.class)
Set (PKey, Rs.getlong (1));
Else
Set (PKey, Rs.getobject (1)); It returns Long object for int coltype
Rs.close ();
}
}
}
Jfinal you can remove the primary key after saving the object