加入两个表JPQL

时间:2017-11-19 15:33:10

标签: java spring hibernate jpql

@Entity
@Table(name="tblUser")    
public class User {

@Id
@GeneratedValue
@Column(name="id")
private Long id;

@Column(name="email",nullable=false)
private String email;

@Column(name="password",nullable=false)
private String password;

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

@OneToMany(mappedBy="user")
private List<Address> addresses = new ArrayList<>();
}



@Entity
@Table(name="tblAddress")
public class Address {

@Id
@GeneratedValue
@Column
private Long id;

@Column
private String streat;

@Column
private String number;

@ManyToOne(fetch=FetchType.EAGER)
private User user;
}



public interface UserService {
List<User> findAll(); 
}



@Service
public class JpaUserService implements UserService {
@Autowired
private UserRepository userRepository;

@Override
public List<User> findAll() {
    return userRepository.findAll();
    }
}



@Controller
@RequestMapping(value="/api/users")
public class ApiUserController {

@Autowired
private UserService userService;

@Autowired
private UserDTOToUser toUser;

@Autowired
private UserToUserDTO toDto;

@RequestMapping(method=RequestMethod.GET)
ResponseEntity<List<UserDTO>> getUser()

List<User> users = userService.findAll();

if(users == null || users.isEmpty()){
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

return new ResponseEntity<>(toDto.convert(users), HttpStatus.OK);
    }
}



@Repository
public interface UserRepository extends JpaRepository<User, Long> {

@Query("select u.id, a.number FROM User u LEFT JOIN u.addresses a WHERE u.id = a.user")
List<User> findAll();
}

当我尝试在我的localhost上的RestClient中运行我的代码时,我得到了这个例外:

{
"timestamp": 1511105123172,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.ClassCastException",
"message": "[Ljava.lang.Object; cannot be cast to jwd.wafepa.model.User",
"path": "/api/users"
}

简而言之,UserDTO是没有密码参数的User类。

如何在JPQL中编写正确的JOIN查询?

1 个答案:

答案 0 :(得分:1)

如果仅从表格中选择特定字段,

@Query只能返回List<Object>。建议您将@Query更改为SELECT u FROM User u LEFT JOIN u.addresses a WHERE u.id = a.user

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u LEFT JOIN u.addresses a WHERE u.id = a.user")
    List<User> findAll();
}