RRR_J
RRR_J

Reputation: 347

JPA Many to One relationship

I am bit beginner on JPA and need some help on fetching the Many to One relationship in JPA.

I have below entities.

User which stores all user information . User extends Audiatable abstract class which is for holding auidt paramters like last modified date, creation date etc.

I am trying to add another fields as lastUpdatedByUser which should get fetched from lastUpdatedBy for which I amtrying to add Many-One relationship. But the relation is not working somehow, am I doing something wrong here?

AuditableEntity.java

public abstract class AuditableEntity<T extends Entity<T, ID>, ID> implements Auditable {

private static final long serialVersionUID = 1L;

@Column(name = "cruserid")
private Long createdBy;


@Column(name = "crdate")
@Type(type = JpaConstants.TYPE_LOCAL_DATE_TIME)
private LocalDateTime createdOn;

@Column(name = "chuserid")
private Long lastUpdatedBy;

@Column(name = "chdate")
@Type(type = JpaConstants.TYPE_LOCAL_DATE_TIME)
private LocalDateTime lastUpdatedOn;

@Transient
@ManyToOne(fetch = FetchType.LAZY, targetEntity = User.class)
@JoinColumn(name = "usrId", referencedColumnName = "chuserid")
private User lastUpdatedByUser;

User.java

public class User extends AuditableEntity<User, Long> {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "usrId")
private Long id;

@Column(name = "usrName")
private String name;

@Column(name = "loginame")
private String loginName;

}

Upvotes: 1

Views: 4688

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

Well, you marked the association with @Transient, which means that the field is not persistent and should be ignored by JPA.

And you also seem to have two different fields to store the same information: lastUpdatedBy and lastUpdateByUser. Remove the first one, and map the second one as

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chuserid")
private User lastUpdatedByUser;

This tells that the association is a ManyToOne to the User entity (no need to specify the targetEntity since it's the type of the field), and that this association is materialized by the join column named "chuserid", in the auditable entity's table, and referencing the ID of the User entity (referencedColumnName is only useful when you use composite IDs, or when you reference an entity by a column which is the the ID)

Upvotes: 3

Related Questions