I want to select object with specific field, but stored object in existing model.
@Entity
public class Car {
@Id
private Integer id;
private String name;
private String type;
private Integer year;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
}
My repository.
public interface CarRepository extends JpaRepository<Car, Integer>{
@Query("SELECT c.name, c.year FROM Car c WHERE c.year = :year")
List<Car> findAll(@Param("year") Integer year);
}
But this will give me error:
Failed to convert from type java.lang.Object[] to type com.sample.model.Car for value '{Chevrolet, 2009}'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.Integer to type com.sample.model.Car
You can use dynamic instantiation. Something like this
select new Car(c.name, c.year) FROM Car c WHERE c.year = :year
or you can use a result transformer (without @Query
).
And you can see this for some thoughts about partial objects loading.
UPDATE
And It needs to have Car(String name, Integer year)
constructor in Car
and default constructor too.