# 5.3 Model

# 1. Basic Usage

Model is one of the most crucial components in ActiveRecord, acting as the Model in the MVC pattern. Here's a sample code to define a Model:

public class User extends Model<User> {
    public static final User dao = new User().dao();
}
1
2
3

By extending the Model in the User class above, you immediately obtain numerous convenient methods to operate on the database. The static dao object declared in User is designed to facilitate query operations. However, this object is not mandatory. With ActiveRecord's Model, there's no need to define properties, getter/setter methods, XML configurations, or Annotation configurations, substantially reducing the amount of code.

Here are some common usages of Model:

// Create a User object with 'name' as James and 'age' as 25, and add it to the database
new User().set("name", "James").set("age", 25).save();
 
// Delete the User with an id value of 25
User.dao.deleteById(25);
 
// Find the User with an id value of 25, change its 'name' to James and update it in the database
User.dao.findById(25).set("name", "James").update();
 
// Query the User with an id value of 25, and only retrieve the values of the 'name' and 'age' columns
User user = User.dao.findByIdLoadColumns(25, "name, age");
 
// Get the 'name' attribute of the user
String userName = user.getStr("name");
 
// Get the 'age' attribute of the user
Integer userAge = user.getInt("age");
 
// Query all users who are older than 18 years
List<User> users = User.dao.find("select * from user where age>18");
 
// Paginate and query users older than 18, with the current page number as 1 and 10 users per page
Page<User> userPage = User.dao.paginate(1, 10, "select *", "from user where age > ?", 18);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

The usage above showcases the dao object declared within the model for demonstration purposes. In practical applications, it's recommended to place the dao object inside a Service and set it to private. This ensures that SQL and database operations are confined within the service layer. You can refer to the usage of dao in the Service layer by downloading the jfinal_demo_for_maven from the official website.

Special Note: The public static final User dao object defined in User is globally shared and can only be used for database queries, not as a data carrier. For data-bearing, you need to use new User().set(...).

# 2. Common Mistakes

Many users often encounter NullPointerException exceptions when using methods like model.find(...). Typically, this is because the model hasn't been mapped using ActionRecordPlugin.addMapping(...). It's advisable to use a generator to automate the generation of mappings, eliminating the need for manual addition of such code. You can access the generator by downloading the jfinal demo from the official website, which provides it.

Last Updated: 9/17/2023, 6:16:57 AM