0

The variable in the request in the mybatis mapper is not replaced. In the case of "select" queries, everything is fine, but I need to be able to create a table by name.

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface TableMapper {
    @Update("""
        create table if not exists #{name}
        (table_name varchar(50) NOT NULL,
        update_date varchar(20) NOT NULL)
        """)
    void createTableByName(@Param("name") String name);
}

What am I doing wrong? Or is this approach not possible when using mybatis?

In logs:

The error occurred while setting parameters
SQL: create table if not exists ? (table_name varchar(50) NOT NULL, update_date varchar(20) NOT NULL)

The variable passed to the method is neither empty nor null.

The list of fields in the table itself is not important, only the possibility of creating a table by a given name.

  • 2
    You cannot use placeholder for a table name [1](https://stackoverflow.com/a/11312274/1261766). You must use `${}` instead. Be sure to sanitize the value to avoid SQL injection. cf. [FAQ](https://github.com/mybatis/mybatis-3/wiki/FAQ#what-is-the-difference-between--and-) – ave Dec 17 '22 at 20:19
  • Thank you from the bottom of my heart!!! What does the choice of #{} or ${} depend on? In the documentation, I saw only #{} everywhere. – Руслан Кузнецов Dec 17 '22 at 20:26
  • 1
    You're welcome :) You should use `#{}` whenever possible because it's safe against SQL injection. `${}` is necessary for table/column names, basically. – ave Dec 17 '22 at 20:46

0 Answers0