繁体   English   中英

Hibernate不会级联实体保存

[英]Hibernate wouldn't cascade entity saving

我的程序有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;
    ...
}

我正在尝试使用Spring 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级联注释以及休眠级联注释,也不会永久保留Ip(*值)。 知道为什么发生此问题吗?

您将@manytomany标记为IP类管理的(mappedBy批注)。 您必须将“用户”添加到IP.user集合中,以使替换保持不变。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM