使用多对一Map在Hibernate JPA查询中获取数据

dba5bblo  于 2022-11-30  发布在  其他
关注(0)|答案(1)|浏览(176)

嗨,我有几个表,列在下面:

public class GroupEntity extends BaseEntity {

    @Id
    @SequenceGenerator(name = "beta_group_seq", sequenceName = "group_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "group_seq")
    @Column(name = "id")
    private Long id;

    @Column(name = "name", length = 1400)
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private UserEntity userEntity;

    @Column(name = "status")
    private String status;
}

UserEntityManyToOne关系:

public class UserEntity extends BaseEntity {

    @Column(name = "user_code", nullable = false, unique = true)
    private String userCode;
}

实体扩展了基本实体:

@Getter
@MappedSuperclass
public abstract class BaseEntity {

    @Column(name = "CREATED_BY", length = 8, updatable = false)
    private String createdBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATION_DATE", updatable = false)
    private Date creationDate;

    @Column(name = "LAST_UPDATED_BY", length = 8, updatable = false)
    private String lastUpdatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "LAST_UPDATED_DATE", updatable = false)
    private Date lastUpdatedDate;
}

为了获取UserEntity中的userCode,我编写了下面的JPA条件查询:

public List<GroupEntity> getData(final String userCode,
                                                                       final String currentGroupName, final String newGroupName) {

        final EntityManager entityManager = entityManagerProvider.get();
        final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        final CriteriaQuery<GroupEntity> cq = cb.createQuery(GroupEntity.class);
        final Root<GroupEntity> root = cq.from(GroupEntity.class);
        cq.select(root).where(cb.or(cb.equal(root.get("userCode"), userCode), cb.equal(root.get("name"),
                currentGroupName), cb.equal(root.get("name"), newGroupName)));
        return entityManager.createQuery(cq).getResultList();
    }

但由于上面的查询失败而出现了一些internalFailure:

Unable to locate Attribute  with the the given name [userCode] on this ManagedType [com.<servicename>.entity.BaseEntity]

我不确定是因为我在上面提出了错误的查询,还是因为其他原因?
谢谢!

7vux5j2d

7vux5j2d1#

必须联接UserEntity才能有一个引用来构建where子句:

Root<GroupEntity> root = cq.from(GroupEntity.class);
Join<GroupEntity,UserEntity> user = root.join("userEntity");
cq.select(root).where(cb.or(
              cb.equal(user.get("userCode"), userCode), 
              cb.equal(root.get("name"), currentGroupName), 
              cb.equal(root.get("name"), newGroupName)));

顺便说一句,您应该考虑为类型安全查询生成元模型。
https://www.baeldung.com/hibernate-criteria-queries-metamodel

相关问题