场景: 我有3个表,Offer,Channel和Offer_Channels。 基本上,Channel是一个查找表,即该表中的值既不能被应用程序插入也不能被应用程序更新。优惠可包含一个或多个频道。我使用Channel表值来填充动态复选框。无论如何,所以这就是我所拥有的:
@Entity
@Table(name = "OFFER")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Offer implements Serializable {
// Offer Id
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "offer_seq_gen")
@Column(name = "OFFER_ID")
private long OfferId;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "OFFER_CHANNELS", joinColumns = { @JoinColumn(name = "OFFER_ID") }, inverseJoinColumns = { @JoinColumn(name = "CHANNEL_ID") })
private Set<Channel> channels = new HashSet<Channel>();
//Other fields and corresponding getters and setters
}
这是Channel实体:
@Entity
@Table(name = "CHANNEL")
public class Channel implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Id
@Column(name = "CHANNEL_ID", insertable=false, updatable=false)
private Long channelId;
@Column(name = "CHANNEL_NAME", insertable=false, updatable=false)
private String channelName;
//getters and setters
}
现在,当用户创建商品时,我需要在Offer表和Offer_Channels表中插入行,并且不对Channel表执行任何操作(无更新/插入)。最初,所有这三个都会发生,所以要实现对通道表&#34;不做任何事情。部分,我在Channel表列上放置了insertable = false和updateable = false,就像魅力一样。现在我使用普通的Hibernates。我的意思是我写了一个独立的java应用程序和一个主类来添加使用hibernate的session.save(offer)的商品。它运行了以下查询:
Hibernate: insert into OFFER
Hibernate: insert into OFFER_CHANNELS
好吧,现在,我有一个休息服务,我使用Spring的JPA存储库来保存信息,我有相同的域对象设置。现在,当我添加优惠时,它会运行:
Hibernate: insert into OFFER
Hibernate: insert into CHANNEL ( It is failing here obviously. I don't want this step to happen)
我的问题: 1.为什么它试图向Channel表写一些东西,即使我在其domain对象中给出了insertable = false,这只是在Spring JPA设置中发生的。使用hibernate设置它可以正常工作。 3.不是@ JoinTable / @OneToMany / insertable / updateble,适合Spring JPA存储库吗? 我在这里缺少什么?
更新:
@Service
@Transactional
public class OfferService {
@Inject
private OfferRepository offerRepository;
public Offer saveOfferInformation(Offer offer) {
log.debug("Saving Offer Info..");
log.debug("Offer object :"+offer);
return offerRepository.save(offer);
}
}
回购:
public interface OfferRepository extends JpaRepository<Offer, Long> {
List<Offer> findByBuySku(String buySku);
}
在REST服务中我只是注入服务并调用它,因此REST服务中没有业务逻辑。现在我得到了,原因是它试图将记录插入频道表:
exception: "org.springframework.dao.DataIntegrityViolationException"
message: "could not execute statement; SQL [n/a]; constraint [PVS_OWNER.CHANNEL_PK]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"