如何在Java Spring中获取字段变量

huangapple go评论69阅读模式
英文:

How to get Field Variable on Java Spring

问题

我在学习项目中遇到了一个问题,就是在以下情况下:"如果条件值为空,然后 else if 条件值字段为空",例如我的代码如下:

对于实体 Users.java

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

    public Users() {
    }

    // 一些设置器和获取器的代码...
}

对于实体 Employee.java

@Entity
public class Employee {
    private Long id;
    private String employeeId;
    private String fullName;
    // ...
    
    public Employee() {
    }
    
    // 一些设置器和获取器的代码...
}

然后,在我的服务类中,我有一个用于插入员工数据到仓库的情况。在这个情况下,在将数据插入到员工表之前,我们需要验证数据,确保 users 表不为空,并且字段 employeeId 应该为空。我的代码如下:

对于仓库 UserRepo.javaEmployeeRepo.java

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

}

@Repository
public interface 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(); // 这是我的问题
        userOptional.getEmployeeId(); // 这是我的问题
        if (!users.isPresent()) {
            throw new Exception("User ID : " + employee.getId() + " Not Founded");
        } else if (!(userOptional == null)) { // 这是我的问题
            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 if 中的 userOptional 总是为 NULL,并且我尝试调试以查看 employeeId 的值,但总是看到它是 NULL。所以,如果有关于我的问题的任何想法,可以回复我的问题。非常感谢你们对解答我的问题。

英文:

I has a issue on my learn project, on case "if condition value is null and then else if condition value field is null" for example my code following these code :

For Entity 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....
}

For Entity Employee.java :

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

and then for my Class Service i have case for insert data Employee with Repository. On case we have validation data before insert data to table Employee, we need to check table users not null and then on field employeeId should null. with my code following this :

For Repository UserRepo.java and EmployeeRepo.java :

@Repository
public interface EmployeeRepo extends CrudRepository&lt;Employee, Long&gt; {

}

@Repository
public interdace UsersRepo extends CrudRepository&lt;Users, Long&gt; {

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

}

For Service UsersService.java :

@Service(&quot;usersService&quot;)
public class UsersService {
	
	@Autowired
	private UsersRepo repo;
	
	public Optional&lt;Users&gt; findById(Long id) {
		return repo.findById(id);
	}
	
	public void updateEmployeeIdUsers(Long id, String employeeId) {
		repo.updateEmployeeIdUsers(id, employeeId);
	}

}

For Service EmployeeService.java :

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

}

on this code we have problem on else if userOptional is always NULL and i try to debug to see value on employeeId just i see always Null. so any idea with my problem because i try some case alway fail with my issue. please if any idea for my issue, can reply these my question. is very thank you of all about thing to answer my question.

答案1

得分: 1

阅读了评论后,我已经理解您的问题。

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

现在您可以从返回的 `userService.findById(employee.getId())` 中获取 `users` 中的 `employeeId`。

**示例:**

```java
String employeeId = users.getEmployeeId(); // 参考您的代码

但在这种情况下,我认为您应该在 usersemployee 之间建立 @OneToOne 关系,或者在 employee 类中扩展 users

JPA 中的一对一关系
hibernate 继承


<details>
<summary>英文:</summary>

After read comments I already understand your problem.

    Users users = userService.findById(employee.getId()).orElseThrow(() -&gt; new Exception(&quot;User ID : &quot;+ employee.getId() +&quot; Not Founded&quot;));

And now you can get your `employeeId` from `users` from returned `userService.findById(employee.getId())`;

**Example:**

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

But in this case in my opinion you should make relation `@OneToOne` between `users` and `employee` or extend `users` in `employee` class.

[One-To-One relation in JPA][1],
[hibernate-inheritance][2]


  [1]: https://www.baeldung.com/jpa-one-to-one
  [2]: https://www.baeldung.com/hibernate-inheritance

</details>



# 答案2
**得分**: 1

对于提出的解决方案,我将做以下假设:

 - `Employee` 和 `Users` 之间存在关系。
 - 一个 `Employee` 只能与一个 `Users` 相关联。
 - `username` 是 `Users` 的自然键。
 - `employeeId` 是 `Employee` 的自然键。

因此,以下是**实体**部分的翻译:

```java
@Entity
public class Users {

  @Id
  @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;

  @Column
  private String username;

  @Column
  private String password;

  // Getter & setter & constructors
}

@Entity
public class Employee {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_seq")
  @SequenceGenerator(name = "employee_seq", initialValue = 1, allocationSize = 1, sequenceName = "employee_id_seq")
  private Long id;

  @Column(name = "employeeid")
  private String employeeId;

  @OneToOne
  @JoinColumn(name = "users_id")
  private Users users;

  // Getter & setter & constructors
}

仓库部分的翻译:

@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) {
    return Optional.ofNullable(newEmployee)
            .filter(newEmp -> null != newEmp.getUsers())
            .map(newEmp -> {
                isNewEmployeeValid(newEmp);

                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");
    }
  }
}
英文:

For the proposed solution, I will assume the following:

  • There is relation between Employee and Users.
  • An Employee can be related with only one Users
  • username is the natural key of Users
  • employeeId is the natural key of Employee

So the entities:

@Entity
public class Users {
@Id
// This one is an example, you can use the configuration you need
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator= &quot;users_seq&quot;)
@SequenceGenerator(name=&quot;users_seq&quot;, initialValue=1, allocationSize=1, sequenceName = &quot;users_id_seq&quot;)
private Long id;
@Column(name = &quot;fullname&quot;)
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= &quot;employee_seq&quot;)
@SequenceGenerator(name=&quot;employee_seq&quot;, initialValue=1, allocationSize=1, sequenceName = &quot;employee_id_seq&quot;)
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 = &quot;employeeid&quot;)
private String employeeId;
/**
* Not sure if this relation could be nullable or not
*/
@OneToOne
@JoinColumn(name = &quot;users_id&quot;)
private Users users;
// Getter &amp; setter &amp; constructors
}

As you can see, there are no "repeated columns" in both entities and there is an unidirectional OneToOne relation between Employee and Users. If you need a bidirectional one, this link will help you with it: Bidirectional OneToOne

The repositories:

@Repository
public interface UsersRepository extends CrudRepository&lt;Users, Long&gt; {
Optional&lt;Users&gt; findByUsername(String username);
}
@Repository
public interface EmployeeRepository extends CrudRepository&lt;Employee, Long&gt; {
Optional&lt;Employee&gt; findByEmployeeId(String employeeId);
}

The services:

@Service
public class UsersService {
@Autowired
private UsersRepository repository;
public Optional&lt;Users&gt; findByUsername(String username) {
return Optional.ofNullable(username)
.flatMap(repository::findByUsername);
}
public Optional&lt;Users&gt; save(Users user) {
return Optional.ofNullable(user)
.map(repository::save);
}
}
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository repository;
@Autowired
private UsersService usersService;
public Optional&lt;Employee&gt; insert(Employee newEmployee) {
/**
* The next line don&#39;t make sense:
*
*   Optional&lt;Users&gt; users = userService.findById(employee.getId());
*
* I mean:
*
*  1. Usually, id column is configured with @GeneratedValue and manage by database. So you don&#39;t need to ask
*     if that value exists or not in Users.
*
*  2. Even if you are including id&#39;s values manually in both entities what should be &quot;asked&quot; 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 -&gt; null != newEmp.getUsers())
.map(newEmp -&gt; {
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(&quot;Username: &quot;+ newEmployee.getUsers().getUsername() +&quot; exists in database&quot;);
}
if (repository.findByEmployeeId(newEmployee.getEmployeeId()).isPresent()) {
throw new RuntimeException(&quot;EmployeeId: &quot;+ newEmployee.getEmployeeId() +&quot; exists in database&quot;);
}
}
}

huangapple
  • 本文由 发表于 2020年8月16日 00:40:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63428461.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定