Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to force a no-argument constructor #2276

Closed
junglechange opened this issue Jun 28, 2021 · 5 comments
Closed

how to force a no-argument constructor #2276

junglechange opened this issue Jun 28, 2021 · 5 comments

Comments

@junglechange
Copy link

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

@harawata
Copy link
Member

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.

@h3adache
Copy link
Member

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.

@junglechange
Copy link
Author

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'}]

@harawata
Copy link
Member

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
Copy link
Member

harawata commented Mar 8, 2023

No response. Closing.

@harawata harawata closed this as completed Mar 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants