Java 对实体的getter的Generify调用
我有两个hibernate实体(带有@Entity注释的Java类),它们看起来像:Java 对实体的getter的Generify调用,java,generics,Java,Generics,我有两个hibernate实体(带有@Entity注释的Java类),它们看起来像: @Entity Employer { Long id; String name; } 及 我在数据库中每个都有几个条目,我正在使用类似流的方式将两个表条目转换为映射: list.stream().collect(Collectors.toMap(Student::getId, Functions.identity())); list.stream().collect(Collectors.
@Entity
Employer {
Long id;
String name;
}
及
我在数据库中每个都有几个条目,我正在使用类似流的方式将两个表条目转换为映射:
list.stream().collect(Collectors.toMap(Student::getId, Functions.identity()));
list.stream().collect(Collectors.toMap(Employer::getId, Functions.identity()));
我想泛化这些流,所以我只需要调用一个方法。但是::getId
部分不能使用像T这样的示例泛型,因为它可以是任何类型。是否有一个特定的hibernate类可供我使用?
或者,唯一的选择是创建我自己的接口,该接口将具有getId方法,并由两个实体类实现?您是在说类似于:
interface Persistable<T>{
T getId();
void setId();
}
Student implements Persistable<Long>{
private Long id;
...
@Overrides
public Long getId(){ ... }
@Overrides
public void setId(Long id){ ... }
}
然后让你的实体扩展这个基类
public class Foo extends BasePersistable<Long> {
public Foo(Long id){ super(id); }
...
@Column(...)
...
}
公共类Foo扩展了BasePersistable{
公共Foo(长id){super(id);}
...
@列(…)
...
}
这样,您只需要在一个地方实现
持久化API。您所说的是:
interface Persistable<T>{
T getId();
void setId();
}
Student implements Persistable<Long>{
private Long id;
...
@Overrides
public Long getId(){ ... }
@Overrides
public void setId(Long id){ ... }
}
然后让你的实体扩展这个基类
public class Foo extends BasePersistable<Long> {
public Foo(Long id){ super(id); }
...
@Column(...)
...
}
公共类Foo扩展了BasePersistable{
公共Foo(长id){super(id);}
...
@列(…)
...
}
这样,您只需要在一个地方实现持久化API。是的,似乎您需要创建自己的接口啊,似乎您需要创建自己的接口