Answer the question
In order to leave comments, you need to log in
How to populate a class field (class = table entities)?
Hello! There are two tables task and user.
There are classes that implement entities.
@Entity
@Table(name = Task.TABLE)
@EntityListeners(AtomicObjectListener.class)
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter
@Setter
private Integer id;
@Column(name = "title")
@Getter
@Setter
private String title;
@Column(name = "user_id")
@Getter
@Setter
private Integer userId;
@Column(name = "user_name")
@Getter
@Setter
private String userName;
}
@Entity
@Table(name = User.TABLE)
@EntityListeners(AtomicObjectListener.class)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter
@Setter
private Integer id;
@Column(name = "user_name")
@Getter
@Setter
private String userName;
}
@Entity
@Table(name = Task.TABLE)
@EntityListeners(AtomicObjectListener.class)
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Getter
@Setter
private Integer id;
@Column(name = "title")
@Getter
@Setter
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
@Setter
@Getter
private User user;
@Column(name = "user_name")
@Getter
@Setter
private String userName = user.getName();
}
Answer the question
In order to leave comments, you need to log in
Hello.
Why do you need a separate field userName
? Use table relationships (OneToMany, ManyToOne). This will give you access to the entity User
, and then to all its fields.
Hello!
Let's assume that 1 user (User) can have several tasks (Task). It turns out that the relationship between them is @OneToMany @ManyToOne
This code in Task is superfluous
@Column(name = "user_name")
@Getter
@Setter
private String userName;
List<Task> tasks
), Add ManyToOne to Task ( User user
) and that's it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question