注解异常 @Column(s) not allowed on a @ManyToOne property

@Column

计量单位类别中,要设置某个字段不能为空。

因为对Hibernate仅仅停留于了解阶段,去慕课网学习了一下Hibernate的注解。

clipboard.png

发现讲师介绍的@Column注解有一项nullable(可否为空)属性,默认为true,这里尝试着添加该注解,并将nullable属性设置为false,不可为空。

@ApiModelProperty("学科类别")
@ManyToOne
// 设置学科类别字段不能为空
@Column(nullable = false)
@JsonView({NoneJsonView.class,
        MeasurementUnitCategoryJsonView.getAllByDisciplineId.class})
private Discipline discipline;

异常

跑一下测试确保改这行代码整座桥不会塌。跑测试的时候却抛出了异常。

clipboard.png

org.hibernate.AnnotationException: @Column(s) not allowed on a @ManyToOne property: com.mengyunzhi.measurement.entity.MeasurementUnitCategory.discipline

大体的意思就是:注解异常,@Column注解不能应用在@ManyToOne的属性上。

话不多说,直接谷歌。

解决方案

打开第一条:Use @JoinColumn instead of @Column。使用@JoinColumn而不是@Column

@Column(s) not allowed on a @ManyToOne property-StackOverflow

大体意思就是,因为加了一个@ManyToOne的注解,所以这个属性就是外键。

package javax.persistence;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Column {

    String name() default "";

    boolean unique() default false;

    boolean nullable() default true;

    boolean insertable() default true;

    boolean updatable() default true;

    String columnDefinition() default "";

    String table() default "";

    int length() default 255;

    int precision() default 0;

    int scale() default 0;
}

解释

看一下@Column注解的源码,我们看到这其中的属性length等显示不是外键应该有的属性,所以推测@Column注解是用于数据表中的普通字段之上。

而在外键之上用一个不适用于其的注解,当然报错啦。而@JoinColumn注解才是官方为我们提供的为外键添加配置的注解。

@ApiModelProperty("学科类别")
@ManyToOne
// 设置学科类别字段不能为空
@JoinColumn(nullable = false)
@JsonView({NoneJsonView.class,
        MeasurementUnitCategoryJsonView.getAllByDisciplineId.class})
private Discipline discipline;

@Column修改为@JoinColumn,测试通过。

clipboard.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值