简体   繁体   中英

How to show alias column in spring data jpa using native query?

I want to show it in my response distance field, but I am not able to do it please help.

Here is my repo class in alias name (distance) I need to attach this distance column with my list of user results.

Repository

String countDistanceQuery = "(3959 * ACOS(COS(RADIANS(:latitude)) * COS(RADIANS(latitude)) * COS(RADIANS(longitude) - RADIANS(:longitude)) + SIN(RADIANS(:latitude)) * SIN(RADIANS(latitude))))";


@Query(value = "SELECT a.* , " + countDistanceQuery + " AS distance FROM user a WHERE a.address LIKE %:address% HAVING distance < 25 ORDER BY distance LIMIT 0, 20" , nativeQuery = true)
public List<User> getNearsetLoactionOfSitter(String address, String latitude, String longitude);

Model

Here I will take the distance attribute as a @Transient to know the JPA does not present in the database.

package com.misha.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import lombok.ToString;
import javax.persistence.*;

@Entity
@ToString
@Table(name = "user",uniqueConstraints = { 
        @UniqueConstraint(columnNames = "email") 
    })
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String contactname;
    
    @Column(unique=true)
    private String email;

    private String password;

    private String company;
    
    private String location;

    private String address;

    private String latitude;

    private String longitude;

    private String open;

    private String close;

    private float chargesperhour;

    private String logo;

    private boolean enabled;
    
    @Transient
    private double distance;
    
    @Column(name = "reset_password_token")
    private String resetPasswordToken;
    
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

    public User() {
        super();
    }

    public User(Integer id, String contactname, String email, String password, String company, String location, String address,
            String latitude, String longitude, String open, String close, float chargesperhour, String logo,
            boolean enabled, String resetPasswordToken) {
        super();
        this.id = id;
        this.contactname = contactname;
        this.email = email;
        this.password = password;
        this.company = company;
        this.location = location;
        this.address = address;
        this.latitude = latitude;
        this.longitude = longitude;
        this.open = open;
        this.close = close;
        this.chargesperhour = chargesperhour;
        this.logo = logo;
        this.enabled = enabled;
        this.resetPasswordToken = resetPasswordToken;
    }


    public User(Integer id, String contactname, String email, String password, String company, String location,
            String address, String latitude, String longitude, String open, String close, float chargesperhour,
            String logo, boolean enabled, double distance, String resetPasswordToken, Set<Role> roles) {
        super();
        this.id = id;
        this.contactname = contactname;
        this.email = email;
        this.password = password;
        this.company = company;
        this.location = location;
        this.address = address;
        this.latitude = latitude;
        this.longitude = longitude;
        this.open = open;
        this.close = close;
        this.chargesperhour = chargesperhour;
        this.logo = logo;
        this.enabled = enabled;
        this.distance = distance;
        this.resetPasswordToken = resetPasswordToken;
        this.roles = roles;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContactname() {
        return contactname;
    }

    public void setContactname(String contactname) {
        this.contactname = contactname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }
    

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getOpen() {
        return open;
    }

    public void setOpen(String open) {
        this.open = open;
    }

    public String getClose() {
        return close;
    }

    public void setClose(String close) {
        this.close = close;
    }

    public float getChargesperhour() {
        return chargesperhour;
    }

    public void setChargesperhour(float chargesperhour) {
        this.chargesperhour = chargesperhour;
    }

    public String getLogo() {
        return logo;
    }

    public void setLogo(String logo) {
        this.logo = logo;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
    
    public String getResetPasswordToken() {
        return resetPasswordToken;
    }

    public void setResetPasswordToken(String resetPasswordToken) {
        this.resetPasswordToken = resetPasswordToken;
    }
    
    public double getDistance() {
        return distance;
    }

    public void setDistance(double distance) {
        this.distance = distance;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

}

Controller

@GetMapping("/users/search")
    public ResponseEntity<List<User>> searchNearestLocation(@RequestParam String address, @RequestParam String latitude, @RequestParam String longitude){
            if(!address.isEmpty() && !latitude.isEmpty() && !longitude.isEmpty()) {             
        try {
        List<User> list = userService.getNearsetLoactionOfSitter(address, latitude, longitude);
                    
                    
        if( list.isEmpty() || list.size() == 0 ) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }       
            return new ResponseEntity<>(list, HttpStatus.OK);           
        }catch(Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
                }           
            }else {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }       
    }
    

I need to add Distance column in my response

I need to show calculated distance in response

@Transient annotation is used to mark a field to be transient for the mapping framework, which means the field marked with @Transient is ignored by mapping framework and the field not mapped to any database column.

Therefore try representing the distance property with @Formula annotation, and apply the distance calculation so that we can obtain the calculated value(I can see that you are calculating the distance based upon the image you have shared).

With @Formula , we can call native database functions and stored procedures and basically do anything that does not break the syntax of an SQL select clause for this field.

Reference: [https://www.concretepage.com/hibernate/formula_hibernate_annotation]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM