admin管理员组文章数量:1391977
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 badges1 Answer
Reset to default 11. 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);
}
}
本文标签: spring bootRetrieve Hibernate query based on java codeStack Overflow
版权声明:本文标题:spring boot - Retrieve Hibernate query based on java code - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744701350a2620582.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论