Announcement Announcement Module
Collapse
No announcement yet.
JpaRepository.save() -> detached entity passed to persist...? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • JpaRepository.save() -> detached entity passed to persist...?

    i'm working with a ManyToOne relationship, for example there are many LineItem entities to one Order entity.

    i have cascade={CascadeType.PERSIST} on LineItem.

    i have a LineItemRepository which extends org.springframework.data.jpa.repository.JpaReposit ory.

    i call LineItemRepository.save() on a LineItem and it saves the LineItem and cascades to the Order, so far so good.

    then i'll call LineItemRepository.save() on another LineItem which references the previously saved Order, and i get:

    Code:
    javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist:
    i kind of expected it to casade to the Order and then realize that nothing has changed in the Order and ignore it.

    what would be an appropriate pattern to emulate for this scenario...?

    thanks,
    tony.

  • #2
    i was able to resolve this using the following section in the spring data jpa documentation:

    Another possibility to alter transactional behaviour is using a facade or service implementation that typically
    covers more than one repository. Its purpose is to define transactional boundaries for non-CRUD operations:
    Example 2.12. Using a facade to define transactions for multiple repository calls

    Code:
    @Service
    class UserManagementImpl implements UserManagement {
    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    @Autowired
    public UserManagementImpl(UserRepository userRepository,
    RoleRepository roleRepository) {
    this.userRepository = userRepository;
    this.roleRepository = roleRepository;
    }
    @Transactional
    public void addRoleToAllUsers(String roleName) {
    Role role = roleRepository.findByName(roleName);
    for (User user : userRepository.readAll()) {
    user.addRole(role);
    userRepository.save(user);
    }
    }

    Comment

    Working...
    X