Pessoal tenho um formulário que carrega os dados de Categoria na Tabela usando o Lazy datatable do primefaces, do momento esta funcionando, porém tenho necessidade de listar as categorias que compartilham da mesma chaveEmpresa.
Ai começa meu problema, pela falta de domínio não consigo colocar o WHERE chaveEmpresa = 1 Exemplo neste tipo de carregamento.
Peço ajuda, segui meu codigo:
@Entity
@Table(name = “categoria”)
public class Categoria implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigo;
@Column(nullable = false, length = 30, unique = false)
private String nome;
@Column(nullable = false, name = "chave")
private Long chaveEmpresa;
@Column(nullable = true)
private boolean estado;
}
@Named
@ViewScoped
public class CategoriaController implements Serializable {
private static final long serialVersionUID = 1L;
private Categoria categoria;
private List<Categoria> categorias;
@Autowired
private CategoriaService categoriaService;
private CategoriaLazyDataModel categoriaLazys;
@Autowired
private Seguranca usuarioLogado;
@PostConstruct
public void inicializar() {
this.categoriaLazys = new CategoriaLazyDataModel(categoriaService, usuarioLogado.getEmpresa().getCodigo());
}
}
public class CategoriaLazyDataModel extends LazyDataModel implements SelectableDataModel {
private static final long serialVersionUID = -6123945723069023025L;
private final transient CategoriaService categoriaService;
private static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASCENDING;
private static final String DEFAULT_SORT_FIELD = "nome";
private Long chave;
public CategoriaLazyDataModel(CategoriaService categoriaService, Long chave) {
this.categoriaService = categoriaService;
this.chave = chave;
}
@Override
public Object getRowKey(Categoria categoria) {
return categoria.getCodigo();
}
@Override
public Categoria getRowData(String rowKey) {
Long rowId = Long.valueOf(rowKey);
List<Categoria> categorias = (List<Categoria>) super.getWrappedData();
return categorias.stream().filter(categoria -> categoria.getCodigo().equals(rowId)).findAny().orElse(null);
}
@SuppressWarnings("deprecation")
@Override
public List<Categoria> load(int first, int pageSize, List<SortMeta> multiSortMeta, Map<String, Object> filters) {
Sort sort = new Sort(getDirection(DEFAULT_SORT_ORDER), DEFAULT_SORT_FIELD);
if (multiSortMeta != null) {
List<Order> orders = multiSortMeta.stream()
.map(m -> new Order(getDirection(m.getSortOrder() != null ? m.getSortOrder() : DEFAULT_SORT_ORDER),
m.getSortField()))
.collect(Collectors.toList());
sort = new Sort(orders);
}
return filterAndSort(first, pageSize, filters, sort);
}
@Override
public List<Categoria> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
Sort sort = null;
if (sortField != null) {
sort = new Sort(getDirection(sortOrder != null ? sortOrder : DEFAULT_SORT_ORDER), sortField);
} else if (DEFAULT_SORT_FIELD != null) {
sort = new Sort(getDirection(sortOrder != null ? sortOrder : DEFAULT_SORT_ORDER), DEFAULT_SORT_FIELD);
}
return filterAndSort(first, pageSize, filters, sort);
}
private List<Categoria> filterAndSort(int first, int pageSize, Map<String, Object> filters, Sort sort) {
Map<String, String> filtersMap = filters.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString()));
@SuppressWarnings("deprecation")
Page<Categoria> page = categoriaService.buscarPeloFitro(chave,filtersMap, new PageRequest(first / pageSize, pageSize, sort));
this.setRowCount(((Number) page.getTotalElements()).intValue());
this.setWrappedData(page.getContent());
return page.getContent();
}
private static Direction getDirection(SortOrder order) {
switch (order) {
case ASCENDING:
return Direction.ASC;
case DESCENDING:
return Direction.DESC;
case UNSORTED:
default:
return null;
}
}
}
@Service
public class CategoriaService {
@Autowired
private CategoriaRepository categoriaRepository;
public Page<Categoria> buscarPeloFitro(Long chave, Map<String, String> filters, Pageable pageable) {
return categoriaRepository.findAll(getFilterSpecification(filters), pageable);
}
private Specification<Categoria> getFilterSpecification(Map<String, String> filterValues) {
return (Root<Categoria> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> {
Optional<Predicate> predicate = filterValues.entrySet().stream()
.filter(v -> v.getValue() != null && v.getValue().length() > 0).map(entry -> {
Path<?> path = root;
String key = entry.getKey();
if (entry.getKey().contains(".")) {
String[] splitKey = entry.getKey().split("\\.");
path = root.join(splitKey[0]);
key = splitKey[1];
}
return builder.like(path.get(key).as(String.class), "%" + entry.getValue() + "%");
}).collect(Collectors.reducing((a, b) -> builder.and(a, b)));
return predicate.orElseGet(() -> alwaysTrue(builder));
};
}
private Predicate alwaysTrue(CriteriaBuilder builder) {
return builder.isTrue(builder.literal(true));
}
}
public interface CategoriaRepository
extends JpaRepository<Categoria, Long>, JpaSpecificationExecutor {
Page<Categoria> findAllByChaveEmpresa(@Nullable Specification<Categoria> filterSpecification, Pageable pageable,@Param("chaveEmpresa") Long chave);
}
