为什么即使使用@OneToMany LAZY加载,子实体也仍会得到不需要的select语句?

时间:2019-04-29 20:31:14

标签: hibernate spring-boot spring-data-jpa

我有三个实体CountryStateCity

@Data
@Entity
@Table(name = "country", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }) })
public class Country {

    @Id
    @Column(name = "country_id")
    private int countryId;

    @Column(name = "name", length = 45)
    private String name;

    @Column(name = "phonecode", length = 45)
    private int phoneCode;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "country_id")
    private Set<State> states;
}

@Data
@Entity
@Table(name = "state")
public class State {

    @Id
    @Column(name = "state_id")
    private int stateId;

    @Column(name = "name", length = 45)
    @NotBlank
    private String name;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "state_id")
    private Set<City> cities;

}

@Data
@Entity
@Table(name = "city")
public class City {

    @Id
    @Column(name = "city_id")
    private int cityId;

    @Column(name = "name", length = 45)
    private String name;

}

这是它们之间的联系:
Country 1:N State State 1:N City

我正在使用Spring框架,因此对于我的DAO,我正在使用JpaRepository for CRUD

public interface CountryDao extends JpaRepository<Country, Integer>{}

这是我试图让该国所有城市的Id = 101的测试用例

@Autowired
private CountryDao countryDao;

@Test
@Transactional
public void getAllStateWithCountryName() {
    Country country = countryDao.findById(101).orElseThrow(() -> new EntityNotFoundException());
    System.out.println("country: " + country.getName());
    country.getStates().forEach((state) -> System.out.println("state: " + state.getName()));
}

该测试确实为我带来了城市数据,但我看到为select实体生成了一些不需要的City语句。当我在FetchType=LAZYOneToMany的{​​{1}}关系中使用State时从未见过City

任何想法,这是什么问题?

这是输出:

state.getCities()

0 个答案:

没有答案