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

I need to implement a Spring Boot controller where each endpoint is supposed to retrieve the sql query

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);
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744701351a4588796.html

相关推荐

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

    I need to implement a Spring Boot controller where each endpoint is supposed to retrieve the sql query

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信