简体   繁体   中英

How to return fields in Spring Boot that is not present in the model?

So I have a use case where I want to return a particular attribute for all the rows of a table. But the attribute does not exist in the table. It should be generated on the fly.

For example - A table called Student - has the following attribute * ID * Name

Now, when I use the repository for this model class, I want to return all the rows of data including ID and Name but also append another property called URL along with each row. So output will be -

  • ID
  • Name
  • URL

The data for the URL can be generated on the fly - say = "example.com/"+ID

How shall I proceed ?

The same model/Repository/Service class for this entity are as follows -

Entity Student

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class StudentDetail {

            @Id
            private Long ID;
            private String Name; 

    }

Repository

@Repository
public interface StudentDetail  extends JpaRepository<StudentDetail , Integer> {

}

Service

@Override
    public List<StudentDetail> getStudentDetails() {
        List<StudentDetail> studentDetail = studentDetailsRepository.findAll();
        return studentDetail;
    }

The service will return all the rows with only ID and Name attribute. How do I calculate the URL parameter in repository ?

You can add a transient field (it means, it won't be mapped to any column and persisted):

public class StudentDetail {

        @Id
        private Long ID;
        private String Name;
        @Transient
        private String url = // Here comes your implementation

}

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