java 使用join springboot从两个表中检索数据

au9on6nz  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(114)

我在用户表和地址表之间建立了一个连接。我收到一条错误消息:"错误消息":无法调用com. pastrycertified. cda. models. Address. getId(),因为地址为空。我无法检索用户的地址我看不出它来自何处。它在尝试检索地址时返回空。感谢您的帮助
用户模型:

public class User extends AbstractEntity implements UserDetails{

    private String civility;

    private String lastname;

    private String firstname;

    @Column(unique = true)
    private String email;

    private String password;

    private String phone;

    private String birth_day;

    private Integer idAddress;

    @OneToOne
    private Address address;

    @OneToOne
    private Role role;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singletonList(new SimpleGrantedAuthority(role.getName()));
    }

    @Override
    public String getUsername() {
        return getEmail();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}

地址型号:

public class Address extends AbstractEntity{

    private Integer address_number;

    private String street;

    private String zipCode;

    private String city;

    private String country;

    @OneToOne
    @JoinColumn(name = "id_user")
    private User user;
}

用户日期至

public class UserDto {

    private Integer id;

    private String civility;

    private String lastname;

    private String firstname;

    private String birth_day;
 
    private String email;

    private String password;

    private String phone;

    private String role_name;

    private AddressDto address;

    public static UserDto fromEntity(User user) {

        return UserDto.builder()
                .id(user.getId())
                .civility(user.getCivility())
                .lastname(user.getLastname())
                .firstname(user.getFirstname())
                .birth_day(user.getBirth_day())
                .email(user.getEmail())
                .password(user.getPassword())
                .phone(user.getPhone())
                .role_name(user.getRole().getName())
                .address(AddressDto.fromEntity(user.getAddress()))
                .build();
    }

    public static User toEntity(UserDto user) {
        return User.builder()
                .id(user.getId())
                .civility(user.getCivility())
                .lastname(user.getLastname())
                .firstname(user.getFirstname())
                .birth_day(user.getBirth_day())
                .email(user.getEmail())
                .password(user.getPassword())
                .phone(user.getPhone())
                .role(
                        Role.builder()
                                .name(user.role_name)
                                .build()
                )
                .address(AddressDto.toEntity(user.getAddress()))
                .build();
    }
}

地址日期至

public class AddressDto {

    private Integer id;

    private Integer address_number;

    private String street;

    private String zipCode;

    private String city;

    private String country;

    private Integer userId;

    private Integer id_user;

    public static AddressDto fromEntity(Address address) {

        return AddressDto.builder()
                .id(address.getId())
                .address_number(address.getAddress_number())
                .street(address.getStreet())
                .zipCode(address.getZipCode())
                .city(address.getCity())
                .country(address.getCountry())
                .userId(address.getUser().getId())
                .build();
    }

    public static Address toEntity(AddressDto address) {

        return Address.builder()
                .id(address.getId())
                .address_number(address.getAddress_number())
                .street(address.getStreet())
                .zipCode(address.getZipCode())
                .city(address.getCity())
                .country(address.getCountry())
                .user(
                        User.builder()
                                .id(address.getUserId())
                                .build()
                )
                .build();
    }
}

用户服务实现

public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public UserDto findUserById(Integer id) {
        return userRepository.findUserById(id)
                .map(UserDto::fromEntity)
                .orElseThrow(() -> new EntityNotFoundException("Aucun utilisateur n'a été trouvé avec l'ID fourni :" + id));
    }
}

地址服务实现

public class AddressServiceImpl implements AddressService {

    private final AddressRepository addressRepository;
    private final ObjectsValidator<AddressDto> validator;

    @Override
    public AddressDto findById(Integer id) {
        return addressRepository.findById(id)
                .map(AddressDto::fromEntity)
                .orElseThrow(()-> new EntityNotFoundException("L'adresse n'existe pas"));
    }

    @Override
    public AddressDto findAddressByIdUser(Integer id) {
        return addressRepository.findAddressByIdUser(id)
                .map(AddressDto::fromEntity)
                .orElseThrow(()-> new EntityNotFoundException("L'utilisateur ne posséde pas d'adresse"));
    }
        addressRepository.save(address);
        return address.getId();
    }

}

用户存储库

public interface UserRepository extends JpaRepository<User, Integer> {

    @Query(value = "SELECT * FROM user INNER JOIN role ON user.role_id = role.id INNER JOIN address ON user.id = address.id_user WHERE user.id = :id", nativeQuery = true)
    Optional<User> findUserById(Integer id);
}
vlju58qv

vlju58qv1#

您可以如下所示更新存储库并重试吗?

public interface UserRepository extends JpaRepository<User, Integer> {

@Query(value = "SELECT * FROM user 
LEFT JOIN role ON user.role_id = role.id 
LEFT JOIN address ON user.id = address.id_user 
WHERE user.id = :id", nativeQuery = true)
Optional<User> findUserById(Integer id);
}

相关问题