Java – Error in MyBatis while setting parameters

ibatisjavamybatispostgresql

I get this error when running select in MyBatis with PostgreSQL:

### The error may exist in data/mapper.xml
### The error may involve Transaccion.selectDeFraude-Inline
### The error occurred while setting parameters
### SQL: SELECT transaction_id, card_number, transaction_date, fraud FROM transactions.? ORDER BY card_number, transaction_date ASC;
### Cause: org.postgresql.util.PSQLException: ERROR: error de sintaxis en o cerca de «$1»

I get the error here, in the mapper.xml:

<select id="selectDeFraude" parameterType="String" resultMap="result">
    SELECT transaction_id, card_number, transaction_date, fraud FROM transactions.#{tabla} ORDER BY card_number, transaction_date ASC;
</select>

This is the method that calls the select:

public List<Transaccion> selectDeFraude(String tabla){

    SqlSession session = sqlSessionFactory.openSession();

    try {
        List<Transaccion> list = session.selectList("Transaccion.selectDeFraude", tabla);
        return list;
    } finally {
        session.close();
    }
}

If I replace #{tabla} with the name of the table it works just fine. None of the mapper methods work but all of them work if I replace the #{something} with the appropriate value.

Best Answer

It's not exactly the answer to the question but I got it working now. When mapping a table name with myBatis you should use ${table_name} instead of #{table_name}, and it should be an attribute of the object you passed as an argument.

I changed my code to look like this:

<select id="selectDeFraude" parameterType="Transaccion" resultMap="result">
    SELECT transaction_id, card_number, transaction_date, fraud FROM transactions.${tabla} ORDER BY card_number, transaction_date ASC;
</select>

And I added the property tabla to it and know is working just fine.