如何将对象保存到数据库中,同时通过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);
}
@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 :(得分:0)
如果在您的方法中,您没有id
Topic
实体,并且您需要它来保留Beginner
实体,则必须从数据库中检索该信息。
如果在Topic
表中,topic_name为UNIQUE
。简单:执行查询,以检索具有此entity
值的单个主题topicId
或topicName
。实际上,您可以通过保留{{1}来避免查询检索主题名称信息时的值。
您可以通过topicId
信息替换处理中的topicName
信息,以便在您希望保留topicId
实例时设置关系。 :
Beginner
而不是
public void updateResult(String topicId, int userId)