我可以在JPA中查询对象吗?

时间:2015-08-07 10:58:40

标签: java spring hibernate jpa orm

我正在使用JPA和Spring Data,

有一个具有字段UserDetail createdBy的类事件,我想查询由指定用户创建的事件。这是我的查询

@Query("SELECT e FROM  event WHERE e.created_by = :userdetail")
    Collection<Event> getEventsCreatedByUser(@Param("userdetail")UserDetail user);

当我在Dao类中使用此查询启动测试时,我收到错误org.hibernate.hql.internal.ast.QuerySyntaxException: event is not mapped [SELECT e FROM event WHERE e.created_by = :userdetail]

这是实体类,created_by在BaseEntityAudit中,我测试的User类也扩展了BaseEntityAudit并且它运行得很好,pgadmin也显示了createBy列存在于事件表中

@Entity
@Table(name = "Event")
@AttributeOverride(name = "id", column = @Column(name = "event_id",
        nullable = false, columnDefinition = "bigserial"))
public class Event extends BaseEntityAudit {
    @Embedded
    private Point point;    
    @OneToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "event_comments")
    private Collection<Comment> comments = new ArrayList<Comment>();
    @OneToMany
    @JoinTable(name = "\"users_tagged_at_event\"")
    private Collection<UserDetail> usersTagged = new ArrayList<UserDetail>();    
    public Event(UserDetail createdBy, Point point) {
        super();
        this.point = point;
        setCreatedBy(createdBy);
    }

还有BaseEntityAudit

public abstract class BaseEntityAudit extends BaseEntity {
    @Column(name = "created_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @Column(name = "created_by", length = 20)
    private UserDetail createdBy;
    @Column(name = "updated_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;
    @Column(name = "updated_by", length = 20)
    private UserDetail updatedBy;
//geters/setters ...
    /**
     * Sets createdAt before insert
     */
    @PrePersist
    public void setCreationDate() {
        this.createdAt = new Date();
   }
    /**
     * Sets updatedAt before update
     */
    @PreUpdate
    public void setChangeDate() {
        this.updatedAt = new Date();
    }
}

更新

Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: created_by of: home.map.events.entity.Event [SELECT e FROM  home.map.events.entity.Event e WHERE e.created_by = :userdetail]

2 个答案:

答案 0 :(得分:2)

你忘了在from子句中提到event e。我猜你有事件表和事件类(由 @ pL4Gu33 指出)。因此,您需要使用事件而不是事件

@Query("SELECT e FROM Event e WHERE e.createdBy = :userdetail")
                use---^     ^- added      ^---- updated

答案 1 :(得分:1)

你的课程是'活动'不是'活动',也看看Naman Gala的答案。