我有作为父类:User.java
和 2 个类:FacebookUser.java
它们TwitterUser.java
是返回的实体,取决于使用数据库中的类型列DiscriminatorColumn
,我想编写正确的映射器来映射可能是 FacebookUser 或 TwitterUser 实例的用户。我有以下似乎无法按预期工作的映射器,仅映射User
父级而不是子级:
@Mapper
public interface UserMapper {
public static UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);
User map(UserDTO userDTO);
@InheritInverseConfiguration
UserDTO map(User user);
List<UserDTO> map(List<User> users);
FacebookUser map(FacebookUserDTO userDTO);
@InheritInverseConfiguration
FacebookUserDTO map(FacebookUser user);
TwitterUser map(TwitterUserDTO userDTO);
@InheritInverseConfiguration
TwitterUserDTO map(TwitterUser user);
}
然后我使用:
UserDTO userDto = UserMapper.INSTANCE.map(user);
要映射的类:
@Entity
@Table(name = "users")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING, length = 10)
@DiscriminatorValue(value = "Local")
public class User {
@Column
private String firstName;
@Column
private String lastName;
///... setters and getters
}
@Entity
@DiscriminatorValue(value = "Facebook")
public class FacebookUser extends User {
@Column
private String userId;
///... setters and getters
}
@Entity
@DiscriminatorValue(value = "Twitter")
public class TwitterUser extends User {
@Column
private String screenName;
///... setters and getters
}
DTO:
public class UserDTO {
private String firstName;
private String lastName;
///... setters and getters
}
public class FacebookUserDTO extends UserDTO {
private String userId;
///... setters and getters
}
public class TwitterUserDTO extends UserDTO {
private String screenName;
///... setters and getters
}
此外,如果我有与 Facebook 用户和 Twitter 用户或基本用户混合的用户列表:
假设我有以下用户:
User user = new User ("firstName","lastName");
User fbUser = new FacebookUser ("firstName","lastName","userId");
User twUser = new TwitterUser ("firstName","lastName","screenName");
List<User> users = new ArrayList<>();
users.add(user);
users.add(fbUser);
users.add(twUser);
//Then:
List<UserDTO> dtos = UserMapper.INSTANCE.map(users);
我只得到firstName
andlastName
但没有screenName
or userId
。
有什么解决办法吗?