在JPA中使用自定义类型的UniqueConstraint出错

时间:2016-03-08 14:06:03

标签: java hibernate 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正在创建一个与属性不同的名称,因为它比将String作为属性更复杂,但我想避免将这些信息存储在我的类中。

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

1 个答案:

答案 0 :(得分:0)

卡车表中的plateNumber列名是什么(检入DB)?

@UniqueConstraint(columnNames = {"plateNumber"})

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