Why #Autowired not working all the time? - mongodb

Im trying to setup mongodb with SpringBoot and im not using context.xml but trying to configure with configuration class and annotations.
package com.configuration;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
#Configuration
#EnableMongoRepositories(basePackages = "com.mongo")
public class MongoConfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "mongodbname";
}
#Override
public Mongo mongo() throws Exception {
return new MongoClient("127.0.0.1", 27017);
}
#Override
protected String getMappingBasePackage() {
return "com.mongo";
}
}
My repository looks like this :
package com.mongo.repositories;
import com.mongo.documents.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository("sequenceRepository")
public class SequenceRepository{
#Autowired
private MongoTemplate mongoTemplate;
public Sequence findOne(Query query){
return this.mongoTemplate.findOne(query,Sequence.class);
}
public List<Sequence> find(Query query){
return this.mongoTemplate.find(query,Sequence.class);
}
public void save(Sequence object){
this.mongoTemplate.save(object);
}
public void delete(Sequence object){
this.mongoTemplate.remove(object);
}
}
If i use like this in the rest controller it is working properly :
package com.controllers;
import com.mongo.documents.Sequence;
import com.mongo.repositories.SequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class IndexController {
#Autowired
private SequenceRepository sequenceRepository;
#RequestMapping("/")
public String index(){
Sequence sequence = new Sequence();
sequence.setClassName("class.Test");
sequence.setActual(1);
sequenceRepository.save(sequence);
return "index";
}
}
But if i want to use the SequenceRepository inside the Sequence document like this :
package com.mongo.documents;
import com.mongo.repositories.SequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Sequence {
#Autowired
private SequenceRepository sequenceRepository;
#Id
private String id;
private String className;
private int actual;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public int getActual() {
return actual;
}
public void setActual(int actual) {
this.actual = actual;
}
public void save(){
this.sequenceRepository.save(this);
}
public void delete(){
this.sequenceRepository.delete(this);
}
}
After that I change the code in the controller to :
package com.controllers;
import com.mongo.documents.Sequence;
import com.mongo.repositories.SequenceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class IndexController {
#Autowired
private SequenceRepository sequenceRepository;
#RequestMapping("/")
public String index(){
Sequence sequence = new Sequence();
sequence.setClassName("class.Test");
sequence.setActual(1);
sequence.save();
return "index";
}
}
I got a nullPointerExceeption at this point in the save() method.

There is no need to inject your Repository inside your Domain object Sequence as it is really bad design to have a dependency between the domain objects and your repository classes.
To follow some good practices, your Service classes or if you don't need a Service layer, your Controller classes should inject your Repository beans.
In your last code snippet your are already doing it, but the .save() method should be called on your repository SequenceRepository and not on the domain object Sequence.
An example could be the following:
#RestController
public class IndexController {
#Autowired
private SequenceRepository sequenceRepository;
#RequestMapping("/")
public String index(){
Sequence sequence = new Sequence();
sequence.setClassName("class.Test");
sequence.setActual(1);
// now let's save it
sequenceRepository.save(sequence);
return "index";
}
}

You can only autowire Spring-managed components into other Spring-managed components. Your sequence object is not a component (not annotated with #Component, #Service, #Repository or #Controller etc.)
I suggest you follow rieckpil's advice.

Related

I'm doing simple integration of Mongodb and springboot, but unable to save data properly

I'm fairly new to java and spring boot. I'm trying to save data in mongo through spring, but it only saves _id=0 and model class.
My controller
package com.example.usermanagement.resource;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.usermanagement.model.User;
import com.example.usermanagement.repository.userRepository;
#RestController
public class UserController {
#Autowired
private userRepository repository;
#PostMapping("/saveUser")
public String saveUser(#RequestBody User user){
System.out.println(user);
repository.save(user);
return "User Added";
}
#GetMapping("/findAllUsers")
public List<User> getUsers(){
return repository.findAll();
}
#GetMapping("/findAllUsers{id}")
public Optional<User> getUser(#PathVariable int id){
return repository.findById(id);
}
#DeleteMapping("/delete/{id}")
public String deleteUser(#PathVariable int id){
repository.deleteById(id);
return "User Deleted";
}
}
On hitting save through postman, I get this in my db
[![enter image description here][1]][1]
My model
package com.example.usermanagement.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
#Getter
#Setter
#ToString
#Document(collection = "user_data")
public class User {
#Id
private int id;
private String firstName;
private String lastName;
}
And the repository
package com.example.usermanagement.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.example.usermanagement.model.User;
#Repository
public interface userRepository extends MongoRepository<User, Integer> {
}
I do not understand what I'm doing wrong here, Why the rest of the data is not getting saved properly also Id is coming 0 rather than what I'm sending.
Post request I'm sending
{
"id":2,
"name":"yash",
"lastName":"asd",
"role":"dev"
}
When you dont use #Field to notify to database, you need to pass the same model class name as parameters.
{
"id":2,
"firstName":"yash",
"lastName":"asd"
}
Lombok won't automatically be configured. So you need to manually configure. Setting up lombok

Field vehicleRepository required a bean of type ..VehicleInterface that could not be found

I'm trying to #autowire repository reference from Service implementation class but still I'm getting bean not found error
I've already tried moving App.java file in the parent
App.java
package com.trucker;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class App
{
public static void main( String[] args ){
ApplicationContext applicationContext = SpringApplication.run(App.class,args);
}
}
VehicleService.java
package com.trucker.service;
import com.trucker.entity.Vehicle;
import com.trucker.repository.VehicleRepositoryInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class VehicleService implements VehicleServiceI {
#Autowired
VehicleRepositoryInterface vehicleRepository;
#Override
public Vehicle addVehicles(Vehicle vehicle) {
System.out.println(vehicle);
return vehicleRepository.save(vehicle);
}
}
VehicleRepositoryInterface.java
package com.trucker.repository;
import com.trucker.entity.Vehicle;
import org.springframework.context.annotation.Bean;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface VehicleRepositoryInterface extends CrudRepository<Vehicle,String> {
}
VehicleController.java
package com.trucker.controller;
import com.trucker.entity.Vehicle;
import com.trucker.service.VehicleServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class VehicleController {
#Autowired
VehicleServiceI vehicleService;
#RequestMapping(path = "/vehicles", method = RequestMethod.PUT)
public String addVehicles(#RequestBody Vehicle vehicle) {
System.out.println("************IN THE CONTROLLER************"+vehicle);
vehicleService.addVehicles(vehicle);
return "";
}
}
Vehicle.java
package com.trucker.entity;
import javax.persistence.Entity;
import java.sql.Timestamp;
import javax.persistence.Id;
#Entity
public class Vehicle {
#Id
String vin;
String make;
String model;
int year;
int redlineRpm;
int maxFuelVolume;
Timestamp lastServiceDate;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getRedlineRpm() {
return redlineRpm;
}
public void setRedlineRpm(int redlineRpm) {
this.redlineRpm = redlineRpm;
}
public int getMaxFuelVolume() {
return maxFuelVolume;
}
public void setMaxFuelVolume(int maxFuelVolume) {
this.maxFuelVolume = maxFuelVolume;
}
public Timestamp getLastServiceDate() {
return lastServiceDate;
}
public void setLastServiceDate(Timestamp lastServiceDate) {
this.lastServiceDate = lastServiceDate;
}
#Override
public String toString() {
return "Vehicle{" +
"vin='" + vin + '\'' +
", make='" + make + '\'' +
", model='" + model + '\'' +
", year=" + year +
", redlineRpm=" + redlineRpm +
", maxFuelVolume=" + maxFuelVolume +
", lastServiceDate=" + lastServiceDate +
'}';
}
}
application.properties
application.properties
server.port=8084
spring.datasource.url=jdbc:oracle:thin:#localhost:1521:xe
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.driver-class=oracle.jdbc.driver.OracleDriver
spring.datasource.username=system
spring.datasource.password=system
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
Directory Structure:
src
src/main
src/main/resources/application.properties
src/main/java
src/main/java/com.trucker
src/main/java/com.trucker/App.java
src/main/java/com.trucker.controller
src/main/java/com.trucker.controller.VehicleController
src/main/java/com.trucker.entity.Vehicle
src/main/java/com.trucker.repository
src/main/java/com.trucker.repository.VehicleRepositoryInterface
src/main/java/com.trucker.service
src/main/java/com.trucker.service.vehicleService
Take a look at this post it has clear answers
Spring boot autowiring an interface with multiple implementations
or
Spring autowire interface

how avoid to access to other data users. Spring boot + MongoDB

I'm developing a web application with Spring Boot and MongoDB. I'm following the MVC model.
I have a view which shows a list of stored data, but the app ignores the logged user and shows every objects.
https://i.stack.imgur.com/zl7TC.png
Here, the first row was added by another user, but it's showed anyway.
How could I get only the object allowed to the authenticated user?.
The only way I can see is checking the user Id after each query and get only the object of the given user. I think that there should be a better way to do this.
The code is the following:
Entity
import java.io.Serializable;
import java.util.Collection;
import java.util.Set;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "trackings")
public class Tracking extends Entity implements Serializable {
private static final long serialVersionUID = -1249902722123443448L;
#Indexed(unique = true, direction = IndexDirection.DESCENDING)
private String trackingName;
private String SoftwareName;
#DBRef
private Set<Alarm> alarms;
public String getTrackingName() {
return trackingName;
}
public void setTrackingName(String trackingName) {
this.trackingName = trackingName;
}
public String getSoftwareName() {
return SoftwareName;
}
public void setSoftwareName(String softwareName) {
SoftwareName = softwareName;
}
public Collection<Alarm> getAlarms() {
return alarms;
}
public void setAlarms(Set<Alarm> alarms) {
this.alarms = alarms;
}
}
Repository
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import us.etsii.fvt.domains.Tracking;
#Repository
public interface TrackingRepository extends MongoRepository<Tracking, String>{
Tracking findByTrackingName(String name);
}
Controller
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import us.etsii.fvt.domains.Alarm;
import us.etsii.fvt.domains.Tracking;
import us.etsii.fvt.domains.User;
import us.etsii.fvt.services.TrackingService;
import us.etsii.fvt.services.UserService;
#Controller
public class TrackingController {
#Autowired
private UserService userService;
#Autowired
private TrackingService trackingService;
#RequestMapping(value = { "/tracking" }, method = RequestMethod.GET)
public ModelAndView tracking() {
ModelAndView modelAndView = new ModelAndView();
// AƱadimos el usuario al modelo
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject("currentUser", user);
modelAndView.addObject("fullName", user.getFullname());
// AƱadimos la lista de trackings al modelo
List<Tracking> trackings = trackingService.findAll();
modelAndView.addObject("trackings", trackings);
// Devolvemos el modelo
modelAndView.setViewName("tracking");
return modelAndView;
}
...
}
Service
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.etsii.fvt.domains.Tracking;
import us.etsii.fvt.repositories.TrackingRepository;
#Service
public class TrackingService {
#Autowired
private TrackingRepository trackingRepository;
public Tracking findTrackingByName(String name) {
return trackingRepository.findByTrackingName(name);
}
public void saveTracking(Tracking tracking) {
trackingRepository.save(tracking);
}
public List<Tracking> findAll() {
return trackingRepository.findAll();
}
public Tracking findById(String id) {
Optional<Tracking> t = trackingRepository.findById(id);
if(!t.isPresent()) {
return null;
}
return t.get();
}
public void remove(String id) {
trackingRepository.deleteById(id);
}
}
There are ambiguous points in your question but assuming you have an User Entity:
You should get the logged in user from Spring Security
You should include a relation of User Entity to Tracking Entity (include User ID information in Tracking records)
Then you should query the mongo db Tracking Entity with the given user id.
You can use standard query by field functionality of Spring Repository.

Supporting Multiple data sources of Mongo using Spring data

I am trying to configure two different mongo data sources using spring data.According to my requirement I need to change my scanning of base package dynamically at run time. The user can select the data source for a particular entity via property file by providing datasource and entity mapping.
Eg: entity1:dataSource1, entity2:dataSource2. Depending on this mapping I need to package names and need to replace in the #EnableMongoRepositories(basePackages="xxx.xxx.xxxx") at run time. I tired a lot using both Xml configuration and java configuration.But I could not find a possible way.Could some one please provide a solution for the problem if it is there.I am pasting the Entity classes ,Repositories and Configuration both XML and Java Config
package com.account.entity;
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "SampleAccount")
public class Account {
#Id
private String acntName;
#Indexed
private Date startDate;
#Indexed
private String accntType;
private Long acntId;
private Byte byteField;
public String getAcntName() {
return this.acntName;
}
public void setAcntName(String acntName) {
this.acntName = acntName;
}
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getAccntType() {
return this.accntType;
}
public void setAccntType(String accntType) {
this.accntType = accntType;
}
public Long getAcntId() {
return this.acntId;
}
public void setAcntId(Long acntId) {
this.acntId = acntId;
}
public Byte getByteField() {
return this.byteField;
}
public void setByteField(Byte byteField) {
this.byteField = byteField;
}
}
public interface AccountRepository extends MongoRepository<Account, String>{
public Page<Account> findByAcntNameOrStartDate(String acntName, Date startDate, Pageable pageable);
public Page<Account> findByAccntTypeOrStartDate(String accntType, Date startDate, Pageable pageable);
public Account findByAcntName(String acntName);
public Page<Account> findByAcntNameIn(List<String> pkIdList, Pageable pageable);
}
package com.user.entity;
import java.io.Serializable;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "SampleUser")
public class User {
#Id
private String acntName;
#Indexed
private Date startDate;
#Indexed
private String accntType;
private Long acntId;
private Byte byteField;
public String getAcntName() {
return this.acntName;
}
public void setAcntName(String acntName) {
this.acntName = acntName;
}
public Date getStartDate() {
return this.startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getAccntType() {
return this.accntType;
}
public void setAccntType(String accntType) {
this.accntType = accntType;
}
public Long getAcntId() {
return this.acntId;
}
public void setAcntId(Long acntId) {
this.acntId = acntId;
}
public Byte getByteField() {
return this.byteField;
}
public void setByteField(Byte byteField) {
this.byteField = byteField;
}
}
package com.user.repo;
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import com.account.entity.Account;
import com.user.entity.User;
public interface UserRepository extends MongoRepository<User, String>{
public Page<Account> findByAcntNameOrStartDate(String acntName, Date startDate, Pageable pageable);
public Page<Account> findByAccntTypeOrStartDate(String accntType, Date startDate, Pageable pageable);
public Account findByAcntName(String acntName);
public Page<Account> findByAcntNameIn(List<String> pkIdList, Pageable pageable);
}
JavaConfig Files:
MongoConfig.class
package com.Config;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
#Configuration
#EnableMongoRepositories(basePackages = {"xxx.xxx.xxx"},mongoTemplateRef="primaryTemplate")
public class MongoConfig {
#Resource
Environment environment;
public #Bean(name = "primarydb")
MongoDbFactory mongoDbFactory() throws Exception {
MongoCredential credential = MongoCredential.createCredential(
(environment.getProperty("xxx.datastore.mongo.server.userName")),
environment.getProperty("xxx.datastore.mongo.server.database"),
environment.getProperty("xxx.datastore.mongo.server.password").toCharArray());
List<MongoCredential> mongoCredentials = new ArrayList<>();
mongoCredentials.add(credential);
MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(
Integer.parseInt(environment.getProperty("xxx.datastore.mongo.server.connectionsPerHost")))
.build();
List<ServerAddress> serverAddress = new ArrayList<>();
prepareServerAddress(serverAddress);
MongoClient mongoClient = new MongoClient(serverAddress, mongoCredentials, options);
return new SimpleMongoDbFactory(mongoClient,
environment.getProperty("xxx.datastore.mongo.server.database"));
}
private void prepareServerAddress(List<ServerAddress> serverAddress) throws UnknownHostException {
String serverAddressList[] = environment.getProperty("XDM.datastore.mongo.server.address")
.split("\\s*,\\s*");
for (String svrAddress : serverAddressList) {
String address[] = svrAddress.split("\\s*:\\s*");
String host = Objects.nonNull(address[0]) ? address[0] : "127.0.0.1";
Integer port = Objects.nonNull(address[1]) ? Integer.valueOf(address[1]) : 27017;
serverAddress.add(new ServerAddress(host, port));
}
}
#Primary
public #Bean(name = "primaryTemplate")
MongoTemplate mongoTemplate(#Qualifier(value = "primarydb") MongoDbFactory factory) throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(factory);
return mongoTemplate;
}
}

Getting error "No serializer found for class org.springframework.data.mongodb.core.convert.DefaultDbRefResolver$LazyLoadingInterceptor"

I am using spring data mongodb,after doing lazy loading true i am getting error "No serializer found for class org.springframework.data.mongodb.core.convert.DefaultDbRefResolver$LazyLoadingInterceptor".
My domain class is
public class Preference extends BaseEntity {
#DBRef(lazy = true)
User user;
MetadataEnum preferenceType;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public MetadataEnum getPreferenceType() {
return preferenceType;
}
public void setPreferenceType(MetadataEnum preferenceType) {
this.preferenceType = preferenceType;
}
public List<Subtype> getSubtypes() {
return subtypes;
}
public void setSubtypes(List<Subtype> subtypes) {
this.subtypes = subtypes;
}
List<Subtype> subtypes = new ArrayList<Subtype>();
boolean enableSearch;
}
i have wasted my time alot,but i am unable to get suitable answer of it? anyone can help me to reslove it?
Thanks in advance
Add this configuration code for your requirement
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
#Configuration
public class LazyLoadingSerializationConfig {
#Bean
public ObjectMapper objectMapper() {
ObjectMapper om = new ObjectMapper();
final SimpleModule module = new SimpleModule("<your entity>", new Version(1, 0, 0,null));
module.addSerializer(LazyLoadingProxy.class, new LazyLoadingSerializer());
om.registerModule(module);
return om;
}
}
and
import java.io.IOException;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class LazyLoadingSerializer extends JsonSerializer<LazyLoadingProxy> {
#Override
public void serialize(LazyLoadingProxy value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("id", value.toDBRef().getId().toString());
jgen.writeEndObject();
}
}
Hope this may help you!
switch off serializer for that bean because lazy loading with #DBRef works for list of entity only , jackson automatically serialize the #DBRef(lazy = true) List user but not for '#DBRef(lazy = true) User user. So you have to serialize it mannually or switch off serializer for that bean'.