java - 从实体到 DTO 的转变

标签 java spring dto

我想在所有类中使用 DTO 对象,但当我从任何地方将 <User> 更改为 <UserDTO> 时,出现错误。

我的错误日志是;

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class de.javatar81.examples.domain.UserDTO

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class de.javatar81.examples.domain.UserDTO

Caused by: java.lang.IllegalArgumentException: Not a managed type: class de.javatar81.examples.domain.UserDTO

用户.class;

    @Entity
    @Table(name="USER")
    public class User implements Serializable {

        private static final long serialVersionUID = -7860243025833384447L;

        @Id
        private Long id;

        private String login;
        private String firstName;
        private String lastName;
        private Date dayOfBirth;
        @ManyToOne
        private User manager;

//setters and getters

    }

UserDTO.class;

    public class UserDTO implements Serializable {

        private static final long serialVersionUID = -7860243025833384447L;

        private Long id;
        private String login;
        private String firstName;
        private String lastName;
        private Date dayOfBirth;
        private String city;
        private String district;

//setters and getters

    }

UserRepository.class;

public interface UserRepository extends PagingAndSortingRepository<UserDTO, Long>, JpaSpecificationExecutor<UserDTO>, JpaRepository<UserDTO, Long>, Repository<UserDTO, Long>{
    @Query(value = "select * from user where login like :filters% order by login \n-- #pageable\n",
    countQuery = "select count(*) from user where login like :filters%",
    nativeQuery = true)
    Page<UserDTO> findByLogin(@Param("filters") String filters, Pageable pageable);
}

UserService.class;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<UserDTO> findByFilter(Map<String, String> filters, Pageable pageable) {
        return userRepository.findAll(getFilterSpecification(filters), pageable);
    }

    public Page<UserDTO> findByLogin(String filters, Pageable pageable) {
        return userRepository.findByLogin(filters.toLowerCase(), pageable);
    }

    @Transactional
    public void create(UserDTO user) {
        userRepository.save(user);
    }

    private Specification<UserDTO> getFilterSpecification(Map<String, String> filterValues) {
        return (Root<UserDTO> 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));
    }

}

UserBean.class;

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class UserBean {

    @Autowired
    private UserService userService;
    private UserLazyDataModel users;

    @PostConstruct
    private void init() {
        this.users = new UserLazyDataModel(userService);
    }

    public UserLazyDataModel getUsers() {
        return users;
    }
}

UserLazyDataModel.class;

public class UserLazyDataModel extends LazyDataModel<UserDTO> implements SelectableDataModel<UserDTO> {

    private static final long serialVersionUID = -6123945723069023025L;
    private final transient UserService userService;
    private static final SortOrder DEFAULT_SORT_ORDER = SortOrder.ASCENDING;
    private static final String DEFAULT_SORT_FIELD = "id";
    private String columnName;
    private String filter;

    public UserLazyDataModel(UserService userService) {
        this.userService = userService;
    }

    @Override
    public Object getRowKey(UserDTO user) {
        return user.getId();
    }

    @Override
    public UserDTO getRowData(String rowKey) {
        Long rowId = Long.valueOf(rowKey);
        @SuppressWarnings("unchecked")
        List<UserDTO> users = (List<UserDTO>) super.getWrappedData();
        return users.stream().filter(user -> user.getId().equals(rowId)).findAny().orElse(null);
    }

    @Override
    public List<UserDTO> 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<UserDTO> 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<UserDTO> 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()));

        if (!filters.isEmpty()) {
            filters.forEach((k, v) -> {
                columnName = new String(k.toString());
                filter = new String(v.toString());
            });
        } else {
            columnName = new String("login");
            filter = new String("");
        }

        Page<UserDTO> page = userService.findByFilter(filtersMap, new PageRequest(first / pageSize, pageSize, sort));
        Page<UserDTO> pageLogin = userService.findByLogin(filter, new PageRequest(first / pageSize, pageSize));
        this.setRowCount(((Number) pageLogin.getTotalElements()).intValue());
        this.setWrappedData(pageLogin.getContent());
        return pageLogin.getContent();
    }

    private static Direction getDirection(SortOrder order) {
        switch (order) {
        case ASCENDING:
            return Direction.ASC;
        case DESCENDING:
            return Direction.DESC;
        case UNSORTED:
        default:
            return null;
        }
    }
}

index.xhtml;

<?xml version="1.0"?>
<ui:composition xmlns:f="http://java.sun.com/jsf/core"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:pe="http://primefaces.org/ui/extensions">
    <h:head>
    </h:head>
    <h:body styleClass="login">
        <f:view transient="true">
            <h:form id="form">
                <p:dataTable var="users" value="#{userBean.users}" paginator="true"
                    rows="10" sortMode="multiple"
                    paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
                    rowsPerPageTemplate="5,10,15" selectionMode="single" id="userTable"
                    lazy="true">
                    <p:column headerText="Id" sortBy="#{users.id}" filterBy="#{users.id}">
                        <h:outputText value="#{users.id}" />
                    </p:column>
                    <p:column headerText="Login" sortBy="#{users.login}"
                        filterBy="#{users.login}">
                        <h:outputText value="#{users.login}" />
                    </p:column>
                    <p:column headerText="Firstname" sortBy="#{users.first_Name}"
                        filterBy="#{users.firstName}">
                        <h:outputText value="#{users.firstName}" />
                    </p:column>
                    <p:column headerText="Lastname" sortBy="#{users.lastName}"
                        filterBy="#{users.lastName}">
                        <h:outputText value="#{users.lastName}" />
                    </p:column>
                    <p:column headerText="DayOfBirth" sortBy="#{users.dayOfBirth}"
                        filterBy="#{users.dayOfBirth}">
                        <h:outputText value="#{users.dayOfBirth}" />
                    </p:column>
                    <p:column headerText="Manager" sortBy="#{users.manager.lastName}"
                        filterBy="#{users.manager.lastName}">
                        <h:outputText value="#{users.manager.lastName}" />
                    </p:column>
                </p:dataTable>
            </h:form>
        </f:view>
    </h:body>
</ui:composition>

我还需要做什么?

最佳答案

public interface UserRepository extends PagingAndSortingRepository<UserDTO, Long>, JpaSpecificationExecutor<UserDTO>, JpaRepository<UserDTO, Long>, Repository<UserDTO, Long>{
@Query(value = "select * from user where login like :filters% order by login \n-- #pageable\n",
countQuery = "select count(*) from user where login like :filters%",
nativeQuery = true)
Page<UserDTO> findByLogin(@Param("filters") String filters, Pageable pageable);}

通过查看 UserRepository,似乎没有创建 UserRepository 的 bean,因为您忘记使用 @Repository 注释来注释存储库。

您必须使用@Repository(为组件/类创建Bean 的Spring 构造型)来注释UserRepository。因此,在创建 UserRepository 的 bean 之后,您将能够执行您的操作。

关于java - 从实体到 DTO 的转变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193201/

相关文章:

Spring Boot OAuth2 和 Oracle IDCS : JWK Set URI responds with 401 UNAUTHORIZED, 需要 token

java - 带有@Document的mongodb Multi-Tenancy 咒语

c# - 如何使用 AutoMapper 将 Dto 映射到具有嵌套对象的现有对象实例?

java - hibernate 投影具有明显的

java - Android 约束布局不会在全屏上拉伸(stretch)

java - DoubleStream 和 LongStream 的范围方法

java - 从spring-data-jdbc的 "Entities"生成脚本sql

java - Spring-HTTP Status 500 - 请求处理失败;嵌套异常是 java.lang.IllegalArgumentException : [￞] is not a hexadecimal digit

graphql - GraphQL 是否消除了数据传输对象?

java - org.hibernate.NonUniqueObjectException : A different object with the same identifier value was already associated with the session