spring数据jdbc-@column注解在setter上不起作用

gwbalxhn  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(421)

我需要在fetch上转换实体的字段,根据这个官方示例,我尝试用customsetter来实现这一点:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;

@Table("entity")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(builderClassName = "EntityBuilder")
public class Entity {

    @Id
    private String someId;

    @Transient
    private String entityName;

    @Column("entity_name")
    public String getEntityNameUnmodified() {
        return this.entityName;
    }

    @Column("entity_name")
    public void setEntityNameUnmodified(String em) {
        this.entityName = em + " Some modification";
    }
}

但这完全不起作用,结果我 EntityentityName == null .
我下载了github示例并在本地运行,一切正常。我的代码怎么了?

p3rjfoxz

p3rjfoxz1#

我的代码不工作,因为丢失了 @AccessType(AccessType.Type.PROPERTY) 注解。
工作方案:

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.springframework.data.annotation.AccessType;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;

@Table("entity")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(builderClassName = "EntityBuilder")
@AccessType(AccessType.Type.PROPERTY) // IMPORTANT !!!
public class Entity {

    @Id
    private String someId;

    @Transient
    private String entityName;

    @Column("entity_name")
    public String getEntityNameUnmodified() {
        return this.entityName;
    }

    @Column("entity_name")
    public void setEntityNameUnmodified(String em) {
        this.entityName = em + " Some modification";
    }
}

问题是springdatajdbc默认情况下使用字段作为实体列的访问器,如果没有字段,则忽略注解setter和getter。启用“property”访问类型可以解决这个问题。

相关问题