我有一個LAZY OneToOne關係, ,我想加載它每次使用(相同的模型有更多的OneToOne關係,我想做更少的查詢到數據庫。)Spring JPA LAZY加載OneToOne關係不會加載
看着日誌文件中的本地數據庫查詢,我可以看到當我不試圖訪問user.city
時SELECT FROM City...
語句不打印。
但是當訪問user.city
我可以看到在日誌中運行的SQL語句,我正在獲取類實例。但都充滿了City
實體是null
裏面,見下面的詳細信息:
驗證碼:
System.out.println(user.city);
System.out.println(user.city.location);
將打印
Hibernate:
select
city0_.id as id1_3_0_,
city0_.accentName as accentNa2_3_0_,
city0_.location as location3_3_0_,
city0_.name as name4_3_0_,
city0_.state_id as state_id5_3_0_
from
City city0_
where
city0_.id=?
[email protected]
null
古都是我的模型:
@Entity
@Table(
indexes={@Index(name = "name", columnList="name")}
)
public class City {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
public State state;
public String name;
public String accentName;
@Column(name = "location", columnDefinition = "POINT")
public Point location;
}
@Entity
@Table(
name="User"
)
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula("'User'")
@JsonAutoDetect
public abstract class BaseUser {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long id;
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@OneToOne(fetch = FetchType.LAZY)
public City city;
...
}
僅舉與@OneToOne(fetch = FetchType.EAGER)
測試此,當一切都工作正常..
非常感謝你的幫助。
是否存在遺漏setter或@Entity(access = AccessType.FIELD)的問題? – maszter
@maszter我的字段是公開的,你的意思是'r @Entity(access = AccessType.FIELD)是一個問題嗎?' –