J
J
Jsman2019-04-09 20:05:25
Java
Jsman, 2019-04-09 20:05:25

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;

}

The question is how to populate the userName field in the Task class based on the userId ?
could have been done like this:
@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();
}

but I can't make a replacement. a lot of things are tied to an int field (in the Task class).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Conacry, 2019-04-10
@Conacry

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.

O
Orkhan, 2019-04-17
Hasanly @azerphoenix

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;

A simple example is here - https://devcolibri.com/%D0%BA%D0%B0%D0%BA-%D1%81%D...
Add OneToMany to User ( List<Task> tasks), Add ManyToOne to Task ( User user) and that's it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question