Omar BELKHODJA
Omar BELKHODJA

Reputation: 1902

Hibernate wouldn't cascade entity saving

My program has 2 entities:

@Entity
public class User implements Serializable {

    @ManyToMany(cascade={CascadeType.ALL},fetch = FetchType.EAGER,
                targetEntity = Ip.class,mappedBy = "user")
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)    
    private Collection<Ip> allowedIp;
    ...
}

@Entity
public class Ip implements Serializable {
    @Column(unique=false,updatable=true,insertable=true,nullable=true,
            length=255,scale=0,precision=0)
    @Id
    private String value;
    @ManyToMany(targetEntity = User.class)
    private Collection<User> user;
    ...
}

I'm trying to persist a new User using a Spring JPA repository like the following:

@Transactional (readOnly = false)
@Repository
public interface UserRepository extends JpaRepository<User, String> {
}

List<Ip> allowedIp = new ArrayList<Ip>();
allowedIp.add(ipRepository.findOne("*"));

User user = new User();
user.setAllowedIp(allowedIp);

userRepository.save(user);

The problem is that Ip (the * value) is never persisted although if I added the JPA cascading annotation, and also the hibernate cascading annotation. Any idea why this problem is happening ?

Upvotes: 0

Views: 164

Answers (1)

Zielu
Zielu

Reputation: 8562

You marked the @manytomany as mannaged by the IP class (mappedBy annotation). You have to add the User to the IP.user collection to have the reletionship persisted.

for (Ip ip : allowedIp) ip.getUser().add(user) 

Upvotes: 1

Related Questions