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);
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744701351a4588796.html
评论列表(0条)