如何在 Java Spring 上获取字段变量
How to get Field Variable on Java Spring
我的学习项目有问题,例如“如果条件值为空,然后如果条件值字段为空”,例如我的代码遵循这些代码:
对于实体 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....
}
然后对于我的 Class 服务,我有插入数据 Employee with Repository 的案例。如果我们在向 table Employee 插入数据之前有验证数据,我们需要检查 table users not null 然后在字段 employeeId 应该为空。我的代码如下:
对于存储库 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);
}
}
在这段代码中,如果 userOptional 始终为 NULL,我们在 else 上遇到问题,我尝试调试以查看 employeeId 上的值,只是我总是看到 Null。所以对我的问题有任何想法,因为我尝试了一些案例总是因我的问题而失败。如果对我的问题有任何想法,请回答我的这些问题。非常感谢你回答我的问题。
看完评论我已经明白你的问题了。
Users users = userService.findById(employee.getId()).orElseThrow(() -> new Exception("User ID : "+ employee.getId() +" Not Founded"));
现在您可以从返回的 userService.findById(employee.getId())
;
中获取 users
中的 employeeId
示例:
String employeeId = users.getEmployeeId(); // reference to your code
但在这种情况下,我认为你应该在 users
和 employee
之间建立关系 @OneToOne
或在 employee
[=34= 中扩展 users
].
对于建议的解决方案,我将假设如下:
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 & setter & 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 & setter & constructors
}
如您所见,两个实体中都没有“重复列”,并且 Employee
和 [=] 之间存在 单向 OneToOne
关系14=]。如果你需要一个双向的,link 会帮助你:Bidirectional 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");
}
}
}
我的学习项目有问题,例如“如果条件值为空,然后如果条件值字段为空”,例如我的代码遵循这些代码:
对于实体 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....
}
然后对于我的 Class 服务,我有插入数据 Employee with Repository 的案例。如果我们在向 table Employee 插入数据之前有验证数据,我们需要检查 table users not null 然后在字段 employeeId 应该为空。我的代码如下:
对于存储库 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);
}
}
在这段代码中,如果 userOptional 始终为 NULL,我们在 else 上遇到问题,我尝试调试以查看 employeeId 上的值,只是我总是看到 Null。所以对我的问题有任何想法,因为我尝试了一些案例总是因我的问题而失败。如果对我的问题有任何想法,请回答我的这些问题。非常感谢你回答我的问题。
看完评论我已经明白你的问题了。
Users users = userService.findById(employee.getId()).orElseThrow(() -> new Exception("User ID : "+ employee.getId() +" Not Founded"));
现在您可以从返回的 userService.findById(employee.getId())
;
users
中的 employeeId
示例:
String employeeId = users.getEmployeeId(); // reference to your code
但在这种情况下,我认为你应该在 users
和 employee
之间建立关系 @OneToOne
或在 employee
[=34= 中扩展 users
].
对于建议的解决方案,我将假设如下:
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 & setter & 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 & setter & constructors
}
如您所见,两个实体中都没有“重复列”,并且 Employee
和 [=] 之间存在 单向 OneToOne
关系14=]。如果你需要一个双向的,link 会帮助你:Bidirectional 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");
}
}
}