使用Spring在MongoDb中的FinAll只返回一条记录

时间:2017-07-10 10:43:07

标签: java spring mongodb spring-boot

问题是一旦我使用方法findAll使用MongoOperation接口,它工作正常,没有异常,但只返回一个记录,但该集合包含多个记录。我尝试了一个不同的界面,如mongotemp,同样的结果,列表大小总是返回1,即使我从dao本身尝试它

使用mongodb配置Spring DATA

@Configuration
public class MongodbConfig {

public @Bean MongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(new MongoClient(), "inSpace");
}

public @Bean MongoTemplate mongoTemplate() throws Exception {

    MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
    return mongoTemplate;

}
}

DAO课程

@Repository
public class GenericDAOImpl<T> implements GenericDAO<T>  {

@Autowired
protected MongoOperations mongoOper;

public <T> void save(T ct) {
    mongoOper.save(ct);
}

public <T> void remove(T ct) {
    mongoOper.remove(ct);
}

public T getBydId(String id, Class<T> clazz) {
    return mongoOper.findById(id, clazz);
}

public List<T> getAll(Class<T> clazz) {
    System.err.println(" '''''''  " + mongoOper.findAll(clazz).size());
    return mongoOper.findAll(clazz);
}

}

注意:单个项目中的上两个类,并用作包含以下类的其他项目的依赖项

服务呼叫DAO

@Service("userService")
public class UserServiceImpl implements UserService {

@Autowired
private  GenericDAO<Users> userDAO;

public Users create(Users user) {
    userDAO.save(user);
    return user;
}

public Users delete(String id) {
    Users user = userDAO.getBydId(id, Users.class);
    userDAO.remove(user);
    return user;
}

public List<Users> findAll() {
    System.out.println("inside User Service");
    return userDAO.getAll(Users.class);
}

public Users findById(String id) {
    return userDAO.getBydId(id , Users.class);
}

}

控制器类

@RestController
@RequestMapping("/user") 
public class UsersController {

@Autowired
UserService userService;


@RequestMapping(method = RequestMethod.GET, value = "/allUsers")
List<Users> getAllRegistedUsers() {
    System.out.println("inside  UserController");
    return userService.findAll();
}

}

配置类

@SpringBootApplication
@ComponentScan(basePackageClasses=
{UsersController.class,UserService.class,GenericDAO.class})
public class UsersConfiguration {

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

}

}

注意:当我尝试在Main方法中注入bean并通过ApplicationContext使用bean时,它工作正常并返回数据库中的所有记录!

0 个答案:

没有答案