我是Spring编程的新手,在下面的例子中尝试了BID和BIDITEM类之间的一对多关系。我不确定是否保存了BIDITEM数据,因为当我尝试检索BID时,我只获得BID数据而不是BIDITEM数据。我们是否需要为BIDITEM类设置存储库。我可以看到在create方法中接收到完整的BID JSON字符串以及BIDITEM。 你能不能通过它,让我知道它有什么问题。
@Entity
@Table(name = "bid")
public class Bid {
@Id
private String title;
@Column
private long startDate;
@Column
private long endDate;
@OneToMany(mappedBy = "myBid", cascade = {CascadeType.ALL})
private List<BidItem> bidItems = new ArrayList<BidItem>();
//Constructor, getter and setter methods go here
}
@Entity
@Table(name="biditem")
public class BidItem
{
@Id
private String item;
@Column
private String desc;
@Column
private double minAmt;
@ManyToOne
@JoinColumn(name = "title")
private Bid myBid;
//Constructor, getter and setter methods go here
}
public interface BidRepository extends CrudRepository<Bid, String> {
//Tried even JpaRepository
}
public class BidService {
ObjectMapper mapper = new ObjectMapper();
@Autowired
private BidRepository bidRepo;
public Bid create(String bidJson) throws JsonParseException, JsonMappingException, IOException
{
Bid bid = mapper.readValue(bidJson, Bid.class);
// bidJson string has below string
// {"bidItems":[{"item":"item1","desc":"item1","minAmt":"999"}],
// "title":"bid1","startDate":"D1","endDate":"D5"}
Bid savedBid = bidRepo.save(bid);
return savedBid;
}
public Bid findByID(String title)
{
Bid bid = bidRepo.findOne(title);
return bid;
}
}