@OneToMany关系休眠

时间:2018-09-06 08:49:51

标签: java spring hibernate

大家好,我有实体:

孩子: @EDIT感谢@MithatKonuk

 wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
 rpm -ivh epel-release-latest-7.noarch.rpm

 sudo yum install erlang erlang-nox

和家人:@EDIT感谢@MithatKonuk

@Entity
@Table(name="child")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="ID")
    private int id;

    @Column(name="FirstName")
    private String firstName;

    @Column(name="SecondName")
    private String secondName;

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

    @Column(name="Sex")
    private String sex;

  @JsonBackReference
  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name="familyid",referencedColumnName = "id")
  private Family family;

我想获得成为家庭成员的孩子的清单。我尝试进行查询: @EDIT感谢@MithatKonuk

@Entity
@Table(name="family")
public class Family {

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



    @OneToOne(cascade = CascadeType.ALL)
    private Father father;

    @JsonManagedReference
    @OneToMany(mappedBy = "family",fetch=FetchType.EAGER,cascade = CascadeType.ALL)
    private List<Child> childList;

当我尝试运行它时,我总是会出错:

@Transactional
public List<Child> findAllChild(int id) {
    // TODO Auto-generated method stub
    HibernateUtil.initManager();
    HibernateUtil.getEntityManager().clear();
    Query query = HibernateUtil.getEntityManager().createQuery("SELECT child FROM Child child FETCH JOIN child.family u WHERE u.id = :userId ");
    query.setParameter("userId",id);
    List<Child> result = query.getResultList();
    HibernateUtil.shutdown();
    return result;
}

我需要你的帮助。

@Edit好的,所以我将此代码更新为完整实体。您还需要一些吗? 我很抱歉,也许这很容易,但是我学习了休眠模式,而且我不知道该cos出了什么问题。感谢您的回答。

2 个答案:

答案 0 :(得分:0)

首先,您需要更改查询

@Transactional
public List<Child> findAllChild(int id) {
    // TODO Auto-generated method stub
    HibernateUtil.initManager();
    HibernateUtil.getEntityManager().clear();
    Query query = HibernateUtil.getEntityManager().createQuery("SELECT child FROM Child child JOIN FETCH child.family  WHERE child.family.id = :userId ");
    query.setParameter("userId",id);
    List<Child> result = query.getResultList();
    HibernateUtil.shutdown();
    return result;
}

第二个是将@Entity和@Table(“ child”)和@Table(“ family”)添加到每个类中,如下所示

@Entity
@Table("child table name")
public class Child{}

@Entity
@Table("family table name")
public class Family{}

答案 1 :(得分:0)

JOIN应该在FETCH之前,请尝试以下查询:

decodeURIComponent(encodeURIComponent(mystring))