thinker thinker - 1 year ago 75
Java Question

Hibernate: detect linked field and save an object

How can I save object into database and simultaneously detect linked

in the

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

enter image description here

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

private static final long serialVersionUID = 1L;

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

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

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


Answer Source

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) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download