Muthu
Muthu

Reputation: 1550

one to many relationship in Objectify4

I am working with GAE with java. i am just creating a sample application with Student and Course relationships. I am having many branches and many students. Each branch can have many students, i tried like

    ObjectifyService.register(Course.class);
    ObjectifyService.register(Student.class);
    Course course = new Course();
    course.setName("ss");
    course.setBranch("cs");
    ofy().save().entity(course).now();

    Student stu = new Student();
    stu.setName("student1");
    Key<Course> courseKey = new Key<Course>(Course.class, course.getId()); // getting error here
    stu.setCourse(courseKey);
    System.out.println("saving");
    ofy().save().entity(stu).now();

I am not sure how to define this relationship in objecitfy4. I followed the tutorial http://www.eteration.com/objectify-an-easy-way-to-use-google-datastore/

Thanks.

Upvotes: 0

Views: 687

Answers (3)

stickfigure
stickfigure

Reputation: 13556

Look at the Javadocs for Key. Instead of a public constructor, there is a more convenient creator method which requires less typing of <> generics:

Key<Course> courseKey = Key.create(Course.class, course.getId());

Upvotes: 2

Muthu
Muthu

Reputation: 1550

When we use Objectify , if we need any Key to be created for condition(KeyFactory.createKey("Course", course.getId()) , In course object, Id field should be specified with index. It will work fine.

Upvotes: 0

Peter Knego
Peter Knego

Reputation: 80340

There are two keys that you might use:

  1. first the GAE low-level com.google.appengine.api.datastore.Key and
  2. second, the objectify's com.googlecode.objectify.Key.

You can use both with Objectify (as under the hood they are ultimately converted to low-level API).

Neither has a public constructor so you can not use new with them.

With low-level keys you'd use KeyFactory.createKey("Course", course.getId()). With objectify key you'd use com.googlecode.objectify.Key.create(Course.class, course.getId())

Upvotes: 1

Related Questions