Home > Blockchain >  Spring Find By Like Feature
Spring Find By Like Feature

Time:03-06

I have a list of entities in my code (google.com, amazon.com, etc), and I would like to have my repository find an entity when I type feed it a string with a subdomain.

So basically, what repository function do I implement so I can run something like

public List<ValidDomainsEntity> findByCompanyDomainLike("www.google.com");

and have it return the entity with google.com in its

String companyDomain;

where the companyDomain = "google.com"

So in more layman's terms: My db contains URL's without the subdomain or prefix. What query do I use in spring's repository to find that URL when I put in a URL with a subdomain

Edit: Basically how I do the spring equivalent of

select * from valid_domains where 'www.amazon.com' LIKE CONCAT('%', companyDomain);

CodePudding user response:

You can write it in several ways. First option is writing a native query.

@Query(value = "select * from valid_domains where 'www.amazon.com' LIKE CONCAT('%', :companyDomain", nativeQuery = true);
public List<ValidDomainsEntity> myQuery(@Param("companyDomain") String companyDomain);

Second option is writing a simple non native Query and use your Entiry class names and fields. For this you purpose you can use javax.persistence.EntityManager or @Query(value = "", nativeQuery = false). By default @Query is non native query, you dont have to write nativeQuery = true. I show also an EntityManager example.

@Autowired //Constructor dependency injection is more preferred instead of @Autowired
private EntityManager entityManager;

List<ValidDomain> query = entityManager.createQuery("SELECT new ValidDomain(d.id, d.domainName) from ValidDomain d where 'www.amazon.com' LIKE CONCAT('%', :variableName)", ValidDomain.class).getResultList();

Or you can also use EntityManager, entityManager.createNativeQuery() for creating native query.

  • Related