自定義類型我有一個測試,看起來像這樣:誤差的UniqueConstraint在JPA
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
public class TestTruckRepository {
@Autowired
private TruckRepository truckRepository;
@Transactional
@Test
public void doIt(){
//omitted
}
}
的方法doIt方法()甚至沒有達到。我收到的錯誤是:
org.hibernate.AnnotationException: Unable to create unique key constraint (PlateNumber) on table Truck: database column 'plateNumber' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
這裏是一個錯誤是指的類:
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"plateNumber"}))
public class Truck implements Identifiable {
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.MERGE)
private PlateNumber plateNumber;
private String stuff;
@Id
@GeneratedValue
private Long id;
//Getter setter and constructor are omitted.
}
如果我刪除了「uniqueConstraints = ....」然後它似乎是工作很好,但財產不是唯一的。任何想法如何解決這個問題?錯誤是告訴我看看命名。我真的很想避免在我的所有屬性中放置@Column或@JoinColumn(我知道這會解決它)。我猜測hibernate正在創建一個與屬性不同的名稱,因爲它比只有一個字符串作爲屬性更復雜,但我想避免將這些信息存儲在我的類中。
編輯:所有表都是通過休眠創建的,所以我無法進入數據庫並查找列名。
您確定您希望某個特定的列是唯一的,但是不要爲將成爲此列的字段定義@Column。一個N-1將是一個FK,並且將有一個特定的名稱作爲默認值......並且它不會是「plateNumber」 –
定義@ Column根據我所知甚至不可能實際可行,我認爲我會選擇是@ JoinColumn,這迫使我指定字符串作爲列名。我寧願冬眠生成這些。 –
好好迂迴的註釋是JoinColumn但點是一樣的。您沒有定義自動生成的名稱,因此它會爲您生成,並且此自動生成的名稱不會是「plateNumber」,但您希望有一個名爲「plateNumber」的列。並沒有。所以這一切都崩潰了。所以定義它。你定義了一個字符串作爲Unique的列名,所以不明白這種沉默 –