spring-data-jpa 如何从扩展类重写继承的@MappedSuperclass @Column可更新和可插入属性

ee7vknir  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(162)

在下面的设置中,如何使继承的producerId字段从Book中变为updatable = false, insertable = false

@MappedSuperclass
public class StockItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "producer_id")
    private Integer producerId;

}

@Entity
public class Producer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name")
    private Integer name;

}

@Entity
@Table(name = "stock_item")
public class Book extends StockItem {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "producer_id")
    private Producer producer;

    // make inherited producerId field updatable = false, insertable = false here

}

我特别不想执行以下操作,因为我需要该属性保持可更新和可插入,以供其他继承者使用:

@MappedSuperclass
public class StockItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "producer_id", updatable = false, insertable = false)
    private Integer producerId;

}

UPDATE:另一个约束是扩展@MappedSuperclass的所有类都表示同一个表

yrefmtwq

yrefmtwq1#

我发现的一个变通方法是在producer setter中设置producerId,但这不是一个理想的解决方案。

@Entity
public class Book extends StockItem {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "producer_id",  insertable = false, updatable = false)
    private Producer producer;

    public void setProducer(Producer producer) {
        setProducerId(producer.getId());
        this.producer = producer;
    }

    /**
        Setting producerId here directly may cause inconsistency between producer and inherited producerId, therefore method is overridden to be unusable.
    */
    @Override
    public void setProducerId(Integer producerId) {
        throw new UnsupportedOperationException("Inherited field producer cannot be set from Book");
    }

    @Override
    public Integer getProducerId() {
        return producer != null ? producer.getId() : null;
    }

}
a7qyws3x

a7qyws3x2#

根据Asoub的建议,我使用@AttributeOverride执行了以下操作,它工作得很好,因为它允许修改所有列属性:

@Entity
@Table(name = "stock_item")
@AttributeOverride(
        name = "producerId",
        column = @Column(name = "producer_id", insertable = false, updatable = false)
)
public class Book extends StockItem {

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "producer_id")
    private Producer producer;

}

相关问题