java - 从 Java Spring Boot 中的 OneToMany 关系获取特定值

标签 java spring

在获取所有租金时,我只想获取 JSON 响应中的特定值。例如,我只想获取用户的电子邮件和用户名。使用当前代码,我从表 User 中获取所有值。我需要改变什么才能实现我想做的事情?非常欢迎有关此类问题的更多文档! :)

我有以下类(class):租金和用户:

@Entity
@Table(name="rents")
@Data
public class Rent extends BaseModel {
ApiModelProperty(example = "1584359718")
@NotNull
private long date_from;

@ApiModelProperty(example = "1584359718")
@NotNull
private long date_to;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;
}

@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name="users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User extends BaseModel implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;

@NotBlank
private String username;

@NotBlank
private String password;

@CreatedDate
public Long created;

@LastModifiedDate
private Long lastUpdate;

@ElementCollection(fetch = FetchType.EAGER)
@Builder.Default
private List<String> roles = new ArrayList<>();

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());
}

@ApiModelProperty(hidden = true)
@OneToMany(mappedBy = "triggeredBy", fetch = FetchType.LAZY)
@JsonBackReference
private List<Warning> warnings;

@OneToMany(mappedBy="user", fetch = FetchType.LAZY)
private List<Rent> rents;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "group_id")
private Group group;
}

此外,我还有请求和响应类:

@Data
public class RentRequest {
@ApiModelProperty(example = "12345")
@NotNull
private Device device_id;

@ApiModelProperty(example = "1584359718")
@NotNull
private long date_from;

@ApiModelProperty(example = "1584359718")
@NotNull
private long date_to;

@NotNull
private User user_id;

public Rent toRent() {
    Rent rent = new Rent();
    rent.setDate_from(this.date_from);
    rent.setDate_to(this.date_to);
    rent.setUser(this.user_id);
    return rent;
}

@Data
public class RentResponse(){
public RentResponse(){

}

public RentResponse(Rent rent) {
    if (rent != null) {
        this.date_from = rent.getDate_from();
        this.date_to = rent.getDate_to();
        //this.control = rent.getControl();
        //this.device_id = rent.getDevice_id();
        this.user_id = rent.getUser();
    }
}

@ApiModelProperty(example = "12345")
@NotNull
private Device device_id;

@ApiModelProperty(example = "1584359718")
@NotNull
private long date_from;

@ApiModelProperty(example = "1584359718")
@NotNull
private long date_to;

@ApiModelProperty(example = "1584359718")
@NotNull
private User user_id;

public List<RentResponse> toList(List<Rent> rentList) {
    List<RentResponse> rentResponseList = new ArrayList<>();
    for (Rent rent: rentList)
        rentResponseList.add(new RentResponse(rent));
    return rentResponseList;
}
}

最佳答案

希望您将 id 作为参数传递给 Controller ​​类,以便获取用户详细信息。您需要使用 ArrayListList 来完成任务。首先是通过传递 id 将用户的详细信息获取到 ArrayListList 中。我将提供简单的例子。在此示例中,Users 类是模型,UsersRepository 是存储库类,UsersController 是 Controller 类。这里的 List 用于存储与 id 有关的所有详细信息。 UsersRepository 中的方法将获取有关传递的 id 的所有详细信息。这些详细信息将存储在一个列表中,您无法直接传递这些详细信息,因为它包含该 id 的所有详细信息。因此,使用 for-each 循环将获取特定数据(电子邮件、用户名)并将其存储在数组中。如果你愿意,可以直接返回这个数组。但在这种情况下,我将这些数组索引再次放入 ArrayList 中,并且该 ArrayList 将被返回。这样它只返回电子邮件和用户名。

用户类别

package model;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;

@Entity
public class Users {

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

    @NotNull
    @Email
    private String email;
    @NotNull
    private String username;
    @NotNull
    private String password;
    @NotNull
    private int age;

    public Users() {
    }

    public Users(int id, @NotNull @Email String email, @NotNull String username, @NotNull String password, @NotNull int age) {
        this.id = id;
        this.email = email;
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

UsersRepository 类

package repository;

import model.Users;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UsersRepository extends CrudRepository<Users, Long> {

    List<Users> findUsersByIdIsLike(int id);

}

UsersController 类

package controller;

import model.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import repository.UsersRepository;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UsersController {

    @Autowired
    private UsersRepository usersRepository;

    @PostMapping(path = "/singleData")
    public ArrayList<String> getSingleUserData(@RequestParam("id") int id) {
        // get all data to the list using related to the id using the method in UsersRepository class
        List<Users> userAccountList = (List<Users>) usersRepository.findUsersByIdIsLike(id);

        String singleDetails[] = new String[2];

        if (userAccountList != null) {
            for (Users userAccount : userAccountList) {
                singleDetails[0] = userAccount.getEmail();
                singleDetails[1] = userAccount.getUsername();
            }
        }
        ArrayList<String> dataArrayList = new ArrayList<String>();

        // put data in singleDetails to an array list so that array list will be returned
        dataArrayList.add(singleDetails[0]);
        dataArrayList.add(singleDetails[1]);

        return dataArrayList;
    }

}

这对你的工作会有帮助。

关于java - 从 Java Spring Boot 中的 OneToMany 关系获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61855741/

相关文章:

java - 如何防止在 Android Oreo 中的 dobleTap 上启动重复 Activity

java - 如何在使用 JDBC 驱动程序和 MySQL DBMS 时回滚 CREATE TABLE 和 DROP TABLE 等 DDL 语句?

java - 如何在 Spring 中将 bean 集合创建为 XML Java 配置?

java - 找到对集合 : OneToMany empty collections refering to same PersistentBag 的共享引用

java - 如何在 Spring 中使用基于注释的属性

java - 什么是依赖注入(inject)?

java - java 中的多态性 : Why do we set parent reference to child object?

java - JSF Primefaces 下载文件

java - Spring Security - 身份验证失败 - 空白消息

java - 如何让用户使用 vaadin 文件下载器下载 zip 文件