How to create a JPA entity which has a field(s) from another entity?

Viewed 862

I have the following entity in SpringBoot and I would like to create a new entity which has the userID of the registered user and the name of the registered/logged in user as instance fields/table columns.

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="User")
public class WebUser {

    @Id
    @GeneratedValue
    private Long userID;

    @NonNull
    private String name;

    @NonNull
    private String email;

    @NonNull
    private String password;
}

How would I go about doing this using a form in SpringBoot and JPA entity? I am struggling, I tried to create a form with hidden input fields using @OneToMany annotation but the userID and name were null.

Thanks for any help

1 Answers

Frist of all you Should define table column names using @Column(name = "COLUMN_NAME") and assume your new entity name LogUser.

LogUser

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="LogUser")
public class LogUser{

    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID", nullable = false)
    private WebUser webUser;

    @Column(name = "NAME", nullable = false)
    private String name;

}

WebUser

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="User")
public class WebUser {

    @Id
    @GeneratedValue
    @Column(name = "USER_ID")
    private Long userID;

    @Column(name = "NAME", nullable = false)
    private String name;

    @Column(name = "EMAIL", nullable = false)
    private String email;

    @Column(name = "PASSWORD", nullable = false)
    private String password;

    @OneToMany(mappedBy = "webUser")
    private Set<LogUser> logUsers;



}
Related