简体   繁体   中英

DAO interface: Implementation for 2 entities (Java, Hibernate)

I have 2 entities Student and Intsructor. I want to realise Dao interface with Dao Implementations for two entities. I set one class User as a parent of Student an Instructor:

@MappedSuperclass 
public abstract class User {

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

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

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

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

    getters and setters ...

}

and children. Student

@Entity 
@Table(name = "student", schema="els")
public class Student extends User {
    @Column(name="achiev")
    private String achievment;      


   public Student() {
   }

   getter and setter for achievment

}

and the Instructor

@Entity
@Table(name = "instructor", schema="els")
public class Instructor extends User {

    @Column(name = "reputation")
    private int reputation;

    public Instructor() {
    }

    public int getReputation() {
        return reputation;
    }

    public void setReputation(int reputation) {
        this.reputation = reputation;
    }
}

Dao interface:

public interface DAO {
    List<User> getAllUsers();

    ...

}

with DAO implementations for two entities.

But there is a problem. I can't save all properties of each entity because in User class I have just some of them. The Student and Instructor besides inherited properties they have their own.

How can I realize DAO and entities. What is a good practic in this situation?

Thanks

You can try using generics.

public interface GenericDAO<T> {
  List<T> getAll();
}

And when need, you can extends and define the specific functions.

public interface UserDAO extends GenericDAO<User> {
    User getAllWithAvatar();
}

Hope this helps!

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