Spaceship222
Spaceship222

Reputation: 849

Spring Boot: Autowired mapper fails

I am new to spring boot and mybatis. I create a repo which has structure:

main
    java
        com
           ssm
              controller
                  UserController.java
              mapper
                  UserMapper.java # can generated by mybatis generator
              dao
                  UserDao.java # which extends interface UserMapper
              model
                  User.java
              service
                  UserService.java
                  UserServiceImpl.java
              UserSpringBootApplication.java
                   
    resources
        com
           ssm
              xml
                 UserMapper.xml
                 UserDao.xml
        static
        templates
        application.properties
        mybatis-config.xml

In file UserSpringBootApplication.java, its content is

@SpringBootApplication
public class UserSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserSpringBootApplication.class, args);
    }

}

In file UserDao.java:

@Mapper
public interface UserDao extends UserMapper {


   // example
   @ResultMap("Record")
   @Select("select * from UserTable")
   List<User> getAllRecords();
}

In file UserMapper.java:

@Mapper
public interface UserMapper

In file application.properties:

# database config
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.datasource.username=root
spring.datasource.password=xxxxxx

# mybatis
mybatis.config-location=classpath:mybatis-config.xml

In file UserServiceImpl.java, I try to autowire UserDao. But when running application, it gives me error: Field UserDao in com.ssm.service.UserServiceImpl required a bean of type 'com.ssm.dao.UserDao' that could not be found.

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
     
    // ...
}

Thanks a lot!

Upvotes: 1

Views: 3678

Answers (1)

Arie
Arie

Reputation: 178

EDIT: This is only a solution for MapStruct, the real solution is in the comments!

You should user the @Mapper annotation like this:

@Mapper(componentModel = "spring")

From the javadoc:

spring: the generated mapper is a Spring bean and can be retrieved via @Autowired

See: https://mapstruct.org/documentation/stable/api/org/mapstruct/Mapper.html

Upvotes: 3

Related Questions