执行保存操作后使用Spring Data JPA无法获取父记录值

时间:2017-03-14 18:56:15

标签: spring spring-data spring-data-jpa

下面是映射表pojo。

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id", nullable = false, updatable = false)
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    @OneToMany(mappedBy = "user")
    private  Collection<Company>  companyList;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public Collection<Company> getCompanyList() {
        return companyList;
    }
    public void setCompanyList(Collection<Company> companyList) {
        this.companyList = companyList;
    }
}

@Entity
@Table(name = "company")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "company_id", nullable = false, updatable = false)
    private Long id;

    @Column(name = "company_name")
    private String companyName;

    @ManyToOne
    @JoinColumn(name="user_id")
    private User user;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCompanyName() {
        return companyName;
    }
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

}

以下代码将数据存储到公司表中。

        User user = new User();
        Company saveCompany = new Company();
        **user.setId(1L);**
        saveCompany.setUser(user);
        saveCompany.setCompanyName("test company18");

        **companyRepository.save(saveCompany);**

但是,当我调用下面的代码时,firstName的值显示为null。

        company = companyRepository.findCompanyByName("test company18");
        System.out.println("After new company test company:------" + company.getCompanyName());
        System.out.println("After new company test User Id:------" + company.getUser().getId());
        System.out.println("After new company test User FirstName:------" + **company.getUser().getFirstName()**);

获取FirstName值而不是null所需的更改。

提前致谢。

0 个答案:

没有答案