[英]DAO interface: Implementation for 2 entities (Java, Hibernate)
I have 2 entities Student and Intsructor.我有 2 个实体学生和讲师。 I want to realise Dao interface with Dao Implementations for two entities.
我想用 Dao 实现为两个实体实现 Dao 接口。 I set one class User as a parent of Student an Instructor:
我将一个类 User 设置为 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.两个实体的 DAO 实现。
But there is a problem.但有一个问题。 I can't save all properties of each entity because in User class I have just some of them.
我无法保存每个实体的所有属性,因为在 User 类中我只有其中一些。 The Student and Instructor besides inherited properties they have their own.
Student 和 Instructor 除了继承属性外,它们还有自己的属性。
How can I realize DAO and entities.我怎样才能实现 DAO 和实体。 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!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.