简体   繁体   中英

How execute native SQL queries using Spring in runtime in Java?

So, are there any methods to execute native SQL queries from Repository interface?

Yes, I know about @Query annotation, but how to execute queries that can be changed in runtime? Like in JDBC executeQuery() method?

Implement JpaRepository and use

@PersistenceContext
private EntityManager em;

to use the full power of Java to create query of type string and then:

 final Query emQuery = em.createNativeQuery(query);
 final List<Object[]> resultList = emQuery.getResultList();

If you mean using Spring Data you could do something like :

@Query(value = "SELECT p from Person p where r.name = :person_name")
Optional<Person> findPersonByName(@Param("person_name") String personName);

You can use native query as well :

@Query(value = "select * from person p where r.name = :person_name")", nativeQuery = true)
enter code here

You can use a Specification with your JpaRepository to make a dynamic query built at runtime.

Add JpaSpecificationExecutor to your JpaRepository interface...

@Repository
public interface MyRepo extends JpaRepository<MyEntity, Long>, JpaSpecificationExecutor {
}

Then make a class with a static method that returns a Specification....

public class MyEntitySearchSpec {
  private MyEntitySearchSpec() {
    // Remove this private constructor if need to add public non-static methods.
  }

  public static Specification<MyEntity> myEntitySearch(
      final mysearchCriteria MySearchCriteria) {
    return (root, query, cb) -> {
      List<Predicate> predicates = new ArrayList<>();

      if (mysearchCriteria.isOnlyActive()) {
        predicates.add(cb.isNull(root.get("closeDate")));
      }

      if (mysearchCriteria.getCaseNumber() != null) {
        predicates.add(cb.equal(root.get("caseNumber"),
            mysearchCriteria.getCaseNumber()));
      }

      return cb.and(predicates.toArray(new Predicate[] {}));
    };
  }
}

The you can call like this...

myRepo.findAll(myEntitySearch(mysearchCriteria));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM