JFinal DB. tx () Transaction rollback and lambda expression application, jfinaldb. tx
JFinal DB. tx () Transaction rollback
Transactions are required to operate on multiple data records in the database. JFinal contains encapsulated transaction applications.
Statement:
Db. tx (new IAtom () {@ Override public boolean run () throw SQLException {// write the operation to be executed here. The operation result is a boolean value return result ;}});
Practical application example:
1 // create the invitation code 2 public String setInviteCode (final WwInviteCodeTemp codeTemp, final Long userId, Integer app) {3 String inviteCode = ""; 4 if (codeTemp! = Null) {5 inviteCode = codeTemp. getCode (); // get the random invitation code 6 final WwInviteCode code = (WwInviteCode) newRecord (new WwInviteCode (); // Save the invitation code 7 code. setApp (app); // save product code 8. setUserId (userId); 9 code. setInviteCode (inviteCode); 10 final Integer finalApp = app; 11 boolean B = use (). tx (new IAtom () {12 @ Override13 public boolean run () throws SQLException {14 boolean flag = codeTemp. setAction (1 ). update (); 15 if (flag) {16 WwInviteCode wwInviteCode = WwInviteCode. dao. findById (userId); 17 if (wwInviteCode! = Null) {18 flag = false; 19} else {20 flag = code. setApp (finalApp ). setUserId (userId ). setInviteCode (codeTemp. getCode ()). save (); 21} 22} 23 return flag; 24} 25}); 26 if (B = false) {27 inviteCode = ""; 28} 29} 30 return inviteCode; 31}
If return false or an exception is thrown, the transaction will be rolled back. If return true, the transaction will be committed, Db. the tx () method returns true/false values. You can return the value to the job. If you want the run method to pass variables to the outer layer, you can define a final modified container class object in the outer layer.
Change to lambda expression mode:
1 // create the invitation code 2 public String setInviteCode (final WwInviteCodeTemp codeTemp, final Long userId, Integer app) {3 String inviteCode = ""; 4 if (codeTemp! = Null) {5 inviteCode = codeTemp. getCode (); // get the random invitation code 6 final WwInviteCode code = (WwInviteCode) newRecord (new WwInviteCode (); // Save the invitation code 7 code. setApp (app); // save product code 8. setUserId (userId); 9 code. setInviteCode (inviteCode); 10 final Integer finalApp = app; 11 boolean B = use (). tx ()-> {12 boolean flag = codeTemp. setAction (1 ). update (); 13 if (flag) {14 WwInviteCode wwInviteCode = WwInviteCode. da O. findById (userId); 15 if (wwInviteCode! = Null) {16 flag = false; 17} else {18 flag = code. setApp (finalApp ). setUserId (userId ). setInviteCode (codeTemp. getCode ()). save (); 19} 20} 21 return flag; 22}); 23 if (B = false) {24 inviteCode = ""; 25} 26} 27 return inviteCode; 28}
For more information about Java Lambda, see:
30-minute Java Lambda getting started tutorial