Spring数据jpa - 为什么生成的SQL包含未在Entity字段中的未知列?

问题描述 投票:0回答:1

我跟随this blog by Vlad在我的两个实体UserJobProfile的b / w中实现一对一的关系

@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "user_id", unique = true, nullable = false)
    private Integer userId;

    @Column(name = "unique_id", unique = true, length = 45, updatable = false)
    private String uniqueId;

    @Column(name = "email", unique = true, length = 45, updatable = false)
    private String email;
}


@Entity
@Table(name = "job_profile")
public class JobProfile  {

    @Id
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private User user;

    @Column(name = "is_looking_job")
    private Boolean isLookingJob;


}

想法是,我的客户将为用户发送工作细节。数据(我为了简单而减少了)就像:{“isLookingJob”:true}

控制器将负责为用户创建JobProfile

public void saveUserExperience(Principal principal, @RequestBody UserExperienceDto experienceDto) {
        User user = userService.findByEmail(principal.getName());       

        JobProfile jobProfile = new JobProfile();
        jobProfile.setUser(user);

        JobHistory jobHistory = new JobHistory();
        jobHistory.setIsLookingJob(experienceDto.getIsWilling())

        jobProfileDao.save(jobProfile);


    }

JobProfileDao是一个Spring-Data-Jpa接口。

public interface JobProfileDao extends JpaRepository<JobProfile, Integer> {

}

所以,这里的保存操作是生成错误的SQL命令(insert into job_profile (is_looking_job, is_willing, user_user_id) values (?, ?, ?)),因此给出错误could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement

我很困惑地看到user_user_id列生成的地方。

我正在为我的项目使用Spring-data-Jpa + Hibernate的Spring启动。

hibernate spring-boot jpa spring-data-jpa
1个回答
1
投票

你在@JoinColumn字段上缺少JobProfile.user,因此hibernate使用user_user_id(基于字段名称和User中PK列的名称)

事实上,the article you mention有以下注释

如果要在使用@MapsId时自定义主键列名称,则需要使用@JoinColumn批注。有关更多详细信息,请查看此文章。

How to change the @OneToOne shared primary key column name with JPA and Hibernate

© www.soinside.com 2019 - 2024. All rights reserved.