I have user table with column id, mname, firstname, lastname, age (5 column) using spring data jpa I need to get only id, firstname, age (only 3 column)
userentity is below user.java
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = -3009157732242241606L;
@Id
private long id;
@Column(name = "mname")
private String mName;
@Column(name = "firstname")
private String firstName;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String lastName;
@Column(name="age")
private int age;
//constructor with fileds
user2.java contains the fileds
private Long id;
private String firstname;
private int age;
//getter and setter
UserRepository.java
public interface UserRepository extends CrudRepository<User, Long> {
@Query(value="SELECT usr.id as id,usr.firstname as firstName, usr.age as age FROM user usr WHERE usr.id=?1", nativeQuery=true)
List<User2> getUserDetailsByUserId(Long id);
}
getting the below error in colsole:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.math.BigInteger] to type [com.user.entity.User2]
while inspect the code get the error:
Failed to convert from type [java.lang.Object[]] to type [com.user.entity.User2] for value '{403, firstnnnnnnn, 26}';
Is there any way to map the values to user2 (non-table entity)?
You should use projections :
public interface UserProjection {
Long getId();
String getFirstname();
Integer getAge();
}
public interface UserRepository extends CrudRepository<User, Long> {
List<UserProjection> findById(Long id);
}
@Value // It's Lombok annotation
public class UserDto {
Long id;
String firstname;
Integer age;
}
public interface UserRepository extends CrudRepository<User, Long> {
List<UserProjection> findById(Long id);
List<UserDto> getById(Long id);
}
No, In reality your query return 3 attributes id, firstName, age and not an Object User2
, you can solve your problem like :
First Solution
You can create a constructor in your User2 class which hold this three attributes :
public User2(Long id, String firstName, int age){..}
Then your query should look like this :
SELECT com.packagename.User2(usr.id, usr.firstname, usr.age) FROM user usr WHERE usr.id=?1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Second Solution
You have to change :
List<User2> getUserDetailsByUserId(Long id);
^^^^^
to this :
List<Object[]> getUserDetailsByUserId(Long id);
^^^^^^^^
Then you can loop over the result in your service and cast each Object like this :
List<Object[]> listObjects = userRepository.regetUserDetailsByUserId(id);
List<User2> listUsers = new ArrayList<>();
for(Object[] obj : listObjects){
listUsers.add((Long)obj[0], (String)obj[1], (Integer)obj[2]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.