java - JPA 中自定义类型的 UniqueConstraint 错误

标签 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 创建的,因此我无法进入数据库并仅查找列名。

最佳答案

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

@UniqueConstraint(columnNames = {"plateNumber"})

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

关于java - JPA 中自定义类型的 UniqueConstraint 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869528/

相关文章:

java - 为什么我得到 javax.ejb.EJBTransactionRolledbackException? - setRollbackOnly

Java StringReader 就绪()

java - Spring数据Mongodb检索数据: @Document VO returns null

Hibernate (JPA) 级联 - 从 child 那里检索 id

java - 通过Spring Boot JPA + Postgresql + H2执行间隔

java - 'univ_orientation.dz.Entity.cursusGlobale.Student_idStudent' 上的 @OneToOne 或 @ManyToOne 引用未知实体 : int

java - 有哪些有趣、免费、开源的 Java 动态分析工具?

java - 使用 JFreeChart 在同一框架上显示多个图表

java - org.hibernate.exception.GenericJDBCException : could not execute statement in hibernate

java - Hibernate:我需要 flush() 吗?