我有两个实体
:
-Trader.java
Stockmarket.java
我正在使用@ManyToMany 注释,包含股票市场列表的交易者保存对我有用,但包含交易者列表的股票市场保存不起作用。
交易者.java
import lombok.*;
import javax.persistence.*;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "trader")
public class Trader {
@Id
@GeneratedValue
@Column(name = "trader_id")
private Long id;
@Column(name = "trader_name")
private String traderName;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "TRADER_STOCKMARKET",
joinColumns = { @JoinColumn(name = "trader_id") },
inverseJoinColumns = { @JoinColumn(name = "stockmarket_id") })
private List<Stockmarket> stockmarket;
}
股票市场.java
import lombok.*;
import javax.persistence.*;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "stockmarket")
public class Stockmarket{
@Id
@GeneratedValue
@Column(name = "stockmarket_id")
private Long id;
@Column(name = "stockmarket_name")
private String stockmarketName;
@ManyToMany(mappedBy="stockmarket")
private List<Trader> traders;
}
控制器:
(MySQL 已经有 2 个交易者和 2 个交易所。)
Stockmarket stockmarket3 = new Stockmarket();
stockmarket3.setStockmarketName("Marvel");
List<Trader> allTraders = manyToManyBiService.findAllTraders();
System.out.println("\n\n\n finally " + allTraders.toString() + "\n\n\n ");
stockmarket3.setTraders(allTraders);
manyToManyBiService.saveStockmarket(stockmarket3);
额外的东西,如果它们有助于解决问题
多对多BiService.java:
@Service
public class ManyToManyBiService {
@Autowired
StockmarketRepository stockmarketRepository;
@Autowired
TraderRepository traderRepository;
public void saveTrader(Trader trader){
traderRepository.save(trader);
}
public void saveStockmarket(Stockmarket stockmarket){
stockmarketRepository.save(stockmarket);
}
public Stockmarket findByNameStockmarket(String name){
return stockmarketRepository.findByStockmarketName(name);
}
public List<Stockmarket> findAllStockmarket(){
return stockmarketRepository.findAll();
}
public List<Trader> findAllTraders(){
return traderRepository.findAll();
}
}
StockmarketRepository 和 TraderRepository 是扩展 CrudRepository 的接口。
找到答案。
在 Hibernate 中完成注解解析
错误是我将一个对象放入另一个对象中,但忘记将嵌套对象引用到嵌套它的对象。
粗略地说,我有这样的 A->B->null ,但我需要 A->B->A 来获得:
A->B->A->B->A->B->A->B - >A->B->A...循环。
因此,我的实体应如下所示:
交易者.java
Stockmarket.java:
更新1:
如果有问题
Set<>
,请使用List<> .... = new ArrayList<>();
,