在我的代码下面,我在使用Hibernate和与额外列的多对多关系时遇到了麻烦:
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(schema = "XXX", name = "YYY")
@Audited
public class TransactionEntity extends AbstractBaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(insertable = false, updatable = false)
private Long transactionId;
// fields
@OneToMany(mappedBy = "transaction", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<TransactionTagEntity> tags;
}
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(schema = "XXX", name = "ZZZ")
@Audited
public class TagEntity extends AbstractBaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(insertable = false, updatable = false)
private Long tagId;
// fields
}
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(schema = "XXX", name = "YYY_ZZZ")
@Audited
public class TransactionTagEntity extends AbstractBaseEntity {
@EmbeddedId
private TransactionTagPk pk;
@ManyToOne
@MapsId("transactionId")
@JoinColumn(name = "transaction_id", referencedColumnName = "transactionId", insertable = false, updatable = false)
private TransactionEntity transaction;
@ManyToOne
@MapsId("tagId")
@JoinColumn(name = "tag_id", referencedColumnName = "tagId", insertable = false, updatable = false)
private TagEntity tag;
}
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
@Embeddable
public class TransactionTagPk implements Serializable {
@Column(name = "transaction_id")
private Long transactionId;
@Column(name = "tag_id")
private Long tagId;
}
在持久性适配器中,我有一个接收事务ID和现有标记ID列表的方法。首先,我通过事务ID查找事务,然后搜索标记并构建事务实体列表。然后,我删除与事务关联的所有标记并插入新创建的列表。最后,我保存事务。
我的代码如下:
@Override
public void addTags(long transactionId, List<Long> tagsId) {
Optional<TransactionEntity> transactionEntity = transactionRepository.findById(transactionId);
if (transactionEntity.isEmpty()) {
throw new ForeignKeyConstraintViolatedException("Transaction not found");
}
List<TransactionTagEntity> transactionTagEntityList = tagsId.stream().map(tagId -> buildTransactionTagEntity(transactionEntity.get(), tagId)).toList();
transactionEntity.get().getTags().clear();
transactionEntity.get().setTags(transactionTagEntityList);
transactionRepository.save(transactionEntity.get());
}
private TransactionTagEntity buildTransactionTagEntity(final TransactionEntity entity, final long tagId) {
TagEntity tagEntity = tagRepository.findById(tagId).orElseThrow(() -> new ForeignKeyConstraintViolatedException("Tag not found"));
return new TransactionTagEntity(entity, tagEntity);
}
执行这段代码时,我在保存操作时遇到以下错误:
jakarta.servlet.ServletException: Request processing failed: java.lang.UnsupportedOperationException
我哪里做错了?
1条答案
按热度按时间xghobddn1#
我已经解决了在交易实体中使用此代码: