我有一个CrudRepository,应该使用数组(findByIn
)进行查询。在我的存储库测试中,它有效,但是当我尝试在服务中使用查询时,它不起作用。有人可以解释为什么它不起作用吗?这是我的设置(不包括与该问题无关的一些代码)
数据库模型:
@Entity
@Table(name="Place")
public class Place implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "placeId", nullable = false)
private Long placeId;
@Column(name = "owner", nullable = false)
private String owner;
public Long getPlaceId() {
return placeId;
}
public void setPlaceId(Long placeId) {
this.placeId = placeId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
仓库:
@Repository
public interface PlaceRepository extends CrudRepository<Place, Long> {
List<Place> findByPlaceIdIn(Long[] placeId);
}
服务(这是不起作用的部分):
@Service
public class PlaceService {
@Autowired
private PlaceRepository placeRepository;
public List<Place> getPlaces(Long[] placeIds) {
return placeRepository.findByPlaceIdIn(placeIds);
}
}
问题是,如果
placeRepository.findByPlaceIdIn(placeIds)
包含多个项目,则在我的服务中placeIds
返回0个对象。如果placeIds
仅包含一项,则查询工作正常。我尝试用这段代码替换return placeRepository.findByPlaceIdIn(placeIds)
,该代码对每个数组项进行一个一个的查询(这确实有效,但我想使查询正常工作): ArrayList<Place> places = new ArrayList<Place>();
for (Long placeId : placeIds) {
Long[] id = {placeId};
places.addAll(placeRepository.findByPlaceIdIn(id));
}
return places;
我知道该存储库应该可以工作,因为我对此有一个工作测试:
public class PlaceRepositoryTest {
@Autowired
private PlaceRepository repository;
private static Place place;
private static Place place2;
private static Place otherUsersPlace;
@Test
public void testPlacesfindByPlaceIdIn() {
place = new Place();
place.setOwner(USER_ID);
place2 = new Place();
place2.setOwner(USER_ID);
place = repository.save(place);
place2 = repository.save(place2);
Long[] ids = {place.getPlaceId(), place2.getPlaceId()};
assertEquals(repository.findByPlaceIdIn(ids).size(), 2);
}
}
我还为其他模型提供了另一个存储库,该存储库也使用
findByIn
并且工作正常。我看不到存储库之间的任何相关差异。我认为它可能会提供更多详细信息来显示工作库,因此在下面列出了它:数据库模型:
@Entity
@Table(name="LocalDatabaseRow")
@JsonIgnoreProperties(ignoreUnknown=false)
public class LocalDatabaseRow implements Serializable {
public LocalDatabaseRow() {}
public LocalDatabaseRow(RowType rowType) {
this.rowType = rowType;
}
public enum RowType {
TYPE1,
TYPE2
};
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@JsonProperty("id")
private Long id;
@JsonProperty("rowType")
@Column(name = "rowType")
private RowType rowType;
public Long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public RowType getRowType() {
return rowType;
}
public void setRowType(RowType rowType) {
this.rowType = rowType;
}
}
仓库:
@Repository
public interface LocalDatabaseRowRepository extends CrudRepository<LocalDatabaseRow, Long> {
List<LocalDatabaseRow> findByRowTypeAndUserIdIn(RowType type, String[] userId);
}
最佳答案
尝试使用列表代替:
findByPlaceIdIn(List placeIdList);