Home Ask Login Register

Developers Planet

Your answer is one click away!

TilmannZ February 2016

Queries return duplicates in JDO/Datanucleus/H2

I'm adding 2 object to a database, a Person and a Student (subclass of Person). When I query on Person, it returns each instance e twice. When I query on Student, it return both instances, even though Person is not a sub-class of Student. The code is based on the jdo-test-template from datanucleus. I'm using Datanucleus 5.0.0m1.


Person p = new Person(0, "Pete");
Student s = new Student(1, "Sarah");

Query<Person> qP = pm.newQuery(Person.class);
Collection<Person>cP = (Collection<Person>) qP.execute();
for (Person p2: cP) {
    System.out.println("Person: " + p2.getName() + " " + p2.getId() + " " + System.identityHashCode(p2));

Query<Student> qS = pm.newQuery(Student.class);
Collection<Student>c = (Collection<Student>) qS.execute();
for (Student s2: c) {
    System.out.println("Student: " + s2.getName() + " " + s2.getId() + " " + System.identityHashCode(s2));

The Person class is unchanged from the example template:

public class Person {
    Long id;
    String name;

    public Person(long id, String name) {
        this.id = id;
        this.name = name;

    public String getName() {
        return name;

    public Long getId() {
        return id;

The Student class:

public class Student extends Person {

    public Student(long id, String name) {
        super(id, name);

I also added Student to the persistence.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"


Neil Stockton February 2016

You haven't specified the inheritance strategy and how you want your persistence mechanism to distinguish between classes sharing a table. Use @Inheritance and @Discriminator as per these docs. While it will default the inheritance strategy to be NEW_TABLE for the base class and SUPERCLASS_TABLE for the sub class, it will NOT default any discriminator because maybe you didn't want to have one and never have a need for separating what is stored in that table

Post Status

Asked in February 2016
Viewed 2,490 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life