简体   繁体   中英

hibernate parent child relationship

Let's say I have entity A and entity B. Entity A have @OneTomany relationship with B.

I want to persist row in A only if it has one or more child object's associated with it else throw an exception.

How can i achieve the above requirement in hibernate

You neglected to mention what version of Hibernate you are using. In any case, this falls within the purview of validation. Luckily, in both Hibernate 3 and 4 you can utilize Hibernate Validator to do the job:

public class EntityB implements Serializable {
}

public class EntityA implements Serializable {
    @NotNull
    @Size(min = 1)
    private Set<EntityB> relatedEntities;
}

You may need to pull in the Hibernate Validator jars into your project in order to be able to do this.

Entity class:Register.class

public class Register{

private Long regId;

@OneToMany(mappedBy = "reg")

private Set addrSet;

public Set getAddrSet() {

    return addrSet;

}

public void setAddrSet(Set<Address> addrSet) {
    this.addrSet = addrSet;
}

}

Entity Class:Address.java

public class Address{

object values;

@ManyToOne

private Register reg;

public Register getReg() {

    return reg;

}

public void setReg(Register reg) {
    this.reg = reg;
}

}

public void class searchObject(){

public List lst; public register searchRegisterRow(Long regId){

  Session session = null;

 SessionFactory sessionFactory = null;

 register result = null; 

    try{    

       sessionFactory = new Configuration().configure().buildSessionFactory();      
        session =sessionFactory.openSession();
       String SQL_QUERY ="from Register r where r.redId = "+regId;
       Register reg = session.createQuery(SQL_QUERY);  

             for(Iterator it=lst.iterator();it.hasNext();){


                             reg=(Register)it.next();

            if(reg.getAddrSet().size() > 0){

                              result = reg;

                            }
                            else{

                                throw new Exception();

                            }

        }

        return result;
    }
    }catch(Exception e){

        System.out.println(e.getMessage());

    }finally{
        // Actual contact insertion will happen at this step
        session.flush();

        session.close();

        }

} }

I think you should try above code. this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM