【问题标题】:Not able to fetch the data using manyToOne using Spring Data JPA无法使用 Spring Data JPA 使用 manyToOne 获取数据
【发布时间】:2017-02-02 19:44:11
【问题描述】:

我正在使用 Spring Data、JPA,但无法使用 manyToOne 关系获取数据。

我有 2 个实体 Employee、EmployeeTransferRequest。

@Entity
@Table(name = "employee_detail")
public class EmployeeDetail{

private Employee employee;

private Long empId;

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "emp_id", insertable = false, nullable = false,updatable = false)
    public Employee getEmployee() {
       return _student;
    }

    public void setEmployee(Employee employee) {
      this.employee = employee;
    }


    @Column(name = "emp_id", updatable = false)
    public Long getEmpId() {
       return empId;
    }


    public void setEmpId(Long empId) {
       this.empId = empId;
    }

    }
   @Entity
    @Table(name = "employee")
    class Employee
    {
        @Override
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = " emp_id")
        public Long getEmpId() {
            return _id;
            // Other Fields of Employee class ..
        }
    }

public interface EmployeeTransferRequestRepository extends JpaRepository<EmployeeTransferRequest, UUID>, QueryDslPredicateExecutor<EmployeeTransferRequest>
    {
        default EmployeeTransferRequest findOneUUID  transferRequestId) {
           return findOne(employeeTransferRequest.id.eq(transferRequestId);
        }
    }

我没有从Employee实体端映射EmployeeTransferRequest。只有uni-directional 来自EmployeeTransferRequest。

当我调用findOne 时,我可以从EmployeeTransferRequest 获取所有信息,但无法获取Employee 信息,获取null。

你能帮忙吗?

【问题讨论】:

  • 您是否尝试将 FetchType 从 LAZY 更改为 EAGER?
  • @melli-182,是的,我尝试将 LAZY 更改为 EAGER,但没有成功。
  • 请发布实际代码。此代码无法编译:大写类,缺少括号。您正在对 getter 进行注释,因此 hibernate 应该使用 setter 来填充值,但是由于没有,因此这是行不通的。但是...这不是您实际使用的代码...
  • @Jens Schauder,我已经做出了必要的更改以了解,请您现在检查一下
  • 请同时发布 EmployeeTransferRequest。如果您不在评论中的 @ 和我的名字之间添加空格,我会收到您正在与我交谈的通知。

标签: java hibernate jpa spring-data many-to-one


【解决方案1】:

这是因为您已将映射指定为insertable=false。这意味着当您创建传输请求时,关系不会被持久化,导致您以后查询请求时会出现null。

【讨论】:

  • 我没有使用Employee对象来持久化员工信息,为了持久化我使用empId属性,我已经更新了代码,请检查并建议。
猜你喜欢
  • 2020-03-11
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2019-11-18
  • 2020-08-24
  • 2017-01-31
  • 2019-03-16
相关资源
最近更新 更多