我有三个实体Country
,State
,City
。
@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=LAZY
和OneToMany
的{{1}}关系中使用State
时从未见过City
。
任何想法,这是什么问题?
这是输出:
state.getCities()