Reputation: 332
I am creating a query for paging operation. But when I give the sort column, the answer is wrong. All Completed fields come true. Completed fields in database not true. If there is no sort column, the result is correct. The same problem persists when you do not give sort in Pageable and add an order to the query.
It works when i remove todoitem0_.item_desc as item_des4_0_ from the query. But I couldn't understand the problem
Problem is fixed when the description field is defined as varchar(255). But I need to define @Lob
Controller
@RestController
@CrossOrigin
@RequestMapping("/api/item")
public class TodoItemController {
@GetMapping(value = "/list")
private TodoItemDto getUserItems(Authentication authentication,
@RequestParam("page") int page, @RequestParam("sizePerPage") int sizePerPage){
Pageable pageable = PageRequest.of(page,sizePerPage, Sort.by("createdAt").descending());
return todoItemService.getUserItems(((CustomUserDetails) authentication.getPrincipal()).getId(),pageable);
}
}
Service
@Service
@Transactional
public class TodoItemServiceImpl implements TodoItemService {
@Override
public TodoItemDto getUserItems(long userId, Pageable pageable){
Page<TodoItem> itemPage = todoItemRepository.findUserItems(userId, pageable);
TodoItemDto dto = new TodoItemDto();
dto.setContent(itemPage.getContent());
dto.setTotal((int)itemPage.getTotalElements());
return dto;
}
}
Repository
public interface TodoItemRepository extends JpaRepository<TodoItem, Integer> {
@Query(value = "SELECT i FROM TodoItem i "
+ "INNER JOIN Todo t ON t.user.id = ?1 "
+ "WHERE i.todo.id = t.id ")
Page<TodoItem> findUserItems(long userId, Pageable pageable);
}
Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "items")
public class TodoItem{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotBlank(message = "Item name not be blank")
@Column(nullable = false, unique = true)
private String itemName;
@NotBlank(message = "Item description not be blank")
@Lob
private String itemDesc;
@ManyToOne
@JoinColumn(name = "todoId")
private Todo todo;
@Column(nullable = false)
private boolean completed = false;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable=false, updatable = false)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd / MM / yyyy")
private Date createdAt;
@PrePersist
protected void onCrearedAt() {
this.createdAt = new Date();
}
}
Hibernate Sql Query
select
todoitem0_.id as id1_0_,
todoitem0_.completed as complete2_0_,
todoitem0_.created_at as created_3_0_,
todoitem0_.item_desc as item_des4_0_,
todoitem0_.item_name as item_nam5_0_,
todoitem0_.todo_id as todo_id6_0_
from
items todoitem0_
inner join
todo todo1_
on (
todo1_.user_id=?
)
where
todoitem0_.todo_id=todo1_.id
order by
todoitem0_.created_at desc limit ?
Upvotes: 0
Views: 1007
Reputation: 1647
Notice this '1' digit in your query,
+ "INNER JOIN Todo t ON t.user.id = ?1 "
This is messing with your resultset
Upvotes: 1