Relacionado à essa pergunta que fiz mais cedo sobre Hibernate
Estou construindo uma API Restful, e fazendo um join com 2 tabelas. Porém gostaria de trazer somente alguns atributos da minha tabela do join.
Hoje minha query resulta no seguinte:
[{"id":1,"name":"Java","schedule":"Monday","teacher":{"id":1,"name":"John","phoneNumber":"35483"}}]
Mas eu gostaria que viesse da seguinte maneira:
[{"id":1,"name":"Java","schedule":"Monday","teacher":{"name":"John"}}]
Ou seja, somente o "name" de "teacher"
Query:
public interface CoursesRepository extends CrudRepository<Course, Integer>{
@Query("select c, t.name as teste from Course c join c.teacher t ")
public List<Course> findAllCoursesAndTeachers();
}
Classe Teacher
@Entity
public class Teacher {
@Id
@Column(name="teacher_id")
private int id;
@Column(name="teacher_name")
@Access(AccessType.PROPERTY)
private String name;
@Column(name="teacher_phone")
private String phoneNumber;
@OneToMany(mappedBy="teacher")
private List<Course> courses;
public Teacher() {
courses = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/*
@OneToMany(mappedBy="teacher")
public List<Course> getCourses() {
return courses;
}
*/
}
Classe Course
@Entity
public class Course {
@Id
@Column(name="course_id")
private int id;
@Column(name="course_name")
private String name;
@Column(name="course_schedule")
private String schedule;
@ManyToOne
@JoinColumn(name = "teacher_id")
private Teacher teacher;
public Course() {
}
/*
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name="teacher_id")
public Teacher getTeacher() {
return teacher;
}
*/
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSchedule() {
return schedule;
}
public void setSchedule(String schedule) {
this.schedule = schedule;
}
}
Eu tentei usar a @Access(AccessType.PROPERTY)
mas não surtiu efeito