调用Spring Data REST的save方法时接收含空变量对象的问题
Hey there, let's break down this empty variable issue you're facing—especially since your system has that critical multi-company association requirement. I've worked on similar multi-tenant Spring Data REST + React systems before, so here are the most common fixes to try:
1. Frontend Isn't Sending the Required Company Association
Since nearly all your models need a linked Company, the first thing to check is whether your React frontend is actually including this data in the API request payload.
- Common mistake: Forgetting to add a hidden field for the
companyId(or the full Company object) in your form, or not including it in the JSON body when making the POST/PUT request. - Fix example: When sending the request from React, make sure the
companyfield (orcompanyId, depending on your entity mapping) is present:// Example POST request in React const saveEntity = async (entityData) => { const currentCompanyId = getCurrentUserCompanyId(); // Get from your auth context const payload = { ...entityData, company: { id: currentCompanyId } // Match your entity's field name }; const response = await fetch('/api/your-entity-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getAuthToken()}` }, body: JSON.stringify(payload) }); }; - Note: If you're using Spring Data REST's HAL format, you could also link to the Company resource via
_links, but passing the ID is simpler for most cases.
2. Backend Entity Configuration Issues
Double-check your JPA entity's Company association setup—small misconfigurations here often lead to empty fields:
- Missing required constraints: If
Companyis mandatory, make sure your entity has@ManyToOne(optional = false)(this will throw an error if the field is empty, which helps catch issues early). Example:@Entity public class YourEntity { // Other fields... @ManyToOne(optional = false) @JoinColumn(name = "company_id") private Company company; // Getters and setters } - Field name mismatches: If your frontend sends
companyIdbut your entity usescompany, Spring won't map the value correctly. Either align the frontend payload with the entity's field name, or use@JsonProperty("companyId")on the entity field to map it explicitly. - Spring Data REST exposure settings: Ensure you haven't marked the
companyfield as non-exported with@RestResource(exported = false)—that would prevent Spring from accepting the value in save requests.
3. Permission/Interceptor Logic Is Clearing the Field
Since you have role-based access (some Employees have higher permissions), it's possible that a security interceptor or AOP aspect is modifying the incoming entity before it reaches the save method:
- Automatic Company population (better practice): Instead of letting the frontend send the Company ID (which is prone to tampering), auto-populate it from the current authenticated user's context. This also solves the empty variable issue. Example:
@RepositoryRestResource public interface YourEntityRepository extends JpaRepository<YourEntity, Long> { @Override @PreAuthorize("hasAnyRole('OWNER', 'ADMIN')") default <S extends YourEntity> S save(S entity) { // Fetch the current user's associated Company Authentication auth = SecurityContextHolder.getContext().getAuthentication(); CustomUserDetails user = (CustomUserDetails) auth.getPrincipal(); Company userCompany = user.getCompany(); entity.setCompany(userCompany); return JpaRepository.super.save(entity); } } - Check security filters: Make sure your Spring Security configuration isn't stripping or modifying request payload fields based on user roles.
4. Incorrect Content-Type or Serialization
Sometimes the issue is as simple as the frontend sending the wrong content type:
- Ensure your request includes the
Content-Type: application/jsonheader—if you're usingmultipart/form-datainstead, Spring might not parse the JSON payload correctly, leading to empty fields. - Validate the JSON payload structure using browser dev tools (Network tab) to confirm all required fields are present and spelled correctly.
If none of these fix the problem, sharing a snippet of your entity class and the exact frontend request payload would help narrow things down further!
内容的提问来源于stack exchange,提问作者GuiRitter

