JFinal's original Db + Record mode
The Db class and its supporting Record class provide richer database operation functions in addition to the Model class. When using the Db and Record classes, there is no need to map database tables. Record is equivalent to a general Model. The following are some common uses of the Db + Record mode:
// Create a record object with a name attribute of James and an age attribute of 25 and add it to the database
Record user = new Record(). set("name", "James").set("age", 25); Db.save("user", user);
// Delete the record in the user table with id value 25
Db.deleteById("user", 25);
// Query the Record with id value 25, change its name attribute to James and update it to the database user = Db.findById("user", 25).set("name", "James"); Db.update("user", user);
// Get the name attribute of user
String userName = user.getStr("name ");
// Get the age attribute of user
Integer userAge = user.getInt("age");
// Query all users who are older than 18 years old
List<Record> ; users = Db.find("select * from user where age > 18");
// Paging query for users whose age is greater than 18, the current page number is 1, 10 users per page
Page<Record> userPage = Db.paginate(1, 10, "select *", "from user where age > ?", 18);
Record user = new Record(). set("name", "James").set("age", 25); Db.save("user", user);
// Delete the record in the user table with id value 25
Db.deleteById("user", 25);
// Query the Record with id value 25, change its name attribute to James and update it to the database user = Db.findById("user", 25).set("name", "James"); Db.update("user", user);
// Get the name attribute of user
String userName = user.getStr("name ");
// Get the age attribute of user
Integer userAge = user.getInt("age");
// Query all users who are older than 18 years old
List<Record> ; users = Db.find("select * from user where age > 18");
// Paging query for users whose age is greater than 18, the current page number is 1, 10 users per page
Page<Record> userPage = Db.paginate(1, 10, "select *", "from user where age > ?", 18);
The following is an example of transaction processing:
boolean succeed = Db.tx(new IAtom(){
public boolean run() throws SQLException {
int count = Db.update("update account set cash = cash - ? where id = ?", 100, 123);
int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);
return count == 1 && count2 = = 1;
}});
public boolean run() throws SQLException {
int count = Db.update("update account set cash = cash - ? where id = ?", 100, 123);
int count2 = Db.update("update account set cash = cash + ? where id = ?", 100, 456);
return count == 1 && count2 = = 1;
}});
The above two database update operations are executed in one transaction. If an exception occurs during the execution or the invoke() method returns false, the transaction will be automatically rolled back. .