com.mongodb.MongoSocketReadException: Prematurely reached end of stream..............How to solve - mongodb

Sorry for my long post of code.
But I am just a beginner. I want to learn Spring Framework with MongoDB.
I am getting this exception but I have read some post about this problem. However, I didn't understand and how to fix it.
I haven't created application configuration. Is this the one that causes the exception?
Can anyone help me to fix this?
I am really appreciate it. Many thanks....
package com.mywebapp.dao;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.mywebapp.model.Location;
import com.mywebapp.model.User;
#Repository
public interface UserRepository extends ReactiveMongoRepository<User, String>{
List<User> findAllUsers();
User findBy_id(ObjectId id);
User findByUsername(String username);
List<User> findByFirstName(String firstName);
List<User> findByLastName(String lastName);
User findByEmail(String email);
List<User> findByDateOfBirth(Date dob);
List<User> findByLocation(Location location);
}
package com.mywebapp.controller;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mywebapp.model.Location;
import com.mywebapp.model.User;
import com.mywebapp.service.UserService;
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value="/",method = RequestMethod.GET)
public List<User> getAllUser(){
return userService.findAllUsers();
}
#RequestMapping(value="/{username}",method = RequestMethod.GET)
public User getUserByUserName(#PathVariable("username") String userName){
return userService.findByUserName(userName);
}
#RequestMapping(value="/{firstname}",method = RequestMethod.GET)
public List<User> getUserByFirstName(#PathVariable("firstname") String firstName){
return userService.findByFirstName(firstName);
}
#RequestMapping(value="/{lastname}",method = RequestMethod.GET)
public List<User> getUserByLastName(#PathVariable("lastname") String lastName){
return userService.findByLastName(lastName);
}
#RequestMapping(value="/{email}",method = RequestMethod.GET)
public User getUserByEmail(#PathVariable("email") String email){
return userService.findByEmail(email);
}
#SuppressWarnings("deprecation")
#RequestMapping(value="/{dob}",method = RequestMethod.GET)
public List<User> getUserByDOB(#PathVariable("dob") String dob) throws Exception{
Date dateOfBirth = new Date(dob);
return userService.findByDateOfBirth(dateOfBirth);
}
#RequestMapping(value="/{location}",method = RequestMethod.GET)
public List<User> getUserByLocation(#PathVariable("location") Location location){
return userService.findByLocation(location);
}
#RequestMapping(value= "/{id}", method = RequestMethod.GET)
public User getUserById(#PathVariable("id") ObjectId id) {
return userService.findById(id);
}
}
package com.mywebapp.service;
import java.util.Date;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import com.mywebapp.dao.UserRepository;
import com.mywebapp.model.Location;
import com.mywebapp.model.User;
#Service
public class UserService {
private UserRepository userRepo;
public UserService() {
}
public List<User> findAllUsers() {
return userRepo.findAllUsers();
}
public User findById(ObjectId id) {
return userRepo.findBy_id(id);
}
public User findByUserName(String username){
return userRepo.findByUsername(username);
}
public List<User> findByFirstName(String firstName){
return userRepo.findByFirstName(firstName);
}
public List<User> findByLastName(String lastName){
return userRepo.findByLastName(lastName);
}
public User findByEmail(String email){
return userRepo.findByEmail(email);
}
public List<User> findByDateOfBirth(Date dob){
return userRepo.findByDateOfBirth(dob);
}
public List<User> findByLocation(Location location){
return userRepo.findByLocation(location);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>MyWebApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyWebApplication</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>10</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Define below properties in application.properties under resources folder, replace actual values from yours. If MongoDB is default installed and there is no user name/ password then you don't need to define username and password properties.
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.username=*********
spring.data.mongodb.password=*********
spring.data.mongodb.database=demo
Update
Update repository to extend MongoRepository
#Repository
public interface UserRepository extends MongoRepository<User, ObjectId>
{
Remove List<User> findAllUsers(); from your repository.
Change all method in your service to below
public List<User> findAllUsers() {
return userRepo.findAll();
}

Related

Error creating bean with name 'entityManagerFactory' defined in class path ... : Table [command_failure_notification]

When I compile my spring project, I got the following error.
Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Table [command_failure_notification] contains logical column name [user_id] referring to multiple physical column names: [user_id], ["user_id"]
I am using Eclipse and hibernate 6 and Postgres 15 Database.
I have DataBase with name "primo" and it has one table with name "test" and one column with name "id"
I wanted to connect my project to DB for fetching/save my data.
My Connection string in Application.Properties is
spring.datasource.url=jdbc:postgresql://localhost:5432/primo
spring.datasource.username=postgres
spring.datasource.password=postgres
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
My pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.</groupId>
<artifactId>DemoDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>DemoDB</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
And my Java Classes:
package com.example.DemoDB;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.DemoDB.model.Test;
import jakarta.persistence.EntityManager;
#SpringBootApplication
public class DemoDbApplication {
public static void main(String[] args) {
SpringApplication.run(DemoDbApplication.class, args);
SessionFactory sf = HibernateUtil.getSessionFactory();
EntityManager entityManager = sf.createEntityManager();
entityManager.getTransaction().begin();
List<Test> result = entityManager.createQuery( "from Test", Test.class ).getResultList();
for ( Test t : result ) {
System.out.println( "Event (" + t.getId() );
}
entityManager.getTransaction().commit();
entityManager.close();
}
}
package com.example.DemoDB;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
if (sessionFactory == null)
{
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("src/main/resources/hibernate.cfg.xml").build();
Metadata metaData = new MetadataSources(standardRegistry)
.getMetadataBuilder()
.build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
}
return sessionFactory;
}
catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
package com.example.DemoDB.model;
import java.util.Objects;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;
import org.json.JSONObject;
#Entity
#NamedQuery(name = "Test.findAll", query = "SELECT u FROM Test u")
public class Test extends ADbModelEntity
{
private static final long serialVersionUID = -5165500932608878421L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
public Test() {
}
public Test(String id) {
this.id = id;
}
public String getId() {
return id;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "User [id= " + id + "]";
}
#Override
public ADbModelEntity clone() {
// TODO Auto-generated method stub
return new Test(this.id);
}
#Override
public int hashCode() {
return Objects.hash(this.id) ;
}
#Override
public boolean equals(Object other) {
if(other instanceof Test) {
return this.id.equalsIgnoreCase( ((Test)other).id );
}
return false;
}
public JSONObject toJSONObject()
{
JSONObject json = new JSONObject();
json.put("id", this.id);
return json;
}
}

Getting Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name Error using Spring Boot 2

I am using Spring Boot 2 to create web application and running the application using CommandLineRunner to connect PostgreSql database
1 . "LinkRepository" Interface:
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.entity.Link;
public interface LinkRepository extends CrudRepository<Link, Long> {
}
2. 'Link' Entity :
package com.example.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "link")
public class Link {
#Id
#GeneratedValue
#Column(name = "id")
private Long id;
#Column(name = "NAME")
private String name;
#Column(name = "url", unique = true)
private String url;
public Link(String name, String url) {
this.name = name;
this.url = url;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
3. Demo Application Config:
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.example.entity.Link;
#SpringBootApplication(scanBasePackages = { "com.example" })
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean
public CommandLineRunner demo(LinkRepository repository) {
// TODO Auto-generated method stub
return (args) -> {
repository.save(new Link("test", "link"));
for (Link linkrepo : repository.findAll()) {
System.out.println(linkrepo.getName());
}
};
}
}
4. Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
5. Application.properties :
spring.datasource.url=jdbc:postgresql://localhost:5432/TestDb
spring.datasource.username=postgres
spring.datasource.password=root
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto = create
spring.h2.console.enabled=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect
I am getting following error :
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo' defined in com.example.demo.DemoApplication: Unsatisfied dependency expressed through method 'demo' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'linkRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.entity.Link
If you want to use CommandLineRunner, then that should be something like this:
`#SpringBootApplication(scanBasePackages = { "com.example" })
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
return (args) -> {
repository.save(new Link("test", "link"));
for (Link linkrepo : repository.findAll()) {
System.out.println(linkrepo.getName());
}
};
}
I've just prefer doing that like this:
1) Create a new class called for example DemoBootstrap
2) And it should be soemthing like this
#Component
public class DemoBootstrap implements ApplicationListener<ContextRefreshedEvent> {
private final LinkRepository categoryRepository;
public DemoBootstrap(LinkRepository linkRepository) {
this.linkRepository = linkRepository;
}
#Override
#Transactional
public void onApplicationEvent(ContextRefreshedEvent event) {
// Here add all links that should be saved
// for example
linkRepository.save(new Link("foo", "bar"));
linkRepository.save(new Link("foo2", "bar2"));
// etc
}
Add #EntityScan("com.example.entity") on DemoApplication class or move DemoApplication to 'com.example' package and then spring will scan all sub-packages.

Swagger 2 UI not accessible ,Spring boot application deployed on external tomcat

I have copied the war to apache-tomcat-8.0.43/webapps and started tomcat using ./startup.sh. When I try to access http://localhost:8080/swagger-ui.html, I get 404 but it's working when I say mvn spring-boot:run. Am I missing any configuration? Sample code below:
package com.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
#SpringBootApplication
#EnableSwagger2
public class UserMicroServicesApplication extends SpringBootServletInitializer {
private static ConfigurableApplicationContext ctx;
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(UserMicroServicesApplication.class);
}
public static void main(String[] args) throws Exception {
ctx = SpringApplication.run(UserMicroServicesApplication.class, args);
}
#Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.user.controller")).paths(regex("/api.*")).build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo("User API", "User service API.", "V1", "Terms of service", "", "", "");
}
}
controller class
-------------------
package com.user.controller;
import com.user.service.UserService;
import com.user.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
#RestController
#RequestMapping(value = "/api")
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#RequestMapping(value = "/user", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.CREATED)
#ResponseBody
public UserVO createUser(#RequestBody #Valid UserVO user) {
logger.debug("creating user with email = {}", user);
UserVO updatedUserVO = userService.createUser(user);
logger.debug("user created with id {}", updatedUserVO.getId());
return updatedUserVO;
}
}
POM.xml
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>1.5.7.RELEASE</version>
</dependency>
You need to add context path to the link.
apache-tomcat-8.0.43/webapps/${war-name}
http://localhost:8080/${war-name}/swagger-ui.html

Passing Class object containing HashMap<String, Set<String>> as instance variable to RESTService

i have a POJO class BookType as:
package com.jersey.series.json.service;
import java.util.HashMap;
import java.util.Set;
public class BookType {
#Override
public String toString() {
return "BookType [bookId=" + bookId + ", bookName=" + bookName + ", author=" + author + ", category=" + category
+ ", obj=" + obj + "]";
}
protected int bookId;
protected String bookName;
protected String author;
protected String category;
protected HashMap<String, Set<String>> obj = new HashMap<>();
public HashMap<String, Set<String>> getObj() {
return obj;
}
public void setObj(HashMap<String, Set<String>> obj) {
this.obj = obj;
}
public int getBookId() {
return bookId;
}
public void setBookId(int value) {
this.bookId = value;
}
public String getBookName() {
return bookName;
}
public void setBookName(String value) {
this.bookName = value;
}
public String getAuthor() {
return author;
}
public void setAuthor(String value) {
this.author = value;
}
public String getCategory() {
return category;
}
public void setCategory(String value) {
this.category = value;
}
}
And a rest Service :
package com.jersey.series.json.service;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/bookservice")
public class BookServiceImpl implements IBookService {
#POST
#Path("addbookandreturnjson")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public BookType saveAndReturnBookInfojson(BookType bookType) {
return bookType;
}
}
i ma making this call using PostMan:
http://localhost:8080/Jersey-JSON-IO/rest/bookservice/addbookandreturnjson
this is my message body with type application Json
{"bookId":5,"bookName":"abc","author":"saurabh","category":"Test","obj":{"1":["abc","xyz"]}}
Service is receiving everything correct except for the "obj" field where am i doing wrong or what i need to do.I am using Glassfish 4.1.1 as web container.Here is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>in.bench.resources</groupId>
<artifactId>Jersey-JSON-IO</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Jersey-JSON-IO</name>
<description>Jersey web service using JSON (Jackson parser) as request/response</description>
<!-- https://jersey.java.net/documentation/latest/media.html#json.jackson -->
<!-- Jersey repository -->
<repositories>
<repository>
<id>snapshot-repository.java.net</id>
<name>Java.net Snapshot Repository for Maven</name>
<url>https://maven.java.net/content/repositories/snapshots/</url>
<layout>default</layout>
</repository>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<jersey.version>2.12</jersey.version>
<jersey.scope>compile</jersey.scope>
<compileSource>1.7</compileSource>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>Jersey-JSON-IO</finalName>
<!-- maven compiler plugin -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey.version}</version>
<scope>${jersey.scope}</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
<scope>${jersey.scope}</scope>
</dependency>
</dependencies>

How can we create Auto generated field for mongodb using spring boot

I write some code.I want to make questionId field in BaseQuestion Class as Autogenerated.Any solution for that? I am not using jpa jar.so i can't use #Generatedvalue annotation.So how we show here this field is auto generated.
code is below.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>audit_project</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
BaseQuestion.java
package model;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "basequestion")
public class BaseQuestion {
#ID
private String id;
private int questionId;
private String responseType;
private boolean required;
private boolean active;
private String questionCode;
private QuestionText questionText;
private String category;
private List<Responses> responses;
public QuestionText getQuestionText() {
return questionText;
}
public void setQuestionText(QuestionText questionText) {
this.questionText = questionText;
}
public List<Responses> getResponses() {
return responses;
}
public void setResponses(List<Responses> responses) {
this.responses = responses;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public String getResponseType() {
return responseType;
}
public void setResponseType(String responseType) {
this.responseType = responseType;
}
public boolean getRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public String getQuestionCode() {
return questionCode;
}
public void setQuestionCode(String questionCode) {
this.questionCode = questionCode;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
AuditProjectRepository.java
package repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import model.BaseQuestion;
public interface AuditProjectRepository extends MongoRepository<BaseQuestion, String> {
public BaseQuestion findByQuestionId(int questionId);
public BaseQuestion findByQuestionCode(String questionCode);
public Long deleteByQuestionId(int questionid);
}
MongoDB came with all sophisticated ObjectId generation feature, but often you just jumped the ship from relational database, and you still want an easy to read / communicate numeric identifier field which automatically increments every time new record is inserted.
One neat suggestion from MongoDB tutorial is to use a counter collection with a ‘counter name’ as its id, and a ‘seq’ field to store the last used number.
When developing using Spring Data MongoDB, this neat trick can be written as a simple service. Here I used the collection name as the counter name so it’s easy to guess / remember.
import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import com.model.CustomSequences;
#Service
public class NextSequenceService {
#Autowired private MongoOperations mongo;
public int getNextSequence(String seqName)
{
CustomSequences counter = mongo.findAndModify(
query(where("_id").is(seqName)),
new Update().inc("seq",1),
options().returnNew(true).upsert(true),
CustomSequences.class);
return counter.getSeq();
}
}
CustomSequences is just a simple class representing the collection. Please beware the usage of int data type, this will limit to 2^31 entries maximum.
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "customSequences")
public class CustomSequences {
#Id
private String id;
private int seq;
// getters and setters
}
Then when inserting a new entry (with help of Spring MongoDB Repository support), just set the id field like this before you save it
BaseQuestion baseQuestion = new BaseQuestion();
baseQuestion.setQuestionId(nextSequenceService.getNextSequence("customSequences"));
/* Rest all values */
baseQuestionRepository.save(baseQuestion);
If you don't like this way then you need to use MongoDBEvents and use onBeforeConvert to generate automated value using same above approach.
Also above approach is threadsafe as findAndModify() is a thread safe atomic method
Using a String for your primary key would be a good idea. With this, you do not configure anything since the strings are automatically generated.