@Column
計量單位類別中,要設置某個字段不能爲空。
因爲對Hibernate
僅僅停留於瞭解階段,去慕課網學習了一下Hibernate
的註解。
發現講師介紹的@Column
註解有一項nullable
(可否爲空)屬性,默認爲true
,這裏嘗試着添加該註解,並將nullable
屬性設置爲false
,不可爲空。
@ApiModelProperty("學科類別")
@ManyToOne
// 設置學科類別字段不能爲空
@Column(nullable = false)
@JsonView({NoneJsonView.class,
MeasurementUnitCategoryJsonView.getAllByDisciplineId.class})
private Discipline discipline;
異常
跑一下測試確保改這行代碼整座橋不會塌。跑測試的時候卻拋出了異常。
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
,測試通過。