Hibernate:检测链接字段并保存对象

时间:2016-11-20 10:22:57

标签: java hibernate

如何将对象保存到数据库中,同时通过topic_id检测grammar.topics中的关联topic_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

1 个答案:

答案 0 :(得分:0)

如果在您的方法中,您没有id Topic实体,并且您需要它来保留Beginner实体,则必须从数据库中检索该信息。
如果在Topic表中,topic_name为UNIQUE。简单:执行查询,以检索具有此entity值的单个主题topicIdtopicName。实际上,您可以通过保留{{1}来避免查询检索主题名称信息时的值。

您可以通过topicId信息替换处理中的topicName信息,以便在您希望保留topicId实例时设置关系。 :

Beginner

而不是

public void updateResult(String topicId, int userId)