Basic usage of MyBatis-@TableField

MyBatis Plus is a powerful persistence layer framework that provides many convenient annotations and configurations, including @TableFieldannotations for configuring field mapping.

@TableField annotation

@TableFieldAnnotations are used to configure field mapping information, and can be used to specify attributes such as database field names and field strategies in entity classes.

basic usage

import com.baomidou.mybatisplus.annotation.TableField;

public class User {
    
    
    @TableField("user_name")
    private String username;
    
    // 省略其他字段和方法
}

In the above code, @TableField("user_name")the annotation specifies usernamethe database field name corresponding to the field user_name.

Detailed attribute

@TableFieldAnnotations have the following common properties:

  • value: specifies the column name of the field in the database, and expressions can be used.
  • exist: Specifies whether the field is a field in the database table, the default is true.
  • fill: The specified field is an auto-fill field, and the optional values ​​are FieldFill.DEFAULT, FieldFill.INSERT, and FieldFill.UPDATEso on.
  • select: Specifies whether to query when the field is queried, the default is true.
  • condition: Specify the condition of the field during update operation, the default is an empty string.

complete example

  1. Entity class
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;

public class User {
    
    
    @TableField(value = "user_name", exist = true, fill = FieldFill.DEFAULT, select = true, condition = "")
    private String username;
    
    // 省略其他字段和方法
}
  1. configuration file

In the configuration file of MyBatis Plus (for example mybatis-config.xml), @TableFieldsupport for annotations needs to be added:

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    <typeAliases>
        <package name="com.example.entity" />
    </typeAliases>
</configuration>
  1. quote
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

public interface UserMapper extends BaseMapper<User> {
    
    
}

public class UserService extends ServiceImpl<UserMapper, User> {
    
    
}

In the above code, UserMapperit is a custom Mapper interface, which is inherited from BaseMapper; UserServiceit is a custom Service class, which is inherited from ServiceImpl.

In this way, we can perform database operations through UserMapperand UserService, and @TableFieldthe configuration in the annotation will also take effect.

The above is @TableFieldthe basic usage and configuration instructions of the annotation, I hope it can be helpful to you!

Guess you like

Origin blog.csdn.net/qq_41177135/article/details/131961516