thinker thinker - 19 days ago 8
Java Question

Hibernate: detect linked field and save an object

How can I save object into database and simultaneously detect linked

topic_id
in the
grammar.topics
by
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

Answer

If in your method, you have not the id for Topic entity and you need it for persisting your Beginner entity, you must retrieve that information from the database.
If in Topic table , topic_name is UNIQUE. Easy : do a query where you retrieve the single Topic entity or the topicId with this topicName value.
Ideally, you could avoid the query by keeping the topicId value when you retrieve the topic name information.

You could so replace topicName information in your processing by topicId information to be able to set the relation when you want to persist your Beginner instance. :

public void updateResult(String topicId, int userId) 

instead of

public void updateResult(String topic_name, int userId)