Как получить переменную поля на Java Spring

#java #spring #spring-boot #entity #field

#java #spring #spring-boot #сущность #поле

Вопрос:

У меня возникла проблема в моем проекте learn, в случае «если значение условия равно нулю, а затем еще, если поле значения условия равно нулю», например, мой код, следующий за этим кодом :

Для объекта Users.java :

 @Entity
public class Users {
    private Long id;
    private String employeeId;
    private String fullName;
    private String username;
    private String password;
    ...

    public Users() {
    }

    Some Code Setter and Getter....
}
  

Для объекта Employee.java :

 @Entity
public Class Employee {
    private Long id;
    private String employeeId;
    private String fullName;
    ...
    
    public Employee() {
    }
    
    Some Code Setter and Getter....
}
  

и затем для моего класса Service у меня есть случай для вставки данных Employee в репозиторий. В случае, если у нас есть данные проверки перед вставкой данных в таблицу Employee, нам нужно проверить, что table users не null, а затем в поле EmployeeID должно быть null. с моим кодом, следующим за этим :

Для репозитория UserRepo.java и EmployeeRepo.java :

 @Repository
public interface EmployeeRepo extends CrudRepository<Employee, Long> {

}

@Repository
public interdace UsersRepo extends CrudRepository<Users, Long> {

@Transactional
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("UPDATE Users u SET u.employeeId = :employeeId WHERE u.id = :id")
public void updateEmployeeIdUsers(@Param("id") Long id, @Param("employeeId") String employeeId);

}
  

Для сервиса UsersService.java :

 @Service("usersService")
public class UsersService {
    
    @Autowired
    private UsersRepo repo;
    
    public Optional<Users> findById(Long id) {
        return repo.findById(id);
    }
    
    public void updateEmployeeIdUsers(Long id, String employeeId) {
        repo.updateEmployeeIdUsers(id, employeeId);
    }

}
  

Для сервиса EmployeeService.java :

 @Service("employeeService")
public class EmployeeService {
    
    @Autowired
    private EmployeeRepo employeeRepo;
    
    @Autowired
    private UsersService userService;
    
    public Employee insertEmployee(Employee employee) throws Exception {
        Optional<Users> users = userService.findById(employee.getId());
        Users userOptional = new Users(); **//on this my problem**
        userOptional.getEmployeeId(); **//on this my problem**
        if (!users.isPresent()) {
            throw new Exception("User ID : "  employee.getId()  " Not Founded");
        }else if (!(userOptional == null)) { **//on this my problem**
            throw new Exception("User employeID : "  employee.getEmployeeId()  " Already Exist on Users");
        }
        
        String str1 = "TEST";
        Long idUser = employee.getId();
        userService.updateEmployeeIdUsers(idUser, str1);
        return employeeRepo.save(employee);
    }

}
  

в этом коде у нас проблема с else, если параметр userOptional всегда равен NULL, и я пытаюсь выполнить отладку, чтобы увидеть значение в EmployeeID, просто я всегда вижу Null. итак, любая идея с моей проблемой, потому что я пытаюсь в каком-то случае всегда терпеть неудачу с моей проблемой. пожалуйста, если есть какие-либо идеи по моей проблеме, можете ответить на эти мои вопросы. большое спасибо за то, что ответили на мой вопрос.

Комментарии:

1. userOptional необязательное значение равно null, потому что этот объект пуст. Users userOptional = new Users(); в этом случае вы просто создаете пустой объект. Я не понимаю, какова цель вашего кода.

2. Ваш код всегда будет завершаться с ошибкой, потому что (!(userOptional == null)) будет true всегда. Вы создали экземпляр not null Users userOptional = new Users()

3. @Seldo97 да, это верно, я только что узнал об этом. но как это работает, потому что моя цель в этом коде: Необязательно<Users> users = UserService.findById(employee.getId()); Должно быть get значение, где это, чтобы получить EmployeeID. итак, как заставить этот employeId быть включенным в else if.

4. @doctoreкак получить этот EmployeeID из: Необязательно<Пользователи> users = UserService.findById(employee.getId()); для включения в else, если

5. Если я правильно понял, вы хотите найти Users by Employee.id (не экземпляр id of Users ). Если вы ее не нашли => возвращает исключение. Если вы нашли ее, но Users.employeeId не является null => возвращает исключение "User employeID : " employee.getEmployeeId() " Already Exist on Users" . Правильно ли это?

Ответ №1:

Для предлагаемого решения я предположу следующее:

  • Существует связь между Employee и Users .
  • Employee Может быть связано только с одним Users
  • username является ли естественный ключ Users
  • employeeId является ли естественный ключ Employee

Итак, сущности:

 @Entity
public class Users {

  @Id
  // This one is an example, you can use the configuration you need
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator= "users_seq")
  @SequenceGenerator(name="users_seq", initialValue=1, allocationSize=1, sequenceName = "users_id_seq")
  private Long id;

  @Column(name = "fullname")
  private String fullName;

  // Probably this column should be unique and you need to configure in that way here and in your database
  @Column
  private String username;

  @Column
  private String password;

  // Getter amp; setter amp; constructors
}



@Entity
public class Employee {

  @Id
  // This one is an example, you can use the configuration you need
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator= "employee_seq")
  @SequenceGenerator(name="employee_seq", initialValue=1, allocationSize=1, sequenceName = "employee_id_seq")
  private Long id;

  /**
   * Assuming this is your specific identifier for an employee (not related with database PK)
   *    If the assumption is correct, this column should be unique and you need to configure in
   * that way here and in your database
   */
  @Column(name = "employeeid")
  private String employeeId;

  /**
   * Not sure if this relation could be nullable or not
   */
  @OneToOne
  @JoinColumn(name = "users_id")
  private Users users;

  // Getter amp; setter amp; constructors
}
  

Как вы можете видеть, в обеих сущностях нет «повторяющихся столбцов», и между и OneToOne существует Employee однонаправленная Users связь. Если вам нужна двунаправленная переменная, эта ссылка поможет вам с этим: Двунаправленная OneToOne

Репозитории:

 @Repository
public interface UsersRepository extends CrudRepository<Users, Long> {
  Optional<Users> findByUsername(String username);
}



@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
  Optional<Employee> findByEmployeeId(String employeeId);
}
  

Сервисы:

 @Service
public class UsersService {

  @Autowired
  private UsersRepository repository;

  public Optional<Users> findByUsername(String username) {
    return Optional.ofNullable(username)
            .flatMap(repository::findByUsername);
  }

  public Optional<Users> save(Users user) {
    return Optional.ofNullable(user)
            .map(repository::save);
  }
}



@Service
public class EmployeeService {

  @Autowired
  private EmployeeRepository repository;

  @Autowired
  private UsersService usersService;

  public Optional<Employee> insert(Employee newEmployee) {
    /**
     * The next line don't make sense:
     *
     *   Optional<Users> users = userService.findById(employee.getId());
     *
     * I mean:
     *
     *  1. Usually, id column is configured with @GeneratedValue and manage by database. So you don't need to ask
     *     if that value exists or not in Users.
     *
     *  2. Even if you are including id's values manually in both entities what should be "asked" is:
     *
     *    2.1 Is there any Users in database with the same username than newEmployee.users.username
     *    2.2 Is there any Employee in database with the same employeeId
     *
     *    Both ones, are the natural keys of your entities (and tables in database).
     */
    return Optional.ofNullable(newEmployee)
            .filter(newEmp -> null != newEmp.getUsers())
            .map(newEmp -> {
                isNewEmployeeValid(newEmp);

                // Required because newEmp.getUsers() is a new entity (taking into account the OneToOne relation)
                usersService.save(newEmp.getUsers());

                repository.save(newEmp);
                return newEmp;
            });
  }

  private void isNewEmployeeValid(Employee newEmployee) {
    if (usersService.findByUsername(newEmployee.getUsers().getUsername()).isPresent()) {
        throw new RuntimeException("Username: "  newEmployee.getUsers().getUsername()  " exists in database");
    }
    if (repository.findByEmployeeId(newEmployee.getEmployeeId()).isPresent()) {
        throw new RuntimeException("EmployeeId: "  newEmployee.getEmployeeId()  " exists in database");
    }
  }
}
  

Комментарии:

1. спасибо, сэр, за ваш example…it это очень полезно, и тогда я могу попробовать сделать это. я вижу, что в вашем примере используется @onetoone, который я использую для этого, пытается это. но с вашим примером я могу разобраться со своей проблемой, а затем я смогу устранить мою проблему …. большое вам спасибо, сэр, за это…

Ответ №2:

После прочтения комментариев я уже понимаю вашу проблему.

 Users users = userService.findById(employee.getId()).orElseThrow(() -> new Exception("User ID : "  employee.getId()  " Not Founded"));
  

И теперь вы можете получить свой employeeId from users из возвращенного userService.findById(employee.getId()) ;

Пример:

 String employeeId = users.getEmployeeId(); // reference to your code
  

Но в этом случае, на мой взгляд, вам следует установить связь @OneToOne между users и employee или расширить users в employee классе.

Отношение «Один к одному» в JPA,
спящий режим-наследование

Комментарии:

1. О’кей, сэр, мне нужно попробовать ваше решение. итак, мне нужно изменить мой класс Entitiy на employeId становится отношением «@OneToOne» между пользователями таблицы и employee. мой текущий дизайн является ложным, потому что я не применил дизайн ‘@OneToOne или не расширил пользователей в классе employee …. спасибо, сэр, за ответ на мой вопрос ….. я обновлю после того, как попробую ваше решение, сэр. Я надеюсь, что это решение дает ответ, который я искал

2. И вам не нужен запрос на обновление. save() тоже работает как обновление.