Java/mybatis

Mybatis 로그에 쿼리 찍히게 하기

바리새인 2025. 1. 28. 15:15

서비스 쿼리마다 작업해줘야 함

@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public List<User> getUsersOrderedBy(String columnName) {
        // Prepare parameters
        Map<String, Object> params = new HashMap<>();
        params.put("columnName", columnName);

        // Retrieve the mapped statement
        MappedStatement mappedStatement = sqlSessionFactory
                .getConfiguration()
                .getMappedStatement("com.example.mapper.UserMapper.getUsersOrderedBy");

        // Generate the BoundSql
        BoundSql boundSql = mappedStatement.getBoundSql(params);

        // Log the final SQL query
        String finalSql = boundSql.getSql();
        logger.info("Executing SQL: {}", finalSql);

        // Execute the query
        return userMapper.getUsersOrderedBy(columnName);
    }
}