[英]java spring Long[] (array) type
如果我有下一个代码
/**
* Spring Data JPA repository for the Event entity.
*/
@Repository
public interface EventRepository extends JpaRepository<Event, Long>{
@Query("SELECT id, name FROM event WHERE id IN (:ids)")
List<EventItem> findEvents(@Param("ids") Long[] ids);
}
并想要使用它
Long[] ids = new Long[3];
ids[0] = new Long(1);
ids[1] = new Long(2);
ids[2] = new Long(3);
eventRepository.findEvents(ids);
如何正确使用。 我是Spring框架的初学者。 我想同时获取一些带有特殊ID的记录。
使用JPA @NamedQuery
即
事件实体
@Entity
@Table(name = "event")
@NamedQuery(name = "Event.fetchEventItem",
query = "SELECT id, name FROM event WHERE id IN (:ids)"
)
public class Event {
....
}
您的介面
@Repository
public interface EventRepository extends JpaRepository<Event, Long>{
List<EventItem> findEvents(Long[] ids);
}
接口实现类
@Repository
@Transactional(readOnly = true)
public class EventRepositoryImpl implements EventRepository {
@PersistenceContext
EntityManager entityManager;
@Override
public List<EventItem> findEvents(Long[] ids) {
List<Event> list = new ArrayList<Event>();
Query query = em.createNamedQuery("SELECT c FROM Country c");
Query query = entityManager.createNamedQuery("Event.fetchEventItem", Event.class);
query.setParameter(1, ids);
list = query.getResultList();
// Here You can Prapared List<EventItem>
}
}
JPA在方法名称内为您提供了关键字来执行此操作,因此在EventRepository类中,通过以下名称添加方法:
List<Event> findByIdIn(List<Long> ids);
您可以在方法名称内找到几个关键字,这些关键字仅按JPA提供的格式进行包装。
参考资料
表2.3方法名称中支持的关键字->
https://docs.spring.io/spring-data/jpa/docs/1.6.0.RELEASE/reference/html/jpa.repositories.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.