JPA多对一关系 [英] JPA Many to One relationship

查看:83
本文介绍了JPA多对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JPA的初学者,需要一些帮助来获取JPA中的多对一关系.

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

我有以下实体.

存储所有用户信息的用户.用户扩展了Audiatable抽象类,该类用于保存最后修改日期,创建日期等类似的参数.

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

我正在尝试添加其他字段作为 lastUpdatedByUser ,该字段应从我试图为其添加多对一关系的 lastUpdatedBy 中获取. 但是这种关系以某种方式无法正常工作,我在这里做错了吗?

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

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

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;

}

推荐答案

好吧,您用@Transient标记了关联,这意味着该字段不是持久性的,应由JPA忽略.

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

您似乎还具有两个不同的字段来存储相同的信息:lastUpdatedBylastUpdateByUser.删除第一个,并将第二个映射为

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;

这表明该关联是与User实体的ManyToOne(因为它是字段的类型,因此无需指定targetEntity),并且该关联由可审核实体的名为"chuserid"的连接列实现.表,并引用用户实体的ID(referencedColumnName仅在使用复合ID时,或在通过ID列来引用实体时才有用)

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)

这篇关于JPA多对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆