Is there any method that we can use to run our custom SQL queries passed as string in spring hibernate?

Viewed 138

I am new to spring framework and hibernate. I learned HibernateTemplate class functions like save(), update(), delete(), load(), loadAll() etc. In all these functions we are doing only reading, updating, deleting, updating functions only. In SpringJdbc we can execute our custom SQL queries(as string) also using functions like query or execute but in hibernate with spring, I am not able to see any method that we can use to run our custom query and get the result as list of persistent objects. Is there any way by which we can do it in spring hibernate?

2 Answers

Hibernate is just an ORM implementation. ORM = Object-relational-mapping .

Therefore Hibernate only does what it was created to do. Create the link between java objects and database objects

Also Hibernate is just an implementation that is used by default from Spring. You could as well chose another implementation. You normally call spring methods which then get executed by Hibernate.

If you use Spring Jpa you can find many methods to achieve that. One of them are Native Queries in repositories.

Example

@Repository
public interface CarRepository extends CrudRepository<Car, Long>, PagingAndSortingRepository<Car, Long> {
 
    @Query(value="select * from car a where a.model= :model", nativeQuery=true)
    List<Car> getCarsByModel(String model);
}

yes like Boug says you can customized and use a lot of different approaches. you can also create NamedQuery on top of your entity like below:

@NamedQuery(
            name = "EntityA.findAllWithName",
            query = "SELECT a FROM EntityA a where a.name= :name")
@Entity
public class EntityA{

  @Id  
  private UUID id;
  private String name;
}

and then you can use it wherever you need like:

public void method(String name){
  Query query=entityManager.createNamedQuery(EntityA.findAllWithName);
  query.setParameter("name",name);
  
  List<EntityA> results=quety.getResultList();
}
Related