Spring-boot, unable to autowire a class.No default constructor found Exception is raised - spring-annotations

I am new to spring-boot. After i moved a class to different package (other the one contains 'Application'), Could not instantiate bean class: No default constructor found Exception is raised.
Before (workable code)
package com.server;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Controller;
#Configuration
#ComponentScan(basePackages = {"com.server" })
#EnableAutoConfiguration
#Profile({ "default" })
#Controller
public class Application {
private static Log logger = LogFactory.getLog(Application.class);
public static void main(String[] args) {
logger.info("Starting Application...");
SpringApplication.run(Application.class, args);
}
}
A piece of code from http://bitwiseor.com/2013/09/20/creating-test-services-with-spring-boot/
package com.server;
import java.util.Collections;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#Controller
#Profile({ "default" })
class Franchise {
private JdbcTemplate jdbcTemplate;
#Autowired
public Franchise(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#ResponseBody
#RequestMapping("/api/franchise/{id}")
String franchiseId(#PathVariable Long id) {
try {
return jdbcTemplate.queryForMap("SELECT id, title FROM franchises WHERE id=?", id).toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
#ResponseBody
#RequestMapping("/api/franchise")
String franchises() {
try {
return jdbcTemplate.queryForList("SELECT id, title FROM franchises").toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
}
I am able to bring up the server when class 'Application' and 'Franchise' are located in the same package. However, when I moved the class 'Franchise' into another package as shown below, I've got this exception: Could not instantiate bean class: No default constructor found Exception is raised.
package com.server.api;
import java.util.Collections;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#Controller
#Profile({ "default" })
class Franchise {
private JdbcTemplate jdbcTemplate;
#Autowired
public Franchise(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
#ResponseBody
#RequestMapping("/api/franchise/{id}")
String franchiseId(#PathVariable Long id) {
try {
return jdbcTemplate.queryForMap("SELECT id, title FROM franchises WHERE id=?", id).toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
#ResponseBody
#RequestMapping("/api/franchise")
String franchises() {
try {
return jdbcTemplate.queryForList("SELECT id, title FROM franchises").toString();
} catch(EmptyResultDataAccessException ex) {
return Collections.EMPTY_MAP.toString();
}
}
}
How can I solve this problem if I wanted to move this class into a different package?
Thanks!
Edit: I found a solution
When I removed the following tag, I am able to put the class into separate package.
#Configuration
#Profile({ "default" })
But I have no idea why...

It looks to me like your Franchise class is package private (the default visibility for a java class). That would explain everything (and no need to involve Spring or anything other than a compiler). To fix it just declare your class to be "public".
Marten is also correct that #Configuration is probably not want you mean for the Franchise (but in this case it's harmless).

Related

Spring boot - Null pointer exception while mocking MongoTemplate.getCollection()

I have written a service class which uses MongoTemplate.getCollection().
But while writing the test case I am mockingMongoTempalte and MongoCollection but getting NullPointerException.
Following is the code.
Service class
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.NoSuchElementException;
#Service
public class ABCService {
#Autowired
MongoTemplate mongoTemplate;
public byte[] exportFrom(String collectionName) {
if(!mongoTemplate.collectionExists(collectionName))
throw new NoSuchElementException("Collection does not exist");
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
do something
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Test Class:
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.mongodb.core.MongoTemplate;
import static org.mockito.Mockito.*;
#ExtendWith(MockitoExtension.class)
class ABCServiceTest {
#Mock
private MongoTemplate mongoTemplate;
#Mock
private MongoCollection<Document> documentMongoDBCollection;
#InjectMocks
private ABCService abcService ;
#Test
void exportFrom() throws Exception {
JSONObject obj = new JSONObject();
obj.put("_id", "1234");
obj.put("accessField", "xyz 123");
Document doc = Document.parse(obj.toString());
byte[] pos = obj.toString().getBytes();
when(mongoTemplate.collectionExists("DataCollection"))
.thenReturn(true);
when(mongoTemplate.getCollection(any(String.class)))
.thenReturn(documentMongoDBCollection); // **This returning Null pointer exception**
when(abcService .exportFrom("DataCollection"))
.thenReturn(pos);
byte[] result = abcService .exportFrom("DataCollection");
Assertions.assertNotNull(result);
verify(mongoTemplate,times(1)).collectionExists("DataCollection");
verify(mongoTemplate,times(1)).getCollection("DataCollection");
}
}
Expecting to throw object to complete the mocking of Mongo template.

Field authorMongoRepository required a bean of type that could not be found

Description:
Field authorMongoRepository in com.example.SpringReturnObject.Mongo.Controller.AuthorController required a bean of type 'com.example.SpringReturnObject.Rest.Controller.AuthorMongoRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.SpringReturnObject.Rest.Controller.AuthorMongoRepository' in your configuration.
AuthorMongoRepository class
package com.example.SpringReturnObject.Rest.Controller;
import com.example.SpringReturnObject.Mongo.Model.Author;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface AuthorMongoRepository extends MongoRepository<Author, String> {
List<Author> findByUsernameContainingIgnoreCase(String username);
List<Author> findByArticles_titleContainingIgnoreCase(String title);
}
AddnewDocument.java
package com.example.SpringReturnObject.Mongo.Implementation;
import com.example.SpringReturnObject.Mongo.Model.Article;
import com.example.SpringReturnObject.Mongo.Model.Author;
import com.example.SpringReturnObject.Rest.Controller.AuthorMongoRepository;
import com.example.SpringReturnObject.Rest.Controller.MongoController;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AddNewDoc implements MongoController {
#Autowired
AuthorMongoRepository authorMongoRepository;
#Override
public List<Author> getAllList() {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
authorMongoRepository.deleteAll();
final Article article1;
try {
article1 = new Article("Spring Boot - MongoDB + Data + Web"
, "MongoDB", df.parse("10/5/2018"));
final Article article2 = new Article("Spring Boot - MongoDB + Data + Web"
, "H2 Console", df.parse("2/3/2016"));
final Article article3 = new Article("Spring Cloud - Zuul + Eureka + Rest Web", "Load Balancer with Zuul", df.parse("5/1/2018"));
final Article article4 = new Article("Spring Cloud - Feign"
, "Feign Client + Eureka + Rest", df.parse("5/6/2018"));
Author author1 = new Author("Melardev", Arrays.asList(article1, article2));
Author author2 = new Author("Momo", Arrays.asList(article3, article4));
authorMongoRepository.save(author1);
authorMongoRepository.save(author2);
}
catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
MongoControllerInterface
package com.example.SpringReturnObject.Rest.Controller;
import com.example.SpringReturnObject.Mongo.Model.Author;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public interface MongoController {
#GetMapping("/author")
List<Author> getAllList();
}
ApplicationStartup.java
package com.example.SpringReturnObject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#EnableMongoRepositories(basePackages = "com.example.SpringReturnObject.Rest.Controller.AuthorMongoRepository")
#EnableAutoConfiguration
#Configuration
#ComponentScan({"com.example.*"})
#EntityScan({"com.example.*"})
#SpringBootApplication
public class SpringReturnObjectApplication {
public static void main(String[] args) {
SpringApplication.run(SpringReturnObjectApplication.class, args);
}
}

spring restfull service request and response as Text/plan

I'm new in Spring boot, I just follow a simple tutorial and I finished a simple service where I received a Json request and Response with a Json as well, now I need to change the request/response as a Text/Plain, these its what I have in my controller class:
package com.notas.core.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.notas.core.entity.Nota;
import com.notas.core.model.MNota;
import com.notas.core.service.NotaService;
#RestController
#RequestMapping("/v1")
public class NotaController {
#Autowired
#Qualifier("servicio")
NotaService servicio;
#PutMapping("/nota")
public boolean agregarNota(#RequestBody #Valid Nota nota) {
return servicio.crear(nota);
}
#PostMapping("/nota")
public boolean modificarNota(#RequestBody #Valid Nota nota) {
return servicio.actualizar(nota);
}
#DeleteMapping("/nota/{id}/{nombre}")
public boolean borrarNota(#PathVariable("id") long id, #PathVariable("nombre") String nombre) {
return servicio.borrar(nombre, id);
}
#GetMapping("/notas")
public List<MNota> obtenerNotas(Pageable pageable){
return servicio.obtenerPorPaginacion(pageable);
}
}
Could you please tell me whats do I have to change in order to receive a Text/Plain and response with the same mediatype.
In all Mapping annotation (#Get, #Post...) they have an attribute consumes and produces, you could add that using the media type
#PostMapping(value="/foo", consumes = MediaType.TEXT_PLAIN_VALUE , produces= MediaType.TEXT_PLAIN_VALUE)
public String plainValue(#RequestBody String data) {
return; //logic
}

How to use Rest Service while using Spring Boot & Spring Data Jpa

Im working on a spring boot application for rest service with using spring data jpa. I followed instructors and read much answers but I couldn't fix my rest service.
Here is application.class
package tr.kasim.Application;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories("tr.kasim.Dao")
#EntityScan("tr.kasim.Model")
#ComponentScan({"tr.kasim.Service", "tr.kasim.Application" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Here is `restcontroller.class
package tr.kasim.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tr.kasim.Service.PersonelService;
import tr.kasim.Model.Personel;
#RestController
public class STRestController {
#Autowired
public PersonelService personelService;
#RequestMapping(value = "/api/personels", method = RequestMethod.GET)
public ResponseEntity<List<Personel>> getPersonels(){
List<Personel> personels = personelService.findAll();
return ResponseEntity.ok().body(personels);
}
}
`
Here is Service.class`
package tr.kasim.Service;
import java.util.List;
import tr.kasim.Model.Personel;
public interface PersonelService {
List<Personel> findAll();
}
`
Here is ServiceImplemantion.class
package tr.kasim.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tr.kasim.Dao.PersonelDao;
import tr.kasim.Model.Personel;
#Service
public class PersonelServiceImpl implements PersonelService {
#Autowired
private PersonelDao personelDao;
#Override
#Transactional
public List<Personel> findAll() {
return personelDao.findAll();
}
}
Here is Dao.class
package tr.kasim.Dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import tr.kasim.Model.Personel;
#Repository
public interface PersonelDao extends JpaRepository<Personel, Long> {
List<Personel> findAll();
}
Lastly here is my application.properties
#MySql Connection
spring.datasource.url=jdbc:mysql://localhost:3306/exampleproject?verifyServerCertificate=false&useSSL=true
spring.datasource.username=root
spring.datasource.password=*******
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#Jpa/Hibernate
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
#Logging
logging.file=staffTracking.log
logging.level.org.springframework.web=debug
Im not sure about componentScan. When I read answers I discovered someone mentioned about it but I tried and I got still nothing. Please show me where I failed. Best Regards.
I updated Application.class, now I can deploying project but rest service not working still.
How did you try ComponentScan? The issue here seems that you have a package structure like this:
tr.kasim.Application
- Application.java
tr.kasim.Service
- PersonelService.java
- PersonelServiceImpl.java
tr.kasim.Dao
- PersonelDao.java
Now since, the mainClass is in tr.kasim.Application it would scan for bean definitions inside that package (or a sub-package in tr.kasim.Application). So,
either you move the mainClass out to a parent-package like tr.kasim, or
use #ComponentScan({ "tr.kasim.Dao", "tr.kasim.Service", "tr.kasim.Application" }) and so on.
-- Update --
Based on the discussion so far, I'd suggest taking the first option as that reduces the effort to manually enable scan for entity, repository, etc.

HikariCP for MongoDB in springboot

I am looking to create a connection pool - for mongoDB in Springboot. I am currently making use of Springdata Mongo repositories to connect to DB and collections but unsure of how to create the datapool connection
Here is the current implementation
PersonRepository.java
package com.test.TestAPI.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.test.TestAPI.dto.Person;
#Repository
public interface PersonRepository extends MongoRepository<Person, String> {
}
PersonService
package com.test.TestAPI.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;
#Service
public class PersonService {
#Autowired
private PersonRepository personRepo;
public List<Person> findAllPersons() {
return personRepo.findAll();
}
public Person createPerson(Person person) {
return personRepo.save(person);
}
}
PersonController
package com.test.TestAPI.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.TestAPI.service.impl.PersonService;
import com.test.TestAPI.dto.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
#RestController
#RequestMapping(path="/v1/personController")
#Api(value="Controller for Person document")
public class PersonController {
#Autowired
PersonService service;
#GetMapping("/getAllPersons")
#ApiOperation(produces = MediaType.APPLICATION_JSON_VALUE, httpMethod = "GET", response = List.class,
value = "getAllPersons from the database", notes = "Sample note")
public ResponseEntity<List<Person>> getAllPersons(){
List<Person> personList = service.findAllPersons();
return new ResponseEntity<List<Person>>(personList, HttpStatus.OK);
}
}
SimpleCommandLineConfig
package com.test.TestAPI.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Component;
import com.test.TestAPI.repository.PersonRepository;
import com.test.TestAPI.dto.Person;
#Component
#Order(3)
public class SimpleCommandLineConfig implements CommandLineRunner {
#Autowired
PersonRepository repo;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("third command line runner");
System.out.println(repo.save(new Person("rr","rr",4)));
}
}
App.java
package com.test.TestAPI.main;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
* Hello world!
*
*/
#SpringBootApplication
#ComponentScan(basePackages= {"com.test.TestAPI"})
#EnableMongoRepositories(basePackages= {"com.test.TestAPI.repository"})
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
Also, I would like to know if spring data repos like a custom repo for MongoDB takes care of connection pool mechanism? How does connection pooling happen in that case? Could you please help me on this
I think I found an answer for this. Just like we use JDBC templates for RDBMS to store the databases, spring provides something called MongoTemplates which forms a connection pool based on the db configuration given
Here is a sample implementation
MongoClientFactory.java
public #Bean MongoClientFactoryBean mongo() throws Exception {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
mongo.setHost("localhost");
MongoClientOptions clientOptions = MongoClientOptions.builder().applicationName("FeddBackAPI_DB")
.connectionsPerHost(2000)
.connectTimeout(4000)
//.maxConnectionIdleTime(1000000000)
.maxWaitTime(3000)
.retryWrites(true)
.socketTimeout(4000)
.sslInvalidHostNameAllowed(true)//this is very risky
.build();
mongo.setMongoClientOptions(clientOptions);
return mongo;
}
DataSourceConfig.java (Another config class. Same config class can also be used to define all beans)
package com.fmr.FeedBackAPI.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
#Configuration
#Import(value=MongoClientFactory.class)
public class DataSourceConfig {
#Autowired
Mongo mongo;
#Autowired
Environment env;
#Bean
public String test() {
System.out.println("mongo"+mongo);
return "rer";
}
private MongoTemplate mongoTemplate() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
MongoTemplate template = new MongoTemplate(factory);
return template;
}
#Bean
#Qualifier(value="customMongoOps")
public MongoOperations mongoOps() {
MongoOperations ops = mongoTemplate();
return ops;
}
#Bean
public MongoDbFactory factory() {
MongoDbFactory factory = new SimpleMongoDbFactory((MongoClient) mongo, "mongo_test");
return factory;
}
// #Bean
// public GridFsTemplate gridFsTemplate() {
// return new GridFsTemplate(mongo, converter)
// }
#Bean
public javax.sql.DataSource dataSource() {
HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(100);
// ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
// ds.setJdbcUrl(env.getProperty("spring.datasource.url"));;
//ds.setUsername(env.getProperty("spring.datasource.username"));
//ds.setPassword(env.getProperty("spring.datasource.password"));
ds.addDataSourceProperty("cachePrepStmts", true);
ds.addDataSourceProperty("prepStmtCacheSize", 250);
ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
ds.addDataSourceProperty("useServerPrepStmts", true);
return ds;
}
}
Now autowire the template/mongoOperations in you dao implementation or service and use it
package com.fmr.FeedBackAPI.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.fmr.FeedBackAPI.dto.ConfigDTO;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
#Service
public class PlanConfigService {
#Autowired
#Qualifier(value="customMongoOps")
MongoOperations mongoOps;
public List<ConfigDTO> createConfigDTOList(List<ConfigDTO> configDTOList) {
List<ConfigDTO> configList = new ArrayList<>();
if(!mongoOps.collectionExists(ConfigDTO.class)) {
mongoOps.createCollection("ConfigDTO_table");
}
//create the configDTOList
mongoOps.insert(configDTOList, ConfigDTO.class);
configList = mongoOps.findAll(ConfigDTO.class, "ConfigDTO_table");
return configList;
}
public List<ConfigDTO> createConfigDTO(ConfigDTO configDTO) {
List<ConfigDTO> configList = new ArrayList<>();
if(!mongoOps.collectionExists(ConfigDTO.class)) {
mongoOps.createCollection("ConfigDTO_table");
}
//create the configDTOList
mongoOps.save(configDTO);
configList = mongoOps.find(query(where("planId").is(configDTO.getPlanId())), ConfigDTO.class,"ConfigDTO_table");
return configList;
}
}
Here is the application.properties (this is the default instance running in local)
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mongo_test
spring.data.mongodb.repositories=true
#
spring.datasource.url=jdbc:mongodb://localhost:27017/mongo_test