2016-11-20 51 views
0

如何將對象保存到數據庫中並同時檢測grammar.topics中的鏈接topic_idtopic_name休眠:檢測鏈接字段並保存對象

public void updateResult(String topic_name, int userId) { 
    Session session = sessionFactory.getCurrentSession(); 
    Beginner bgn = new Beginner(); 
    bgn.setUserId(userId); 
    bgn.setScore(100); 
    // how to detect `topic_id` here by `topic_name` from the `grammar.topics` 
    bgn.setTopic_id(...); 
    session.save(bgn); 
} 

enter image description here

@Entity 
@Table(name = "beginner", uniqueConstraints = 
    {@UniqueConstraint(columnNames = {"user_id", "topic_id"})}) 
public class Beginner implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @Column(name = "user_id", nullable = false) 
    private int user_id; 

    @Id 
    @Column(name = "topic_id", nullable = false) 
    private int topic_id; 

    @Column(name = "score", nullable = false) 
    private int score; 

    //getters&setters 

回答

0

如果你的方法,你有沒有爲id實體Topic,你需要它堅持你的Beginner的實體,您必須從數據庫中檢索信息。
如果在Topic表中,topic_name是UNIQUE。簡單:通過此topicName值檢索單個主題entitytopicId的查詢。
理想情況下,您可以通過在檢索主題名稱信息時保留topicId值來避免查詢。

您可以在處理中用topicId替換topicName信息,以便在您想要保留Beginner實例時能夠設置關係。 :

public void updateResult(String topicId, int userId) 

,而不是

public void updateResult(String topic_name, int userId)