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.
}

如果我删除"唯一约束 = ..."。然后它似乎工作正常,但该属性不是唯一的。有什么想法可以解决这个问题吗?错误告诉我查看命名。我真的很想避免在我的所有财产上放置@Column或@JoinColumn(我知道这否则可以解决它)。我猜 hibernate 正在创建一个与属性不同的名称,因为它比仅将 String 作为属性更复杂,但我想避免将该信息存储在我的类中。

编辑:所有表都是由hibernate创建的,所以我不能进入数据库并仅查找列名。

卡车表中车牌号的列名是什么(在数据库中检查)?

@UniqueConstraint(columnNames = {"plateNumber"})

UniqueConstraint 具有 columnNames,因此它不必与您的属性名称相同。您使用什么命名策略?JPA 根据配置的命名策略创建表、列和其他对象的名称。默认情况下,应该使用SimpleNamingStrategy,在这种情况下它应该可以工作,因为结果列名应该是属性名称plateNumber。

最新更新