Question

I have 2 questions: suppose we have one entity named class and another called student. each class has onetomany students.

public class Clas implements Serializable {
@Id
  @GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;
@OneToMany(cascade=CascadeType.ALL)
Collection<Student> students;
public clas(){
super();
}
 ..... getters and setters
}

q1: i get the exception there are no fields to be mapped because of sequence strategy, when adding any other column like String name, it works, but i don't need that field what can i do ?

q2. the ids is autogenerated, and i want to query all students in class c1, but i don't has the id of this class, how to get such query without using id? or how to get database entity id to query on it ?

iam working with mysql server glassfish v2.1 toplink jpa 1.0

Thanks

Was it helpful?

Solution

Regarding your second question: when you create a Clas instance, persist it, and flush, the ID is autogenerated, and assigned to the ID field of the Clas instance. Since flushing happens automatically at the end of the transaction, calling this transactional session bean method will return a Clas instance with an ID:

public Clas createClas() {
    Clas c = new Clas();
    // call setters to populate the clas
    entityManager.persist(c);
    return c;
}

Caller code:

Clas c = mySessionBean.createClas();
int clasId = c.getId(); // clasId is the generated ID of the created Clas.

Once you have the clas ID, and want to get all its student, just do the following:

public Collection<Student> getStudentOfClas(int clasId) {
    Clas clas = entityManager.find(Clas.class, clasId);
    return clas.getStudents();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top