Spring Data JPA会在onetoone映射中找到从关联表中检索数据吗?

时间:2016-12-12 05:19:48

标签: spring-data-jpa

我正在使用Spring Data JPA。我有两个表如下:

投资和投资_类型。 Investment和Investment_Type之间存在一对一的关系。

我的投资类如下:

@Entity
public class Investment {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int investmentId;

@NotNull(message = "Cannot be empty")
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "investment_type_id")
private InvestmentType investmentType;

@NotNull(message = "Cannot be empty")
private String investmentNumber;

 //getter and setter methods


}

我的InvestmentType类如下:

@Entity
public class InvestmentType {

@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer investmentTypeId;

private String investmentTypeName;

//getter and setter methods
}

我的InvestmentRepository如下:

public interface InvestmentRepository extends JpaRepository <Investment, Integer>{

}

我的控制器有以下代码:

List<Investment> investments = investmentRepo.findAll();
    for(Investment investment:investments){
        logger.info(" Got investment with id "+investment.getInvestmentId());
        if(investment.getInvestmentType() != null){
            logger.info("Investment Type is "+investment.getInvestmentType().getInvestmentTypeName());
        }
        else{
            logger.info("null investment type ");
        }
    }

但是,for循环始终输出&#34; null投资类型&#34;

因此看起来findAll方法不会从具有OneToOne映射的InvestmentType表中检索数据。

我做错了吗?我是否需要做一些明确的事情才能从映射的相关表中检索数据?

1 个答案:

答案 0 :(得分:0)

一对一关联是唯一一个无法代理的关联。添加获取类型为lazy并在相关表colum上使用mappedby。

父表

@NotNull(message = "Cannot be empty")
@OneToOne(fetch = FetchType.LAZY, optional = false)
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "investment_type_id")
private InvestmentType investmentType;

相关表格

@Id @GeneratedValue(strategy=GenerationType.AUTO)
@OneToOne(mappedBy = "investment")
private Integer investmentTypeId;