java - Hibernate 禁用默认行为

标签 java spring hibernate jpa hibernate-mapping

我的 Hibernate 在对列的调用进行假设时遇到问题。

具体来说,当我执行 @ManyToOne 字段时,我引用另一个表中的列。 发生的情况是,如果我也不输入 @JoinColumn 注释,它会映射名称中带有下划线的字段。

例如,我有这样的类(class):

@Entity
public class User extends AbstractEntity {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private int id;

     private String username;
     private String password;

     @OneToMany(fetch = FetchType.LAZY, mappedBy = "userFK")
     private List<TwitterAccount> twitterAccounts;

     /* GETTERS & SETTERS OMITTED */
}

然后我有 TwitterAccount 类:

@Entity
public class TwitterAccount extends AbstractEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne(fetch = FetchType.LAZY)
    private User userFK;
}

发生的情况是,当它尝试获取某个用户的 Twitter 帐户时,我收到异常:MySQLSyntaxErrorException:“字段列表”中的未知列“twitteracc1_.userFK_id”

看看它尝试将 userFK 映射到:userFK_id。当然不存在!我没有给它起这个名字。

所以问题归结为:是否可以关闭此功能?(将列名变成“field_'foreignkey”的功能)

我知道使用 @JoinColumn(name = "userFK") 可以解决这个问题,但我宁愿将其关闭。

问候

最佳答案

这是 JPA 规范指定的默认值

The concatenation of the following: the name of the referencing relationship property or field of the referencing entity or embeddable class; ""; the name of the referenced primary key column. If there is no such referencing relationship property or field in the entity, or if the join is for an element collection, the join column name is formed as the concatenation of the following: the name of the entity; ""; the name of the referenced primary key column.

在 hibernate 中,这是在 NamingStrategy 中实现的,在本例中是 EJB3NamingStrategy。您可以实现您自己的版本,决定您想要使用的任何版本。但这可能只会让人们变得复杂/困惑(他们可能期望标准适用)。

关于java - Hibernate 禁用默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20351054/

相关文章:

java.lang.ClassNotFoundException : com. sun.jersey.spi.service.ComponentProvider 异常

java - hibernate中特定的关系类型

java - 安卓 SIP : How to make audio call without using SIP address (I want to use real phone number instead)

java - 在mapstruct映射器中实现自定义行为的问题

java - Spring 通过 XML Beans 定义注册多个 Hibernate 数据源

java - 缓存不适用于 map

java - Hibernate Session.save() 不返回值?

java - Hibernate 加载延迟列表的延迟初始化异常

java - 将 PostgreSQL JSON 列映射到 Hibernate 实体属性

java - Spark 地理瓷砖加入