【问题标题】:Child property in spring data jpa query is not working春季数据 jpa 查询中的子属性不起作用
【发布时间】:2017-12-17 08:45:30
【问题描述】:

我们正在使用 spring boot 1.5.3 提供的 spring data jpa。在存储库类中,我想从一个表中只获取几列,包括来自子表(这是一个单映射)的数据,所以我编写了一个带有查询的方法。 但是该查询方法不起作用并在日志中看到以下错误/警告

SQL Error: -104, SQLState: 42601
DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=.;ARRAY + - ROW NEXTVAL PREVVAL NEXT PREVIOUS ( <INTEGER>, DRIVER=4.19.26

这是我的父实体:

@Entity
@Table(name = "parent_table")    
public Class Parent {
   // no-param constructor

   Parent(int id, String name, Child childData) {
      // assign these accordingly
   }
   // id, name, and couple of other mappings

   @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval=true)
   private Set<Child> childData;
}

子实体:

@Entity
@Table(name = "child_table")
public class Child {
    // id and couple of other columns

    @ManyToOne (fetch = FetchType.LAZY)
    @JoinColumn(name = "p_id", nullable = false, insertable = false, updatable = false)
    private Parent parent;

}

存储库在这里:

@Transactional
public interface ParentRepository extends CrudRepository<Parent, Integer> {

    @Query("select new Parent(id, name, p.childData) from Parent p where p.id=?1")
    public Parent findOnlyChildDataById(final int id);

}

【问题讨论】:

    标签: hibernate spring-boot spring-data-jpa


    【解决方案1】:

    不要使用自定义方法通过'id'获取实体,使用本机方法findOne

    public interface ParentRepository extends CrudRepository<Parent, Integer> {
    }
    
    @Service    
    public ParentService {
    
        @Authoware
        prvate ParentRepository repo;
    
        public Parent getParentById(int id) {
            return repo.getOne(id);
        }
    }
    

    【讨论】:

    • 感谢您的回复。但是,在这里我不需要父级中的所有列。所以,我用 jpa 查询编写了自定义方法。
    • 如果您需要一个没有某些属性的实体,那么这不是一个实体,它是一个DTO,您需要另一个technic 来处理它。
    • 谢谢。但是,我已经在 repo 中使用了下面给出的类似方法,效果很好。 @Query("select new Parent(id, name, application, anothercolumn) from Parent p where p.application=?1") public List findAllByApplication(String application) 我只在包含子属性的地方遇到问题查询。
    猜你喜欢
    • 2022-01-12
    • 2021-07-31
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2015-02-27
    • 2017-12-09
    • 2017-12-13
    相关资源
    最近更新 更多