如何处理嵌入式复合键?

How to handle embedded composite key?

我有一个名为 table 的监视列表,它只包含两个字段,符号和名称。这种组合是独一无二的。我遇到休眠错误:

"Repeated column in mapping for entity"

错误,我不知道为什么。

我创建了一个 WatchlistId class,如下所示:

@Embeddable
public class WatchlistId implements Serializable {
    @Column(name="symbol")
    private String symbol;
    
    @Column(name="name")
    private String name;
    
    WatchlistId() {     
    }

    WatchlistId(String symbol, String name) {
        this.symbol = symbol;
        this.name = name;
    }
//getters and setters
@Override
    public boolean equals(Object o) {
        if (this == o) return true;
 
        if (o == null || getClass() != o.getClass()) return false;
 
        WatchlistId that = (WatchlistId) o;
        return Objects.equals(symbol, that.symbol) && Objects.equals(name, that.name);
    }
 
    @Override
    public int hashCode() {
        return Objects.hash(symbol, name);
    }   

监视列表 class 如下所示:

@Entity
@Table(name = "watchlist")
public class Watchlist {
    @EmbeddedId
    public WatchlistId watchlistId;
    
    private String symbol;
    private String name;
 
    public Watchlist() {      
    }
    
    public Watchlist(WatchlistId watchlistId, String symbol, String name) {
        this.watchlistId = watchlistId;
        this.symbol = symbol;
        this.name = name;
    }
    
    public WatchlistId getWatchlistId() {
        return watchlistId;
    }
    public void setWatchlistId(WatchlistId watchlistId) {
        this.watchlistId = watchlistId;
    }
}

存储库如下所示:

@Repository
public interface WatchlistRepository extends JpaRepository<Watchlist, WatchlistId>{
    @Query(value="select * from watchlist w where (name = :w.watchlistId.name)", nativeQuery = true)
    List<Watchlist> getWatchlist(@Param("name") String name);

    @Query(value="insert into watchlist w (symbol,name) values (:watchlist.watchlistId.symbol,:watchlist.watchlistId.name)", nativeQuery = true)
    String addSymbolToWatchlist(@Param("watchlist") Watchlist watchlist);
}

使用 @Embeddable 时,可嵌入 class 中的字段会自动添加到 table,因此您会得到重复项。

因此,您需要删除 symbolname 字段并从 WatchlistId 成员中使用它们:

@Entity
@Table(name = "watchlist")
public class Watchlist {
    @EmbeddedId
    public WatchlistId watchlistId;
    
    public String getSymbol(){
        return watchlistId.getSymbol();
    }
    
    public String getName(){
        return watchlistId.getName();
    }
}