Model


Model is one of the most important components in ActiveRecord, which acts as the Model part in the MVC pattern. The following is a sample code for

Model definition:

public class User extends Model<User> {
public static final User dao = new User();
}
By inheriting Model, User in the above code immediately has many convenient methods for operating the database. The dao static object declared in User is defined to facilitate query operations, and this object is not necessary. Model based on ActiveRecord does not need to define properties, getter, setter methods, XML configuration, or Annotation configuration, which greatly reduces the amount of code.

The following are some common uses of Model:

// Create a User object with the name attribute as James and the age attribute as 25 and add it to the database
new User(). set("name", "James").set("age", 25).save();

//Delete the User with id value 25 User.dao.deleteById(25);

// Query the User whose id value is 25, change its name attribute to James and update it to the database
User.dao.findByIdLoadColumns (25).set("name", "James").update() ;

// Query the user whose id value is 25, and only take the values ​​of the name and age fields
User user = User.dao.findByIdLoadColumns (25, "name, age");

// Get the user's name attribute
String userName = user.getStr("name");

// Get the user's age attribute
Integer userAge = user.getInt( "age");

// Query all users who are older than 18 years old
List<User> users = User.dao.find("select * from user where age>18");

// Paging query for users older than 18, the current page number is 1, 10 users per page
Page<User> userPage = User.dao.paginate(1, 10, "select *", " from user where age > ?", 18);


##Special attention: public static final User defined in User The dao object is globally shared and can only be used for database queries and cannot be used for data bearing objects. Data carrying needs to be implemented using new User().set(…).