Skip to content

Cannot use object properties correctly if SPRING_NAMED_PARAMETER #216

Description

@yu64

I using below version:

  1. org.mybatis.scripting:mybatis-thymeleaf:1.0.4
  2. org.springframework:spring-jdbc:6.0.9
  3. java 17

This issue occurs when using object properties with mb:p.

Probably because Spring JDBC does not allow you to specify properties of objects.

Exception thrown

java.lang.RuntimeException: org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'person.id': No value registered for key 'person.id'

This issue can be avoided by using mb:bind="person.id=${person.id}".

However, it cannot be used inside th:each. (Correctly, it will be overwritten by the value from the last loop.)

This causes the "Bulk insert" section of the document to fail.

The code is as follows.

Domain objects

public class Person {

        private String id;
        private String name;
        private String birthDate;

        public String getId() {
            return id;
        }
        public String getName() {
            return name;
        }
        public String getBirthDate() {
            return birthDate;
        }
}

Sql Template

INSERT INTO
    
    person

    VALUES(
        /*[# mb:p="person.id"/]*/,
        /*[# mb:p="person.name"/]*/,
        /*[# mb:p="person.birthDate"/]*/
    )

;

Creating SqlGenerator Method

public SqlGenerator createSqlGenerator() {

        SqlGeneratorConfig config = SqlGeneratorConfig.newInstanceWithCustomizer(c ->
            c.getDialect().setBindVariableRenderInstance(BindVariableRender.BuiltIn.SPRING_NAMED_PARAMETER)
        );

        return new SqlGenerator(config);
}

Run query Method

public int insert(String sqlTemplate, SqlGenerator gen, NamedParameterJdbcTemplate jdbc) {
        final Person person = new Person();
        person.id = "ID-001";
        person.name = "John Doe";
        person.birthDate = "2001-01-01"; 

        final Map<String, Object> params = new HashMap<>();
        params.put("person", person);

        System.out.println(params);

        final String jdbcSql = gen.generate(sqlTemplate, params, params::put);
        
        System.out.println(jdbcSql);
        System.out.println(params);

        return jdbc.update(jdbcSql, params);
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions