2015-02-23 89 views
0

我的程序有2個實體:休眠不會級聯實體節約

@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; 
    ... 
} 

我試圖使用JPA春天像倉庫下列堅持一個新的用戶:

@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); 

問題是,即使我添加了JPA級聯註釋以及hibernate級聯註釋,Ip(*值)也永遠不會持久化。任何想法爲什麼這個問題發生?

回答

1

您將@manytomany標記爲由IP類(mappedBy註釋)管理。您必須將用戶添加到IP.user集合才能保持關聯。

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

已解決。謝謝 ! – 2015-02-23 23:44:59