最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring boot - Retrieve Hibernate query based on java code - Stack Overflow

programmeradmin1浏览0评论

I need to implement a Spring Boot controller where each endpoint is supposed to retrieve the sql query of a java data fetch.

Example:

var users = entityManagerService.findTable("userTable").getRepository().findAllData();

I need for the hibernate query used to retrieve the data above to be return in the method.

How can I achieve that?

I need to implement a Spring Boot controller where each endpoint is supposed to retrieve the sql query of a java data fetch.

Example:

var users = entityManagerService.findTable("userTable").getRepository().findAllData();

I need for the hibernate query used to retrieve the data above to be return in the method.

How can I achieve that?

Share Improve this question edited Mar 13 at 12:29 seenukarthi 8,68410 gold badges50 silver badges74 bronze badges asked Mar 13 at 12:13 Diogo AlpendreDiogo Alpendre 301 silver badge8 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

1. Modify Your Service

Update your repository service to return the SQL query before execution.

import .hibernate.query.Query;
import .hibernate.Session;
import .springframework.stereotype.Service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;

@Service
public class EntityManagerService {

    @PersistenceContext
    private EntityManager entityManager;

    public String getGeneratedSQL(String tableName) {
        Session session = entityManager.unwrap(Session.class);
        Query<?> query = session.createQuery("FROM " + tableName);
        return query.getQueryString(); // This returns HQL, not raw SQL
    }
}

2. Create a Controller to Expose SQL Query

import .springframework.web.bind.annotation.GetMapping;
import .springframework.web.bind.annotation.RequestParam;
import .springframework.web.bind.annotation.RestController;

@RestController
public class QueryController {

    private final EntityManagerService entityManagerService;

    public QueryController(EntityManagerService entityManagerService) {
        this.entityManagerService = entityManagerService;
    }

    @GetMapping("/query")
    public String getQuery(@RequestParam String tableName) {
        return entityManagerService.getGeneratedSQL(tableName);
    }
}
发布评论

评论列表(0)

  1. 暂无评论