Package com.fengjing.framework.mongodb.service

Source Code of com.fengjing.framework.mongodb.service.UserService

package com.fengjing.framework.mongodb.service;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fengjing.framework.mongodb.domain.User;
import com.fengjing.framework.mongodb.repository.RoleRepository;
import com.fengjing.framework.mongodb.repository.UserRepository;

@Service
public class UserService {

  @Autowired
  private UserRepository userRepository;
 
  @Autowired
  private RoleRepository roleRepository;
 
  public User create(User user) {
    user.setId(UUID.randomUUID().toString());
    user.getRole().setId(UUID.randomUUID().toString());
   
    // We must save both separately since there is no cascading feature
    // in Spring Data MongoDB (for now)
    roleRepository.save(user.getRole());
    return userRepository.save(user);
  }
 
  public User read(User user) {
    return user;
  }
 
  public List<User> readAll() {
    return userRepository.findAll();
  }
 
  public User update(User user) {
    User existingUser = userRepository.findByUsername(user.getUsername());
   
    if (existingUser == null) {
      return null;
    }
   
    existingUser.setFirstName(user.getFirstName());
    existingUser.setLastName(user.getLastName());
    existingUser.getRole().setRole(user.getRole().getRole());
   
    // We must save both separately since there is no cascading feature
    // in Spring Data MongoDB (for now)
    roleRepository.save(existingUser.getRole());
    return userRepository.save(existingUser);
  }
 
  public Boolean delete(User user) {
    User existingUser = userRepository.findByUsername(user.getUsername());
   
    if (existingUser == null) {
      return false;
    }
   
    // We must delete both separately since there is no cascading feature
    // in Spring Data MongoDB (for now)
    roleRepository.delete(existingUser.getRole());
    userRepository.delete(existingUser);
    return true;
  }
}
TOP

Related Classes of com.fengjing.framework.mongodb.service.UserService

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.