【发布时间】:2016-07-09 16:51:50
【问题描述】:
有两个实体,
1.状态(两列:statusId状态)
例如值:1 ACTIVE、2 INACTIVE 等)
2.优惠券(三栏:couponId title statusId)
例如值:10 个橙子 1、20 个苹果 2 等)
试图弄清楚要使用什么关系以及如何使用。我尝试过 OneToOne、OneToMany、ManyToOne、ManyToMany 等,但每次状态实体都会添加一个新行
例如21 活跃,22 活跃,23 活跃,等等。
每次保存新优惠券时,Coupon 实体都应获取一个新行,并在 status id 字段中使用 status 的主键,但应添加一个新行。
Yes, Many coupons can share the same status.
The following code produces the following results
Before execution
Status Table
StatusId STATUS
1 ACTIVE
2 INACTIVE
Coupon Table
CouponId Title STATUS
<no rows at present>
After execution
Status Table
StatusId STATUS
1 ACTIVE
2 INACTIVE
3 ACTIVE (This row should not get inserted)
Coupon Table
CouponId Title StatusId
10 Apples 3 (StatusId should be 1 instead of 3)
JSON Request:
{
"title": "Apples",
"status": "ACTIVE",
}
Code:
@Autowired
CouponRespository couponRepository;
@RequestMapping(value = "/coupon", method = RequestMethod.POST)
void createCoupon(@RequestBody Coupon coupon) {
couponRepository.save(coupon);
}
public interface CouponRespository extends JpaRepository<Coupon, Long> {
}
@Entity
public class Status implements Serializable {
@Id
@SequenceGenerator(name = "STATUS_STATUSID_GENERATOR", sequenceName = "STATUS_ID_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STATUS_STATUSID_GENERATOR")
@Column(name = "STATUS_ID")
private long statusId;
@Column(name = "STATUS")
private String status;
}
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "couponId")
@JsonIgnoreProperties({ "statusId" })
public class Coupon implements Serializable {
@Id
@SequenceGenerator(name = "COUPON_COUPONID_GENERATOR", sequenceName = "COUPON_ID_SEQ")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COUPON_COUPONID_GENERATOR")
@Column(name = "COUPON_ID")
private long couponId;
@Column(name = "TITLE")
private String title;
@Column(name = "STATUS_ID")
private Long statusId;
// Need help here how to set this up properly
@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name = "STATUS_ID", insertable = false, updatable = false)
private Status status;
}
感谢任何帮助。
【问题讨论】:
-
那么,多张优惠券可以共享相同的状态吗?如果是,则为多对一,否则为一对一。发布您用于创建和保存优惠券的代码,说明您希望它做什么以及它会做什么。
-
@JBNizet 添加了代码以及数据库中的预期内容和更新内容