mybatis-3 icon indicating copy to clipboard operation
mybatis-3 copied to clipboard

how to force a no-argument constructor

Open junglechange opened this issue 4 years ago • 4 comments

When the order of the sql statement columns and the parameter list of the constructor are not the same, it is easy to make mistakes with the parameter constructor

https://github.com/mybatis/mybatis-3/blob/7f783984692b146154de5b37d351c17f1c904ded/src/main/java/org/apache/ibatis/executor/resultset/DefaultResultSetHandler.java#L720

junglechange avatar Jun 28 '21 17:06 junglechange

Hello @junglechange ,

Sorry, I couldn't understand what you mean. Please provide a test case or demo project like these so that we can reproduce the problem on our end.

harawata avatar Jun 28 '21 18:06 harawata

If you are trying to make it always use the no arg constructor then use the AutomapConstructor annotation. Or simply do not use constructor mapping.

h3adache avatar Jun 29 '21 01:06 h3adache

create table user ( name varchar(32), info varchar(32) ); insert into user(name, info) VALUES ('hello', 'world');

static class User {
    private String info;
    private String name;

    public User(String info, String name) {
        this.info = info;
        this.name = name;
    }

    public String getInfo() {
        return info;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" +
                "info='" + info + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

@Mapper
interface UserMapper {
    @Select("select name,info as abc from user")
    List<User> findAll();
}

call UserMapper.findAll

Expected result

[User{info=null, name='hello'}]

Actual result

[User{info='hello', name='hello'}]

junglechange avatar Jun 29 '21 02:06 junglechange

Your User class does not have a no-arg constructor. MyBatis (or anyone) cannot call a constructor that does not exist.

Any of the following should resolve your problem.

  1. Add the no-arg constructor
  2. Use a result map with <constructor /> or @ConstructorArgs
  3. Change the result column order to name, info

There also is an ongoing discussion about an enhancement to use argument names for mapping. See #2192 #2196

harawata avatar Jun 29 '21 17:06 harawata

No response. Closing.

harawata avatar Mar 08 '23 23:03 harawata