Spring Crude Repository无法更新实体,新手求助
Hey there! Let's figure out why your Organisation update isn't working with CrudRepository. Since you're new to Spring, I'll break down the most common pitfalls step by step—no overly technical jargon, promise!
1. Double-check your Entity's Primary Key Setup
CrudRepository's save() method decides whether to insert a new record or update an existing one entirely based on the entity's primary key. If this is misconfigured, it'll always default to creating a new Organisation instead of updating.
- Make sure your
Organisation.javahas a properly annotated primary key:@Entity public class Organisation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) // Adjust strategy based on your DB private Long id; // Other fields (name, address, etc.) // Getters and setters } - When trying to update, ensure the
Organisationobject you pass tosave()has an existing, valid primary key value (notnullor a value that doesn't exist in the database). If the id is missing, JPA will treat it as a new entity.
2. Use the Correct Update Pattern
A super common mistake for new Spring devs is creating a brand-new Organisation object, setting only the fields you want to change, and calling save(). This won't work because the new object has no link to an existing database record.
Instead, follow this pattern in your service layer:
@Service public class OrganisationService { private final OrganisationRepository organisationRepository; // Constructor injection (preferred over @Autowired) public OrganisationService(OrganisationRepository organisationRepository) { this.organisationRepository = organisationRepository; } public Organisation updateOrganisation(Long orgId, Organisation updatedDetails) { // 1. Fetch the existing entity from the database Organisation existingOrg = organisationRepository.findById(orgId) .orElseThrow(() -> new RuntimeException("Organisation not found with id: " + orgId)); // 2. Update only the fields you need to change existingOrg.setName(updatedDetails.getName()); existingOrg.setAddress(updatedDetails.getAddress()); // Add other fields here // 3. Save the modified existing entity (triggers an update, not insert) return organisationRepository.save(existingOrg); } }
The key here is modifying an entity that JPA already "manages" (from the findById call)—this tells JPA to update the existing record instead of creating a new one.
3. Verify Your Primary Key Generation Strategy
If you're using @GeneratedValue(strategy = GenerationType.IDENTITY) (common for auto-incrementing IDs in MySQL/PostgreSQL), manually setting an ID value might be ignored by the database, leading to a new record instead of an update.
- If you need to manually specify IDs for updates, consider switching to a strategy like
GenerationType.AUTOorGenerationType.SEQUENCE(depending on your database), or ensure the ID you're passing is definitely present in the database.
4. Check for Transaction Support
Sometimes updates fail silently because there's no transaction wrapping the operation. Spring Data JPA relies on transactions to persist changes to managed entities.
Add the @Transactional annotation to your service layer update method to ensure proper transaction management:
@Transactional // Adds transaction support for the method public Organisation updateOrganisation(Long orgId, Organisation updatedDetails) { // ... existing update logic ... }
Start with checking points 1 and 2 first—those are the most frequent culprits for new Spring developers. Let me know if you need to share more code snippets from your Organisation.java or service layer!
内容的提问来源于stack exchange,提问作者Danail Kondov

