繁体   English   中英

Spring Boot + H2 + JPA项目的问题

[英]problem with spring boot + h2 + jpa project

这是我的User类:

@Data
@Entity
public class User {

    @Id @GeneratedValue Long userID;
    String eMail;
    String phoneNumber;
    String displayName;
    //File displayPicture;
    String firstName;
    String middleName;
    String lastName;
    ArrayList<ClassRoom>adminOf=new ArrayList<>();
    ArrayList<ClassRoom>memberOf=new ArrayList<>();
    @NotNull
    int rating;
    boolean isTeacher;
    ArrayList<Assignment>assignmentsToSubmit=new ArrayList<>();
    ArrayList<Assignment>assignmentsSubmitted=new ArrayList<>();

    @OneToOne(fetch = FetchType.LAZY,targetEntity = LoginCredential.class)
    @JoinColumn(name = "userID",referencedColumnName = "userID")
    private LoginCredential loginCredential;

    User() {
    }
}

这是控制器UserController类:

@RestController
class UserController {

    private final UserRepository repository;
    UserController(UserRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/user/{id}")
    User one(@PathVariable Long id) {
        return repository.findById(id).orElseThrow(() -> new UserNotFoundException(id));
    }
}

我通过浏览器访问了http://localhost:8080/user/1 这是输出:

spring-h2-jpa获取映射

这里也显示了loginCredential ,但是我想返回除它之外的所有内容。

没有另一堂课怎么办?

@JsonIgnore添加到字段定义。 另外,您可以在类级别使用@JsonIgnoreProperties

我注意到您尝试给字段私有访问修饰符。 这不会将字段隐藏到JSON序列化程序中,因为您的类使用Lombok的@Data进行了注释,当不使用@ Getter / @ Setter进行覆盖访问时,该数据将访问方法设置为public。

或者您可以让另一个对象返回浏览器

@Builder
@Data
public class UserResponse {

    private String eMail;
    private String phoneNumber;
    private String displayName;

    // omitted the rest because im lazy

}


@RestController
public class UserController {

    private final UserRepository repository;

    @Autowire
    public UserController(UserRepository repository) {
        this.repository = repository;
    }

    @GetMapping("/user/{id}")
    public UserResponse one(@PathVariable Long id) {
        final Optional<UserEntity> user = repository.findById(id).orElseThrow(() -> new UserNotFoundException(id));
        return user.map(userEntity -> {
            return UserResponse.builder()
                .eMail(userEntity.getEMail())
                .phoneNumber(userEntity.getphoneNumber())

                // omitted the rest because im lazy

                .build();
        })

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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