MyBatis 实体类映射:如何忽略字段?
在 MyBatis 中,使用 ' @Transient' 注解可以忽略实体类中的特定字段,使其不参与数据库表的映射。
使用 @Transient 注解忽略字段
以下示例代码展示了如何使用 @Transient 注解来忽略 password 字段:
public class User {
private Long id;
private String username;
@Transient
private String password;
// 省略getter和setter方法
}
在上述代码中,使用 @Transient 注解标注了 password 字段,表示该字段不参与数据库表的映射。在进行数据库操作时,MyBatis 会忽略该字段。
引入 javax.persistence 依赖
需要注意的是, @Transient 注解来自 javax.persistence 包,因此需要在项目中引入对应的依赖,例如:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
使用注解配置方式忽略字段
如果你使用的是注解配置方式,也可以使用 @Transient 注解来忽略某个字段。以下示例代码展示了如何使用注解配置方式来忽略 password 字段:
@Table(name = "user")
public class User {
@Id
private Long id;
private String username;
@Transient
private String password;
// 省略getter和setter方法
}
在上述代码中,使用了 @Table 注解来指定表名,并使用 @Id 注解标注了主键字段。同时,使用 @Transient 注解标注了 password 字段,表示该字段不参与数据库表的映射。
原文地址: https://www.cveoy.top/t/topic/pJKN 著作权归作者所有。请勿转载和采集!