
[英]Spring boot: Custom mapping between DTO and Entity using ModelMapper
[英]Mapping a database view entity with a simple entity and pass to DTO using Spring Data
我只是在学习Spring Data。 我想用一个简单的Entity映射数据库视图Entity并传递给DTO,DTO将同时包含两个实体的列。 我知道我可以使用特殊的数据库视图,但是我需要精确地映射Spring Data的实体。 我有一个数据库视图实体“ MentorStudents”:
@Entity
@Table(name = "mentor_students")
@Immutable
public class MentorStudents implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "mentor_id", updatable = false, nullable = false)
private Long mentorId;
//This entity I need to map
private Mentor mentor;
@Column(name = "active_students")
private Integer activeStudents;
public MentorStudents() {
}
//getters, setters, equals, hashCode
}
上述实体的数据库视图sql是:
SELECT id AS mentor_id, active_students
FROM mentor
LEFT JOIN ( SELECT mentor_id, count(mentor_id) AS active_students
FROM contract
WHERE close_type IS NULL
GROUP BY mentor_id) active ON mentor.id = active.mentor_id
ORDER BY mentor.id;
我有一个简单的实体“ Mentor”:
@Entity
@Table(name = "mentor")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Mentor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "first_name", nullable = false)
private String firstName;
@NotNull
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "patronymic")
private String patronymic;
@Column(name = "phone")
private String phone;
@NotNull
@Column(name = "email", nullable = false)
private String email;
@Column(name = "skype")
private String skype;
@Column(name = "country")
private String country;
@Column(name = "city")
private String city;
@Column(name = "max_students")
private Long maxStudents;
//getters, setters, equals, hashCode
我必须获得一个DTO,其中包含所有Mentor字段和一个不含“ mentorId”字段的“ activeStudents” MentorStudents字段。 怎么做
使用弹簧数据投影:
public interface YourDto {
// all Mentor get fields
String getFirstName();
...
// activeStudents get field
Integer getActiveStudents();
}
public interface YourRepository extends JpaRepository<YourEntity, Integer> {
@Query(value = "select ...(all fields match YourDto) from Mentor m, MentorStudents s where m.id = s.mentorId and m.id = ?1")
Optional<YourDto> findMyDto(Integer mentorId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.