Annotation Configuration
This article details the usage and properties of MyBatis-Plus annotations and provides source code links for deeper understanding. You can view the source code of the annotation classes via the link below.
@TableName
This annotation is used to specify the database table name that corresponds to an entity class. Use this annotation when the entity class name differs from the database table name, or when the entity class name is not the camelCase version of the table name.
@TableName("sys_user")public class User { private Long id; private String name; private Integer age; private String email;}
value
Type: String
Default value: ""
Specifies the database table name that corresponds to the entity class. Use this attribute to specify the correct table name when your entity class name differs from the table name.
schema
Type: String
Default value: ""
Specifies the database schema name. Typically, if your database does not use schemas to organize tables, you can leave this property empty.
keepGlobalPrefix
Type: boolean
Default: false
When you configure a global tablePrefix, this property determines whether to keep using the global table prefix. If you set this to true, the global table prefix will automatically be added even when you specify a table name in the annotation.
resultMap
Type: String
Default value: ""
Specifies the ID of the ResultMap defined in your XML file, which maps query results to a specific type of entity class object.
autoResultMap
Type: boolean
Default: false
Whether to automatically build a resultMap. If you have already configured a resultMap, this setting will not take effect.
excludeProperty
Type: String[]
Default: {}
Added in: @since 3.3.1
Specifies the property names to exclude during mapping. These properties will not be included in the generated SQL statements.
@TableId
This annotation marks the primary key field in your entity class. If your primary key field is named id
, you can omit this annotation.
@TableName("sys_user")public class User { @TableId private Long id; private String name; private Integer age; private String email;}
value
Type: String
Default value: ""
Specifies the primary key field name in the database table. If you don’t set this value, MyBatis-Plus will use the field name from your entity class as the primary key field name in the database table.
type
Type: Enum
Default: IdType.NONE
Specifies the primary key generation strategy.
IdType Enumeration Definitions
IdType.AUTO
: Uses the database’s auto-increment ID as the primary key.IdType.NONE
: No specific generation strategy. If there are IdType-related configurations in the global settings, it will follow those.IdType.INPUT
: You manually set the primary key value before inserting data.IdType.ASSIGN_ID
: Automatically assigns anID
, suitable for primary keys of typeLong
,Integer
, orString
. By default, this uses the snowflake algorithm implemented viaIdentifierGenerator
’snextId
method. @since 3.3.0IdType.ASSIGN_UUID
: Automatically assigns aUUID
, suitable forString
type primary keys. The default implementation usesIdentifierGenerator
’snextUUID
method. @since 3.3.0
@TableField
This annotation marks non-primary key fields in your entity class. It tells MyBatis-Plus how to map entity class fields to database table columns. If your entity field names follow camelCase naming conventions and match the database column names exactly, you can omit this annotation.
@TableName("sys_user")public class User { @TableId private Long id; @TableField("nickname") // Maps to database column "nickname" private String name; private Integer age; private String email;}
value
Type: String
Default value: ""
Specifies the column name in the database. Use this attribute to specify the correct database column name when your entity class field name differs from the database column name.
exist
Type: boolean
Default value: true
Indicates whether this field exists in the database table. If you set this to false, MyBatis-Plus will ignore this field when generating SQL.
condition
Type: String
Default value: ""
Specifies the conditional expression for a field when executing an EntityQuery. This allows you to customize how the field is compared in the WHERE clause. If a value is set for this property, it will be used; otherwise, the global default %s=#{%s}
is applied.
For specific syntax, refer to SqlCondition.
Example Explanation
Suppose we have a User entity class with three fields: id, name, and age. We want to query all users older than 18. We can use QueryWrapper to build this query by passing a User entity instance:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.SqlCondition;
// Entity class definition@TableName("sys_user")public class User { @TableId private Long id;
private String name;
@TableField(condition = "%s > #{%s}") // Custom condition expression for the age field private Integer age;
private String email;}
// Build query using EntityQuerypublic List<User> findUserAgeOver18() { // Create User instance for setting query conditions User queryEntity = new User(); queryEntity.setAge(18); // Set the value for the age field
// Create QueryWrapper instance and pass the User instance QueryWrapper<User> queryWrapper = new QueryWrapper<>(queryEntity);
// Execute the query List<User> userList = userMapper.selectList(queryWrapper);
return userList;}
In this example, we use the @TableField(condition = "%s > #{%s}")
annotation to set a custom condition expression for the age field. When building the query, we create a User instance and set the age field value to 18. We then use this instance to create the QueryWrapper, and MyBatis-Plus automatically generates the corresponding SQL query condition based on the annotations on the entity class.
When you execute the findUserAgeOver18
method, MyBatis-Plus generates an SQL statement similar to:
SELECT * FROM sys_user WHERE age > 18;
This approach allows the condition property to customize how fields behave during queries, making queries more flexible and tailored to specific requirements while avoiding the tedious task of manually writing SQL fragments.
update
Type: String
Default value: ""
Specifies the expression for a field in the SET clause during update operations. This property takes precedence over the el attribute, allowing you to customize the update logic for the field.
Example Explanation
Suppose you have a User entity class containing a version field, and you want to automatically increment the version field by 1 each time user information is updated. You can use the update attribute of the @TableField annotation to implement this functionality:
import com.baomidou.mybatisplus.annotation.TableField;
@TableName("sys_user")public class User { @TableId private Long id;
private String name;
private Integer age;
private String email;
@TableField(update="%s+1") // Custom expression for updates private Integer version;}
In this example, the @TableField(update="%s+1")
annotation tells MyBatis-Plus to use the expression version = version + 1
for the version field during update operations. This means that each time user information is updated, the version field value automatically increases by 1.
If you execute the following update operation:
User user = new User();user.setId(1L);user.setName("Updated Name");user.setAge(30);user.setEmail("updated@example.com");
userMapper.updateById(user);
MyBatis-Plus automatically generates SQL similar to:
UPDATE sys_userSET name = 'Updated Name', age = 30, email = 'updated@example.com', version = version + 1WHERE id = 1;
This approach allows you to customize field behavior during updates, making update operations more flexible and tailored to specific requirements, while avoiding the complexity of manually writing SQL fragments.
insertStrategy
Type: Enum
Default: FieldStrategy.DEFAULT
Defines how to handle field values when inserting new records. This property allows you to control whether a field should be included in the INSERT statement, and under what conditions.
FieldStrategy Enum Definition
- FieldStrategy.DEFAULT: Follows the global configuration strategy. If no global configuration is specified, the default behavior is to insert the field only when its value is not NULL.
- FieldStrategy.ALWAYS: Always insert the field, regardless of whether the field value is NULL.
- FieldStrategy.NOT_NULL: Insert the field only when its value is not NULL.
- FieldStrategy.NOT_EMPTY: Insert the field only when its value is not empty (for string types) or not NULL (for other types).
- FieldStrategy.NEVER: Never insert the field, even if the field value is not NULL.
- FieldStrategy.IGNORED: Ignore the check, equivalent to “ALWAYS” @Deprecated
Example Explanation
Suppose we have a User entity class containing a nickname field. We want to insert this field only when nickname is not empty when creating a new user. We can use the insertStrategy property of the @TableField annotation to achieve this:
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.FieldStrategy;
@TableName("sys_user")public class User { @TableId private Long id;
@TableField(insertStrategy = FieldStrategy.NOT_EMPTY) // Insert only when nickname is not empty private String nickname;
private Integer age;
private String email;}
In this example, the @TableField(insertStrategy = FieldStrategy.NOT_EMPTY)
annotation tells MyBatis-Plus to include the nickname field in the INSERT statement only when it’s not empty.
If we perform the following insert operation:
User user = new User();user.setNickname("John Doe");user.setAge(25);user.setEmail("john.doe@example.com");
userMapper.insert(user);
MyBatis-Plus will automatically generate an SQL statement similar to:
INSERT INTO sys_user (nickname, age, email)VALUES ('John Doe', 25, 'john.doe@example.com');
If the nickname field is empty, the generated SQL will not include the nickname field:
INSERT INTO sys_user (age, email)VALUES (25, 'john.doe@example.com');
This achieves the same effect as the following custom MyBatis XML configuration:
<mapper namespace="com.example.mapper.UserMapper">
<!-- Insert user --> <insert id="insertUser" parameterType="com.example.entity.User"> INSERT INTO sys_user ( <if test="nickname != null and nickname != ''"> nickname, </if> age, email ) VALUES ( <if test="nickname != null and nickname != ''"> #{nickname}, </if> #{age}, #{email} ) </insert>
</mapper>
This way, the insertStrategy property allows you to customize field behavior during insertion, making insert operations more flexible and tailored to specific requirements, while avoiding the complexity of manually writing SQL fragments.
updateStrategy
Type: Enum
Default: FieldStrategy.DEFAULT
Defines how to handle field values when updating records. This property allows you to control whether a field should be included in the SET clause of an UPDATE statement and under what conditions.
Refer to the insertStrategy property for more detailed information about the FieldStrategy enum type.
Example Explanation
Suppose we have a User entity class containing a nickname field. We want to always update the nickname field when modifying user information, regardless of whether its value is empty. We can use the updateStrategy property of the @TableField annotation to achieve this:
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.FieldStrategy;
@TableName("sys_user")public class User { @TableId private Long id;
@TableField(updateStrategy = FieldStrategy.ALWAYS) // Always update nickname, ignoring value checks private String nickname;
private Integer age;
private String email;}
In this example, the @TableField(updateStrategy = FieldStrategy.ALWAYS)
annotation tells MyBatis-Plus to always include the nickname field in the SET clause of the UPDATE statement when updating user information, ignoring any value checks.
If we execute the following update operation:
User user = new User();user.setId(1L);user.setNickname("Updated Nickname");user.setAge(30);user.setEmail("updated@example.com");
userMapper.updateById(user);
MyBatis-Plus will automatically generate an SQL statement similar to:
UPDATE sys_userSET nickname = 'Updated Nickname', age = 30, email = 'updated@example.com'WHERE id = 1;
Regardless of whether the nickname field’s value is empty, the generated SQL will include the nickname field. This means that even if the nickname field’s value is empty, the generated SQL will update the nickname field to NULL.
This approach allows the updateStrategy property to customize field behavior during updates, making update operations more flexible and suitable for specific requirements, while avoiding the complexity of manually writing SQL fragments.
whereStrategy
Type: Enum
Default: FieldStrategy.DEFAULT
Defines how to handle field values when generating the WHERE clause for update statements. This property allows you to control whether a field should be included in the WHERE clause and under what conditions.
Refer to the insertStrategy and updateStrategy properties for more detailed information about the FieldStrategy enum type.
Example Explanation
Suppose we have a User entity class containing a nickname field. We want the nickname field to be used as a condition in the WHERE clause only when it is not empty during user information updates. We can use the whereStrategy property of the @TableField annotation to achieve this:
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.FieldStrategy;
@TableName("sys_user")public class User { @TableId private Long id;
@TableField(whereStrategy = FieldStrategy.NOT_EMPTY) // Only use nickname in WHERE clause when not empty private String nickname;
private Integer age;
private String email;}
In this example, the @TableField(whereStrategy = FieldStrategy.NOT_EMPTY)
annotation tells MyBatis-Plus to include the nickname field in the WHERE clause only when it is not empty when generating update statements using whereEntity.
If we execute the following update operation:
User user = new User();user.setEmail("john.doe@example.com");
User whereEntity = new User();whereEntity.setNickname("John Doe");whereEntity.setAge(30);
// Use the whereEntity methodUpdateWrapper<User> updateWrapper = new UpdateWrapper<>(whereEntity);userMapper.update(user, updateWrapper);
MyBatis-Plus will automatically generate SQL similar to:
UPDATE sys_userSET email = 'john.doe@example.com'WHERE nickname = 'John Doe' AND age = 30;
If the nickname field is empty, the generated SQL will not include the nickname field:
UPDATE sys_userSET email = 'john.doe@example.com'WHERE age = 30;
This effect is equivalent to the following custom MyBatis XML configuration:
<mapper namespace="com.example.mapper.UserMapper">
<!-- Update user information --> <update id="updateUser" parameterType="com.example.entity.User"> UPDATE sys_user SET email = #{email} <where> <if test="nickname != null and nickname != ''"> AND nickname = #{nickname} </if> AND age = #{age} </where> </update>
</mapper>
Through this approach, the whereStrategy property allows you to customize field behavior in WHERE clauses, making update operations more flexible and tailored to specific requirements while avoiding the tediousness of manually writing SQL fragments. Refer to the insertStrategy and updateStrategy properties for more detailed information about the FieldStrategy enum type.
fill
Type: Enum
Default: FieldFill.DEFAULT
Field auto-fill strategy. This property specifies how to automatically populate field values during database operations (such as insert and update). By using the FieldFill enum, you can flexibly control field population behavior.
FieldFill Enum Definition
-
FieldFill.DEFAULT
: No automatic filling by default, relies on database default values or manual setting. -
FieldFill.INSERT
: Automatically populates the field value during insert operations. -
FieldFill.UPDATE
: Automatically populates the field value during update operations. -
FieldFill.INSERT_UPDATE
: Automatically populates the field value during both insert and update operations.
Example
Suppose you have a User entity class containing createTime and updateTime fields. You want to automatically populate the creation time when creating a user and automatically update the modification time when updating user information.
import com.baomidou.mybatisplus.annotation.FieldFill;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;import java.time.LocalDateTime;
@TableName("user")public class User { // Other fields...
@TableField(fill = FieldFill.INSERT) private LocalDateTime createTime;
@TableField(fill = FieldFill.UPDATE) private LocalDateTime updateTime;
// Constructors, getters, and setters...}
In this example, the createTime field will be automatically populated with the current time during insert operations, while the updateTime field will be automatically populated with the current time during update operations. This eliminates the need to manually set these time field values during every database operation.
Please note that for the auto-fill feature to work properly, you need to configure the appropriate auto-fill handler in your MyBatis-Plus configuration and ensure that the corresponding insert and update methods are defined in the Mapper interface for your entity class.
select
Type: boolean
Default value: true
Specifies whether the field should be included in SELECT statements during query operations. This attribute gives you granular control over which fields appear in query results.
Detailed Description
-
When the select attribute is set to true (the default value), the field will be included in query results.
-
When the select attribute is set to false, the field will be excluded from query results, even if it exists in the database table. This is useful for protecting sensitive data or optimizing query performance.
Example
Suppose you have a User entity class containing a password field. You want to exclude the password field from query results to protect user privacy.
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;
@TableName("user")public class User { // Other fields...
@TableField(select = false) private String password;
// Constructors, getters, and setters...}
In this example, when you execute a query operation, the password field will not be included in the SELECT statement and therefore won’t appear in query results. This ensures that even though passwords are stored in the database, they won’t be exposed during routine queries.
Note that the select attribute of the @TableField annotation only affects queries generated by MyBatis-Plus. It doesn’t impact other frameworks or manually written SQL statements. Additionally, when using fields with select = false, you need to pay special attention to data security and integrity when accessing these fields through custom queries or other methods.
keepGlobalFormat
Type: boolean
Default: false
Specifies whether to maintain the columnFormat rules defined in the global DbConfig when processing fields. This property controls whether field values apply global column formatting rules during database operations.
jdbcType
Type: JdbcType
Default: JdbcType.UNDEFINED
JDBC type, used to specify the data type of a field in the database. This property allows you to explicitly set the database type for a field to ensure compatibility with the database, especially when handling special types or custom types.
Detailed Description
-
When the jdbcType property is set to JdbcType.UNDEFINED (the default), MyBatis-Plus automatically infers the JDBC type based on the field’s Java type.
-
When the jdbcType property is set to a specific JdbcType enum value, the field will use the specified JDBC type for database operations. This can be used to resolve type mapping issues or when you need precise control over the database type.
Example
Suppose you have a CustomType entity class containing a field of custom type MyCustomType, and you want to store it in the database using a specific JDBC type.
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;import org.apache.ibatis.type.JdbcType;
@TableName("custom_type")public class CustomType { // Other fields...
@TableField(value = "my_custom_field", jdbcType = JdbcType.VARCHAR) private MyCustomType myCustomField;
// Constructors, getters, and setters...}
In this example, the myCustomField field will use the VARCHAR JDBC type for database operations. This way, even though MyCustomType is a custom type, it will be converted to VARCHAR type when stored in the database.
Note that the jdbcType property only needs to be set in specific cases, such as when there’s ambiguous mapping between Java types and database types. In most cases, MyBatis-Plus can automatically handle type mapping, so you don’t need to explicitly set jdbcType. Additionally, the jdbcType property only affects SQL statements generated by MyBatis-Plus and doesn’t impact other frameworks or manually written SQL statements.
typeHandler
Type: Class<? extends TypeHandler>
Default: UnknownTypeHandler.class
The type handler specifies how to handle specific field values during database operations. This property allows you to customize the conversion logic for field values to accommodate specific data types or business requirements.
Detailed Description
-
When the typeHandler property is not set (i.e., using the default value UnknownTypeHandler.class), MyBatis-Plus uses the default type handler to process field values.
-
When the typeHandler property is set to a specific TypeHandler subclass, the field will use the specified type handler for database operations. This is useful for handling custom types, special data formats, or non-standard database types.
Example
Suppose you have a User entity class with a birthDate field. You want to use a custom type handler to manage the date format, enabling the date to be stored in the database in a specific format.
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;import com.example.myproject.typehandler.CustomDateTypeHandler;import java.time.LocalDate;
@TableName("user")public class User { // Other fields...
@TableField(value = "birth_date", typeHandler = CustomDateTypeHandler.class) private LocalDate birthDate;
// Constructors, getters, and setters...}
In this example, the birthDate field uses the CustomDateTypeHandler for database operations. This means CustomDateTypeHandler will handle converting the date value from the database to a LocalDate object during queries, and converting the LocalDate object to a specific date format in the database during updates.
The CustomDateTypeHandler might be implemented as follows:
import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.time.LocalDate;import java.time.format.DateTimeFormatter;
public class CustomDateTypeHandler extends BaseTypeHandler<LocalDate> { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override public void setNonNullParameter(PreparedStatement ps, int i, LocalDate parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, parameter.format(FORMATTER)); }
@Override public LocalDate getNullableResult(ResultSet rs, String columnName) throws SQLException { String dateString = rs.getString(columnName); return (dateString != null) ? LocalDate.parse(dateString, FORMATTER) : null; }
// Implement other required methods...}
In this custom type handler, a DateTimeFormatter defines the date format, and the conversion logic for date values is implemented in the setNonNullParameter and getNullableResult methods.
Please note that for your custom type handler to take effect, you must ensure it is properly registered in the MyBatis-Plus configuration and can be loaded at runtime. Additionally, use custom type handlers carefully to ensure their correctness and performance. For more details, refer to the Field Type Handler documentation.
numericScale
Type: String
Default value: ""
Specifies the number of decimal places to retain. This property only takes effect during update operations. It controls the decimal precision for numeric type fields when updating.
Detailed Description
- When the numericScale property is set to an empty string (the default value), the field’s decimal precision will follow the database’s default settings or the settings defined when the field was created.
- When the numericScale property is set to a specific numeric value (such as “2”), the field will be processed with the specified number of decimal places during update operations.
Example Suppose you have a Product entity class containing a price field. You want to ensure the price retains two decimal places when updated.
import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableName;
@TableName("product")public class Product { // Other fields...
@TableField(value = "price", numericScale = "2") private BigDecimal price;
// Constructors, getters, and setters...}
In this example, the price field will ensure two decimal places are retained during update operations. This means that when updating the price, regardless of how many decimal places the input price value has, it will be formatted to two decimal places.
Please note that for the numericScale property to take effect, you must ensure your database supports the specified number of decimal places and that the numeric type field values are processed correctly during update operations. Additionally, the numericScale property only affects the SQL statements generated by MyBatis-Plus and does not affect other frameworks or manually written SQL statements.
@Version
This annotation marks a field in an entity class as an optimistic locking version number field. Optimistic locking is a concurrency control mechanism that assumes multiple transactions can proceed simultaneously without interfering with each other, only checking for conflicts when committing transactions. By using the @Version
annotation in your entity class, MyBatis-Plus automatically checks the version number during update operations to ensure the data hasn’t been modified by other transactions during the update process.
@TableName("sys_user")public class User { @TableId private Long id; @TableField("nickname") // Maps to database column "nickname" private String name; private Integer age; private String email; @Version // Marks as optimistic locking version number field private Integer version;}
In the example above, the version field is marked as the optimistic lock version number. When performing an update operation, MyBatis-Plus checks whether this field’s value matches the value in the database. If the values don’t match, it indicates that another transaction modified the data after it was read, and MyBatis-Plus throws an optimistic locking exception to alert you to handle the situation appropriately.
Using the @Version annotation effectively prevents data inconsistency issues during concurrent updates, improving your system’s concurrency performance and data integrity. You don’t need to manually write version checking code—MyBatis-Plus automatically handles this process for you.
@EnumValue
This annotation marks a field in an enumeration class to specify which value gets stored in the database. When a field in your entity class is an enum type, the @EnumValue
annotation tells MyBatis-Plus which property of the enum to use for database storage.
@TableName("sys_user")public class User { @TableId private Long id; @TableField("nickname") // Maps to the database column "nickname" private String name; private Integer age; private String email; private Gender gender; // Assume Gender is an enum type}
public enum Gender { MALE("M", "男"), FEMALE("F", "女");
private String code; private String description;
Gender(String code, String description) { this.code = code; this.description = description; }
@EnumValue // Specifies that the 'code' value is stored in the database public String getCode() { return code; }}
In the example above, the code
field in the Gender
enum is marked with @EnumValue
. This means when the gender
field of the User
entity is saved to the database, MyBatis-Plus will store the enum’s code
value (“M” or “F”) instead of the enum constant itself (MALE
or FEMALE
).
Using the @EnumValue
annotation gives you flexible control over how enum types are stored in the database, making the data more compact and easier to handle. It also simplifies the conversion process when reading enum values from the database, as MyBatis-Plus automatically converts the stored value back into the corresponding enum instance based on the @EnumValue
configuration.
@TableLogic
This annotation marks a field in your entity class as a logical delete field. Logical deletion is a data management strategy where records aren’t physically removed from the database. Instead, they are marked as deleted. By using the @TableLogic
annotation, MyBatis-Plus automatically handles the values for the logical delete field during query, update, and delete operations.
@TableName("sys_user")public class User { @TableId private Long id; @TableField("nickname") // Maps to the database field "nickname" private String name; private Integer age; private String email; @TableLogic(value = "0", delval = "1") // Logical delete field private Integer deleted;}
In the example above, the deleted
field is marked as the logical delete field. The value
attribute of the @TableLogic
annotation specifies the value for “not deleted” (0 in this case), and the delval
attribute specifies the value for “deleted” (1 in this case).
When you perform a query, MyBatis-Plus automatically filters out records marked as logically deleted and only returns active records. During an update operation, if the update would change the logical delete field to the “deleted” value, MyBatis-Plus automatically marks the record as deleted. When you perform a delete operation, MyBatis-Plus updates the logical delete field to the “deleted” value instead of physically removing the record.
Using the @TableLogic
annotation enables logical deletion of data, which helps maintain data integrity and traceability while avoiding the risk of data loss associated with physical deletion. You don’t need to write code for logical deletion manually, as MyBatis-Plus handles this process automatically.
@KeySequence
The @KeySequence
annotation specifies the name of a sequence in Oracle databases for generating primary key values in entity classes. In Oracle databases, primary keys are typically generated using sequences rather than auto-incrementing fields like in other databases. This annotation tells MyBatis-Plus to use a specific sequence for primary key generation.
@TableName("sys_user")@KeySequence("SEQ_USER_ID") // Specify sequence name as "SEQ_USER_ID"public class User { @TableId(type = IdType.INPUT) // Use sequence to generate primary key private Long id; @TableField("nickname") // Map to database column "nickname" private String name; private Integer age; private String email;}
In the example above, the @KeySequence
annotation is applied to the User
entity class and specifies the sequence name as “SEQ_USER_ID”. This means when inserting new records, MyBatis-Plus will use this sequence to generate values for the id
field.
The value
attribute of the @KeySequence
annotation specifies the sequence name, while the dbType
attribute specifies the database type. If you don’t specify dbType
, MyBatis-Plus will use the injected IKeyGenerator
implementation by default. If there are multiple IKeyGenerator
implementations, you must specify dbType
.
Using the @KeySequence
annotation ensures that primary key values are generated correctly in Oracle databases while simplifying the configuration process for primary key generation. You don’t need to manually write code to retrieve sequence values, as MyBatis-Plus automatically handles this process.
@InterceptorIgnore
This annotation specifies whether specific plugins (such as multi-tenancy) should be ignored when executing a particular method
(when annotated on the method) or all methods
(when annotated on the Mapper
).
// @InterceptorIgnore(tenantLine = "1") // Ignore the multi-tenancy interceptorpublic interface UserMapper extends BaseMapper<User> {
@InterceptorIgnore(tenantLine = "1") // Ignore the multi-tenancy interceptor List<User> selectUsers();}
In the example above, the multi-tenancy interceptor will be ignored when the selectUsers
method is executed.
Each plugin provided by MyBatis-Plus has a corresponding property in this annotation. For example, the multi-tenancy plugin uses the tenantLine
property. If the property value is “1”, “yes”, or “on”, the corresponding plugin will be ignored. If the property value is “0”, “false”, “off”, or empty, the plugin will execute normally.
For details on plugin usage, see the Plugin Main Body.
@OrderBy
This annotation is used to specify the default sorting method for entity class fields when performing query operations. By using the @OrderBy annotation on entity class fields, you can ensure that when executing queries, if no explicit sorting conditions are specified, MyBatis-Plus will return results according to the sorting rules defined in the annotation.
@TableName("sys_user")public class User { @TableId private Long id; @TableField("nickname") // Maps to database field "nickname" private String name; @OrderBy(asc = false, sort = 10) // Specifies default sorting as descending with priority 10 private Integer age; private String email;}
In the example above, the age field is marked with @OrderBy, with the asc attribute set to false (indicating default descending order) and the sort attribute set to 10 (indicating the priority of this sorting rule).
The asc attribute of the @OrderBy annotation specifies whether the sorting is ascending. If set to true, it indicates ascending order; if set to false, it indicates descending order. The sort attribute specifies the priority of the sorting rule - smaller numbers indicate higher priority, meaning they are applied first.
Note that the sorting rules defined by the @OrderBy annotation have lower priority than sorting conditions explicitly specified through the Wrapper condition query object during queries. If you specify sorting conditions in the Wrapper, the default sorting defined in the @OrderBy annotation will be overridden.
Using the @OrderBy annotation simplifies your code by avoiding the need to explicitly specify sorting conditions in every query. It also provides a default sorting method, which helps improve code readability and maintainability.