java – How to connect MongoDB with Spring Boot through MongoTemplate?

I am using Java 17, Spring Boot 2.7 with MongoDB. I want to connect MongoDB with the help of MongoTemplate ? But I receives only null.

If I use MongoRepository & @Document, this record class becomes dedicated to MongoDB, which I don’t want. I am using JdbcDaoImpl in this program also to connect with MySql.

My UI Class

@Getter
public class Lv {
    private final String employeeCode;
    private final int applicationNumber;

    public Lv(
            @Size(max = 5, message = "Employee Code Must Be Within 4 To 5 Character Long Or Blank")
        @JsonProperty("employeeCode") String employeeCode,
            @Range(min = 0, max = 9999, message = "Application Number Must Be Within 9999 Or Zero")
        @JsonProperty("applicationNumber") int applicationNumber) {
        this.employeeCode = employeeCode;
        this.applicationNumber = applicationNumber;
    }
}

My Record Class

record Leave (
    String employeeCode,
    int applicationNumber,
    String leaveType,
    LocalDate startDate,
    LocalDate endDate) {
}

My Repo

public interface AttendanceRepo {
    List<Leave> selectLeaveApplication(Lv lv);
}

@Repository("attendanceMongo")
public class AttendanceRepoMongo implements AttendanceRepo {

    private final MongoTemplate mongoTemplate;

    @Autowired
    public AttendanceRepoMongo(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public List<Leave> selectLeaveApplication(Lv lv) {
        final Query query = new Query();
        query.addCriteria(Criteria.where("projcd")
                        .is("84"));
        query.fields()
                .exclude("_id");
        return mongoTemplate.findAll(Leave.class, "leave").stream()
                .filter(elements ->
                        lv.employeeCode().trim().length() <= 0 ||
                                elements.employeeCode().equalsIgnoreCase(lv.employeeCode()))
                .filter(elements ->
                        lv.applicationNumber() <= 0 ||
                                elements.applicationNumber() == lv.applicationNumber())
                .collect(Collectors.toList());
    }
}

My Service

public interface AttendanceService {
    List<Leave> selectLeaveApplication(Lv lv);
}

@Service("attendanceService")
public class AttendanceServiceImpl implements AttendanceService {

    private final AttendanceRepo attendanceRepo;

    @Autowired
    public AttendanceRepoMongo(
    @Qualifier("attendanceMongo") AttendanceRepo attendanceRepo) {
        this.attendanceRepo = attendanceRepo;
    }

    @Override
    public List<Leave> selectLeaveApplication(Lv lv) {
    return attendanceRepo.selectLeaveApplication(lv);
    }
}

My Controller

@RestController
@RequestMapping("hr/")
public class AttendanceApi {

    private final AttendanceService attendanceService;

    @Autowired
    public AttendanceApi(AttendanceService attendanceService) {
        this.attendanceService = attendanceService;
    }

    @PostMapping("leave/application/pre")
    public List<Leave> leaveApplicationPre(
            @Valid @NotNull @RequestBody Lv lv) {
        return attendanceService.selectLeaveApplication(lv);
    }
}

My Config

@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class ErpConfig {
    @Bean
    public MongoTemplate mongoTemplate() {
        final MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
        return new MongoTemplate(mongoClient, "erpdb");
    }
}

My Gradle Dependency

plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'war'
}

group = 'org.mycomp'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    compileOnly 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

My Data

[
  {
    "_id": ObjectId("62ac28826940f44772b94b64"),
    "emp_cd": "A001",
    "appl_no": 59,
    "leave_type": "CL",
    "leave_start": "2022-01-01",
    "leave_end": "2022-01-31"
  },
  {
    "_id": ObjectId("62ac28826940f55772b94b64"),
    "emp_cd": "A002",
    "appl_no": 69,
    "leave_type": "EL",
    "leave_start": "2022-01-01",
    "leave_end": "2022-01-31"
  },
  {
    "_id": ObjectId("62ac28826940f66772b94b64"),
    "emp_cd": "A003",
    "appl_no": 79,
    "leave_type": "CL",
    "leave_start": "2022-01-01",
    "leave_end": "2022-01-31"
  }
]

My Error

2022-06-22 13:20:22.123 ERROR 7696 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : 
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: 
Failed to instantiate org.mycomp.mycompmongo.record.Leave using constructor 
public org.mycomp.mycompmongo.record.Leavejava.lang.String,int,java.lang.String,java.time.LocalDate,java.time.LocalDate) 
with arguments null,null,null,null,null] with root cause

java.lang.IllegalArgumentException: Parameter serialNumber must not be null!
    at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.20.jar:5.3.20]
    at org.mycomp.mycompmongo.record.Leave_Instantiator_rrwkac.newInstance(Unknown Source) ~[main/:na]
    at org.springframework.data.mapping.model.ClassGeneratingEntityInstantiator$EntityInstantiatorAdapter.createInstance(ClassGeneratingEntityInstantiator.java:288) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.mapping.model.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:102) ~[spring-data-commons-2.7.0.jar:2.7.0]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:560) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readDocument(MappingMongoConverter.java:526) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:462) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:458) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:120) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.MongoTemplate$ReadDocumentCallback.doWith(MongoTemplate.java:3322) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2974) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2667) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2649) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:902) ~[spring-data-mongodb-3.4.0.jar:3.4.0]
    at org.mycomp.mycompmongo.repository.AttendanceRepoMongo.selectLeaveApplication(AttendanceRepoMongo.java:33) ~[main/:na]
    at org.mycomp.mycompmongo.repository.AttendanceRepoMongo$$FastClassBySpringCGLIB$$c66a1e73.invoke(<generated>) ~[main/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) ~[spring-aop-5.3.20.jar:5.3.20]
    at org.mycomp.mycompmongo.repository.AttendanceRepoMongo$$EnhancerBySpringCGLIB$$95d9930c.selectLeaveApplication(<generated>) ~[main/:na]
    at org.mycomp.mycompmongo.service.AttendanceServiceImpl.selectLeaveApplication(AttendanceServiceImpl.java:25) ~[main/:na]
    at org.mycomp.mycompmongo.api.AttendanceApi.leaveApplicationPre(AttendanceApi.java:29) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681) ~[tomcat-embed-core-9.0.63.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.20.jar:5.3.20]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.63.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.20.jar:5.3.20]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
    at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

Leave a Comment