An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
September 17, 2021 10:03 am GMT
Original Link: https://dev.to/codever/sql-select-with-in-clause-from-list-with-jpa-1g41
SQL Select with IN clause from list with JPA
The native SQL query we want to map in JPA is similar to the following:
SELECT * FROM PARTNER where PARTNER_NUMBER IN ('id1', 'idn').
With JPA you can use a TypedQuery
for example and set the expected list of the IN
clause directly as query parameter
@Statelesspublic class PartnerDataRepository { @Inject private EntityManager em; public List<PartnerData> findPartnerDataFromList( List<String> partnerNumbers) { TypedQuery<PartnerData> query = em.createNamedQuery( PartnerData.FIND_PARTNER_DATA_IN_LIST, PartnerData.class); query.setParameter(PartnerData.PARTNER_NUMBERS, partnerNumbers); return query.getResultList(); }}
In the named query itself you can pass the parameter with :
as you would when setting a "normal" parameter:
@Entity@Access(AccessType.FIELD)@Inheritance(strategy = InheritanceType.SINGLE_TABLE)@Table(name = PartnerData.TABLE_NAME)@NamedQueries({ @NamedQuery( name = PartnerData.FIND_PARTNER_DATA_IN_LIST, query = "select m from PartnerData m where partnerNumber in :partnerNumbers")})public class PartnerData { public static final String TABLE_NAME = "PARTNER"; public static final String PARTNER_NUMBERS = "partnerNumbers"; public static final String FIND_PARTNER_DATA_IN_LIST = "findPartnerDataWithPartnerNumbers"; //... rest ignored for brevity}
Shared from Codever. use the copy to mine functionality to add it to your personal snippets collection.
Original Link: https://dev.to/codever/sql-select-with-in-clause-from-list-with-jpa-1g41
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To