有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate禁用默认行为

我的Hibernate在假设要调用什么列时遇到了问题

具体来说,当我在@manytone字段中引用另一个表中的一列时。 结果是,如果我没有输入@JoinColumn注释,它会在字段名称中映射一个下划线

例如,我有一门课:

@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: Unknown column 'twitteracc1_.userFK_id' in 'field list'

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

所以问题归结为:是否可以关闭此功能(将列名转换为'field_u'foreignkey'的功能)

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

问候


共 (1) 个答案

  1. # 1 楼答案

    这是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。你可以实现你自己的版本,决定你想用什么。但这可能只会让人们变得复杂/困惑(人们可能希望这些标准适用)