Skip to content

Create Model

王爵nice edited this page Mar 17, 2018 · 2 revisions

Creating a database Model is very easy, Anima needs you to know some conventions, so that you will save more unnecessary operations in programming.

Model Agreement

  • The model class is named after the hump(HelloWorldUser)
  • The corresponding database table is a plural of the class name, separated by an underscore (hello_wordsusers)
  • Field naming is also the same
  • Default primary key is id

Create Model

Let's say we have a data table, which is the following structure.

CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) NOT NULL DEFAULT '',
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Create a Java Model

public class User extends Model {
    private Integer id;
    private String userName;
    private Integer age;
    // getter and setter omitted
}

This completes the creation of the Model. Here are some other things (you probably won't use most of the time).

Model Configuration

Config table name and PrimaryKey

Anima provides an annotation @Table to help you customize the table name and primary key above the class, such as the table name is user_info, the primary key is uid.

@Table(name = "user_info", pk = "uid")
public class User extends Model {
    private Integer uid;
}

Ignore Field

Sometimes we define some fields in Model. They are not fields in the database, so they are ignored. Otherwise, the data that is queried will be automatically mapped. This will cause an exception.

Anima provides @Ignore annotations. You can use them on fields. Remember that when your system has multiple annotations of the same name, the package is under io.github.biezhi.anima.annotation 😯.

Custom Field Name

In most cases, I will not use this operation, but it is inevitable that the table is not created by us, does not meet the specification. For example, if a field productname is encountered in the table, this field is productName in the field. However, if you do this, you will have problems and will match the field product_name, which is awkward. . .

Anima provides the @Column field to help correct these irregular operations.

@Column(name = "productname")
private String productName;

Get it! After understanding this, we can start operating the database, let's go ~