Spring Data Query to DTO

We will show here how you can map a DTO to a query using constructor.

First create your entity class. Here we will have a User class.

@Entity
@Table(name = "user")
public class User implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", nullable = false, updatable = false, unique = true)
	private Long id;
	
	@Column(name = "uid", unique = true, nullable=false, updatable=false)
	private String uid;

	@Column(name = "name")
	private String name;

	@Column(name = "email")
	private String email;

	@Column(name = "age")
	private int age;
	
	@JsonIgnoreProperties(value= {"user"})
	@OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
	@JoinColumn(name="address_id")
	private Address address;

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
     // setters and getters
}

Second create your DTO class. In this case we will have a UserDto.

public class UserDto {
	
	private String uid;

	private String name;

	private String email;

	private int age;
	
	private Address address;
	
	public UserDto() {
		this(null,null,null,0);
	}
	
	public UserDto(String uid, String name, String email, int age) {
		this(uid,name,email,age,null);
	}

	public UserDto(String uid, String name, String email, int age, Address address) {
		super();
		this.uid = uid;
		this.name = name;
		this.email = email;
		this.age = age;
		this.address = address;
	}
        // getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {
	
	@Query("select new com.lovemesomecoding.dto.UserDto(user.uid,user.name,user.email,user.age) from User user where user.id = :id")
    UserDto getUserProfile(@Param("id") Long id);
	
	@Query("select new com.lovemesomecoding.dto.UserDto(user.uid,user.name,user.email,user.age,user.address) from User user where user.id = :id")
    UserDto getUserProfileWithRoles(@Param("id") Long id);
}

As you can see that all fields and values must be loaded into the UserDto through the constructors like this one.

com.lovemesomecoding.dto.UserDto(user.uid,user.name,user.email,user.age,user.address)




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *