【问题标题】:Querydsl - Exception in thread "main" java.lang.IllegalArgumentException: No sources givenQuerydsl - 线程“主”java.lang.IllegalArgumentException 中的异常:没有给出源
【发布时间】:2017-01-19 17:01:17
【问题描述】:

我正在使用 Spring MVC、Thymeleaf、JPA (Hibernate) 和 Querydsl 构建一个系统。在测试所有内容时,我遇到了这个异常:

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Serviço nulo: false
[SER_USU] - Fazendo consulta...
[SER_USU] - Dao nulo: false

Exception in thread "main" java.lang.IllegalArgumentException: No sources given
    at com.querydsl.jpa.JPAQueryBase.serialize(JPAQueryBase.java:56)
    at com.querydsl.jpa.JPAQueryBase.serialize(JPAQueryBase.java:50)
    at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:98)
    at com.querydsl.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:94)
    at com.querydsl.jpa.impl.AbstractJPAQuery.fetch(AbstractJPAQuery.java:201)
    at com.regra7.st.db.dao.Dao_Usuario.getPorID(Dao_Usuario.java:35)
    at com.regra7.st.servico.Ser_Usuario.cadastrar(Ser_Usuario.java:46)
    at com.regra7.st.testes.TesteDAO_001.<init>(TesteDAO_001.java:43)
    at com.regra7.st.testes.TesteDAO_001.main(TesteDAO_001.java:19)

不幸的是,这不是很具有描述性,所以,我不知道该怎么做。我已经尝试了一切,但我没有找到解决方案。是的,这就是所有消息(堆栈跟踪)。这是我正在使用的一些文件...

pom.xml (我可能有一些依赖错误,我不太清楚):

<project 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.regra7</groupId>
    <artifactId>Sistema_Teste_001</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>

            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <!-- QUERYDSL -->
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources/java</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

        <!-- SPRING MVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>

        <!-- SPRING CONTEXT (SPRING CORE - TRANSIENT) -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>

        <!-- POSTGRESQL DRIVER JDBC -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.3-1102-jdbc41</version>
        </dependency>

        <!-- API SERVLET E JSP -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <!-- BEAN VALIDATION -->
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.6.Final</version>
        </dependency>

        <!-- IMPLEMENTAÇÃO BEAN VALIDATION (HIBERNATE) -->
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.4.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>

        <!-- THYMELEAF -->
        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.3.RELEASE</version>
        </dependency>

        <!-- THYMELEAF PARA O SPRING 4 -->
        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring4 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>3.0.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-core -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-core</artifactId>
            <version>4.1.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-jpa -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>4.1.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-apt -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>4.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!-- C3P0 -->
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

    </dependencies>
</project>

spring-config.xml (app-context.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<!-- ARQUIVO DE CONFIGURAÇÃO DE CONTEXTO DE APLICAÇÃO. -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd ">

    <!-- Mapeamento de recursos (arquivos css, fontes, imagens, dentre outros). -->
    <!-- <mvc:resources mapping="/css/**" location="/WEB-INF/recursos/css/" /> -->
    <!-- <mvc:resources mapping="/imagens/**" location="/WEB-INF/recursos/imagens/" /> -->
    <!-- <mvc:resources mapping="/fontes/**" location="/WEB-INF/recursos/fontes/" /> -->
    <!-- <mvc:resources mapping="/fontes/**" location="/WEB-INF/recursos/javascript/" /> -->

    <!-- Possibilita o uso de anotações Spring Mvc. -->
    <mvc:annotation-driven />

    <!-- Alternativa a declarar PersistenceAnnotationBeanPostProcessor, 
    um processador de anotações que lê @PersistenceContext. -->
    <context:annotation-config />

    <!-- Define local para procura de componentes Spring (beans configurados 
        por anotações em classes). -->
    <context:component-scan base-package="com.regra7.st.controle" />
    <context:component-scan base-package="com.regra7.st.db.dao" />
    <context:component-scan base-package="com.regra7.st.servico" />
    <context:component-scan base-package="com.regra7.st.testes" />

    <!-- MINHA DEFINIÇÃO COM MEUS CONVERSORES CRIADOS -->
    <mvc:annotation-driven conversion-service="servicoConversao"/>

    <!-- PROPERTY EDITOR NÃO FUNCIONOU, MAS ISSO SIM! -->
    <bean id="servicoConversao" 
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.regra7.st.formularios.conversores.Cov_String_LocalDate"/>
                <bean class="com.regra7.st.formularios.conversores.Cov_LocalDate_String"/>
            </set>
        </property>
    </bean>

    <!-- Template Resolver para Template Engine. -->
    <!-- <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> 
        <property name="prefix" value="/WEB-INF/templates/" /> <property name="suffix" 
        value=".html" /> <property name="templateMode" value="HTML5" /> </bean> -->

    <!-- SpringResourceTemplateResolver automatically integrates with Spring's 
        own -->
    <!-- resource resolution infrastructure, which is highly recommended. -->
    <bean id="templateResolver"
        class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/templates/" />
        <property name="suffix" value=".html" />
        <!-- HTML is the default value, added here for the sake of clarity. -->
        <property name="templateMode" value="HTML" />
        <!-- Template cache is true by default. Set to false if you want -->
        <!-- templates to be automatically updated when modified. -->
        <property name="cacheable" value="true" />
    </bean>

    <!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
    <!-- enables Spring's own MessageSource message resolution mechanisms. -->
    <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
        <!-- Enabling the SpringEL compiler with Spring 4.2.4 or newer can speed 
            up -->
        <!-- execution in most scenarios, but might be incompatible with specific -->
        <!-- cases when expressions in one template are reused across different 
            data -->
        <!-- ypes, so this flag is "false" by default for safer backwards -->
        <!-- compatibility. -->
        <property name="enableSpringELCompiler" value="true" />
    </bean>

    <!-- View resolver do Thymeleaf. -->
    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
    </bean>

    <!-- DATA SOURCE - Implementação do C3p0 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <!-- Propriedades de conexão -->
        <property name = "driverClass" value="org.postgresql.Driver" />
        <property name = "jdbcUrl" value="jdbc:postgresql://localhost:5432/SistemaTeste" />
        <property name = "user" value="postgres" />
        <property name = "password" value="admin" />

        <!-- Propriedades C3p0 -->
        <property name = "initialPoolSize"  value="3" />
        <property name = "minPoolSize"      value="5" />
        <property name = "maxPoolSize"      value="20" />
        <property name = "maxIdleTime"      value="1800" /> <!-- 1800 = 30 min -->
        <property name = "maxStatements"    value="50" />
    </bean>

    <!-- Fábrica EntityManager -->
    <bean id="emf"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="SistemaTeste" />
        <property name="dataSource" ref="dataSource" />
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.generate_statistics">false</prop>
                <prop key="hibernate.use_sql_comments">false</prop>
                <prop key="hibernate.default_schema">regrast</prop>
                <prop key="hibernate.jdbc.batch_size">50</prop>
            </props>
        </property>
    </bean>

    <!-- Gerenciador de transações PlatformTransactionManager -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf" />
    </bean>

    <!-- INTERCEPTADORES -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/usuario/*" />
            <bean class="com.regra7.st.interceptadores.Login" />
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence 
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="SistemaTeste" transaction-type="RESOURCE_LOCAL">

        <!-- PROVEDOR JPA -->
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    </persistence-unit>

</persistence>

我的主要测试类

public class TesteDAO_001 
{
    public static void main(String[] args) 
    {
        new TesteDAO_001(); // Line 19
    }

    public TesteDAO_001()
    {
        AbstractApplicationContext ac = new ClassPathXmlApplicationContext("/META-INF/spring-config.xml");
        Ser_Usuario servico = ac.getBean(Ser_Usuario.class); // Service class

        // For_Cadastro is an account registration form.
        For_Cadastro form = new For_Cadastro();
        form.setNome("Maria Pereira Maxwell"); // Name
        form.setLogin("rodrigologinsoares001");
        form.setSenha1("minhasenha001001"); // Password
        form.setSenha2("minhasenha001001"); // Password confirmation
        form.setCpf("01234567890"); // CPF = Brazil's Social ID
        form.setNascimento(LocalDate.now()); // Birthday
        form.setPai(0L); // Father
        form.setMae(0L); // Mother
        form.setGenero(0L); // Gender

        System.out.printf("Serviço nulo: %s%n" , servico == null);
        servico.cadastrar(form); // Line 43

        ac.close();
    }
}

服务方式

@Autowired
private Dao_Usuario _daoUsu;

@Transactional(rollbackFor = Exception.class)
public void cadastrar(For_Cadastro form)
{
    imprimir("Fazendo consulta...");
    imprimir(String.format("Dao nulo: %s%n", this._daoUsu == null));

    // This may return null.    
    Usuario pai = this._daoUsu.getPorID(form.getPai()); // Line 46
    Usuario mae = this._daoUsu.getPorID(form.getMae());

    imprimir(String.format("pai nulo: %s%n", pai == null));
    imprimir(String.format("mea nulo: %s%n", mae == null));

    // Usuario is a Domain Model Object. A POJO representation of a table.
    Usuario usu = new Usuario(form.getCpf()); // CPF = Brazil's Social ID
    usu.setGenero(Genero.getGenero(form.getGenero())); // Gender
    usu.setNome(form.getNome()); // Name
    usu.setLogin(form.getLogin());
    usu.setSenha(form.getSenha1().getBytes()); // Password
    usu.setNascimento(form.getNascimento()); // Birthday
    usu.setMae(mae); // Mother
    usu.setPai(pai); // Father

    imprimir("Modelo criado. Salvando...");
    this._daoUsu.salvarAtualizar(usu); // Save/Update
    imprimir("Persistência concluída.");
}

DAO 方法:

@PersistenceContext
protected EntityManager _em;

@Override
public Usuario getPorID(Long id) 
{   
    if(id == null)
    {
        return null;
    }

    return new JPAQueryFactory(this._em)
            .select(QUsuario.usuario)
            .where(QUsuario.usuario.id.eq(id))
            .fetchOne(); // Line 32
}

我正在学习如何使用 Querydsl。如果您需要我在这里添加更多代码,请说出来。我已经研究过谷歌,也在社区里。不幸的是,我没有找到任何关于它的信息。有人可以帮帮我吗?

感谢您的时间和耐心。

编辑

这是我的领域模型 Usuario 类:

@Entity
@Table(name="tb_usuarios")
public class Usuario
{
    @Id
    @SequenceGenerator(
            name="ger_id_usuario" , 
            sequenceName="tb_usuarios_id_seq" , 
            allocationSize=1 , 
            initialValue = 1)
    @GeneratedValue(
            strategy=GenerationType.SEQUENCE , 
            generator="ger_id_usuario")
    @Column(
            name = "usu_id" , 
            unique = true)
    protected Long id;

    // Name
    @Column(name = "usu_nome" , unique = true)
    protected String nome;

    // "Business Key"
    @Column(name = "usu_login" , unique = true)
    protected String login;

    // Password
    @Column(name = "usu_senha" , unique = true)
    protected byte[] senha;

    // Brazil's Social ID
    // "Business Key"
    @Column(name = "usu_cpf" , unique = true)
    protected String cpf;

    // Registration moment (date and time)
    @Column(name = "usu_nascimento")
    protected Date nascimento;

    // Gender
    @Column(name = "usu_genero")
    protected byte genero;

    // Father of this person (it may be null).
    @ManyToOne(fetch = FetchType.LAZY , cascade=CascadeType.ALL)
    @JoinColumn(name = "usu_pai")
    protected Usuario pai;

    // Mother of this person (it may be null).
    @ManyToOne(fetch = FetchType.LAZY , cascade=CascadeType.ALL)
    @JoinColumn(name = "usu_mae")
    protected Usuario mae;

    @Column(name = "usu_cadastro")
    protected Timestamp cadastro;

    // Children as a father.
    @OneToMany(mappedBy="pai" , fetch = FetchType.LAZY , cascade = CascadeType.ALL)
    protected Set<Usuario> filhosComoPai;

    // Children as a mother.
    @OneToMany(mappedBy="mae" , fetch = FetchType.LAZY , cascade = CascadeType.ALL)
    protected Set<Usuario> filhosComoMae;

    // Required by default by JPA, public or protected constructor, with no arguments.
    protected Usuario()
    {
        this.filhosComoPai = new HashSet<>();
        this.filhosComoMae = new HashSet<>();
    }

    /** For anyone who works with this class, it must provide a CPF, guaranteeing uniqueness, thus preventing this class from suffering problems when it is inside collections. */
    public Usuario(String cpf)
    {
        if(Util_Validador.isCPFValido(cpf) == false)
        {
            throw new IllegalArgumentException("CPF não encontra-se válido.");
        }

        this.cpf = cpf;

        this.filhosComoPai = new HashSet<>();
        this.filhosComoMae = new HashSet<>();
    }

    // Name
    public void setNome(String nome)
    {
        if(Util_Validador.isNomeValido(nome, 8) == false)
        {
            throw new IllegalArgumentException("Nome de pessoa não encontra-se válido.");
        }

        this.nome = nome;
    }

    public void setLogin(String login)
    {
        if(Util_Validador.isLoginValido(login, 8) == false)
        {
            throw new IllegalArgumentException("Login não encontra-se válido.");
        }

        this.login = login;
    }

    // Password
    public void setSenha(byte[] senha)
    {
        this.senha = senha;
    }

    // Birthday
    public void setNascimento(LocalDate nascimento)
    {
        this.nascimento = Date.valueOf(nascimento);
    }

    // Gender
    public void setGenero(Genero genero)
    {
        if(genero == null)
        {
            throw new NullPointerException("O gênero passado como argumento encontra-se nulo.");
        }

        this.genero = genero.getID();
    }

    /** Defines a father for this person (child).*/
    public void setPai(Usuario pai)
    {
        // It is already?
        if( this.pai == null ||
            this.pai.equals(pai) == false)
        {
            // Remove previous father from this child.
            if(this.pai != null)
            {
                this.pai.removeFilho(this);
            }

            // Defines the new father for this child.
            // There may be a null assignment here!
            this.pai = pai;

            // Add this child to a new parent.
            if(pai != null)
            {
                if(pai.getFilhos().contains(this) == false)
                {
                    pai.addFilho(this);
                }
            }
        }
    }

    // Same logic.
    public void setMae(Usuario mae)
    {
        if( this.mae == null ||
            this.mae.equals(mae) == false)
        {
            if(this.mae != null)
            {
                this.mae.removeFilho(this);
            }

            this.mae = mae;

            if(mae != null)
            {
                if(mae.getFilhos().contains(this) == false)
                {
                    mae.addFilho(this);
                }
            }
        }
    }

    public Long getID()
    {
        return this.id;
    }

    // Name
    public String getNome()
    {
        return this.nome;
    }

    public String getLogin()
    {
        return this.login;
    }

    // Password
    public byte[] getSenha()
    {
        return this.senha;
    }

    // CPF = Brazil's Social ID
    public String getCPF()
    {
        return this.cpf;
    }

    // Birthday
    public LocalDate getNascimento()
    {
        return this.nascimento.toLocalDate();
    }

    // Gender
    public Genero getGenero()
    {
        return Genero.getGenero(
                Long.getLong(
                        Byte.toString(this.genero)));
    }

    // Father
    public Usuario getPai()
    {
        return this.pai;
    }

    // Mother
    public Usuario getMae()
    {
        return this.mae;
    }

    // Date and time of registration (produced by database after insertion).
    public LocalDateTime getCadastro()
    {
        return this.cadastro.toLocalDateTime();
    }

    // Children of this person
    public Set<Usuario> getFilhos()
    {
        // "Genero" is a enum type (Gender), with MALE ("HOMEM") and FEMALE ("MULHER").
        if(this.getGenero() == Genero.HOMEM)
        {
            return Collections.unmodifiableSet(this.filhosComoPai);
        }

        return Collections.unmodifiableSet(this.filhosComoMae);
    }

    // Add a child ("filho") to this person.
    public boolean addFilho(Usuario filho)
    {
        this.isUsuarioNula(filho);
        boolean add = false;

        // FATHER
        if(this.getGenero() == Genero.HOMEM)
        {
            add = this.filhosComoPai.add(filho);

            if(add)
            {
                if( filho.getPai() == null || 
                    filho.getPai().equals(this) == false)
                {
                    Usuario paiAnterior = filho.getPai();

                    if(paiAnterior != null)
                    {
                        paiAnterior.removeFilho(filho);
                    }

                    filho.setPai(this);
                }
            }
        }
        // MOTHER
        else
        {
            add = this.filhosComoMae.add(filho);

            if(add)
            {
                if( filho.getMae() == null ||
                    filho.getMae().equals(this) == false)
                {
                    Usuario maeAnterior = filho.getMae();

                    if(maeAnterior != null)
                    {
                        maeAnterior.removeFilho(filho);
                    }

                    filho.setMae(this);
                }
            }
        }

        return add;
    }

    // Removes the child ("filho") from this person.
    public boolean removeFilho(Usuario filho)
    {
        this.isUsuarioNula(filho);
        boolean rem = false;

        // FATHER
        if(this.getGenero() == Genero.HOMEM)
        {
            rem = this.filhosComoPai.remove(filho);

            if(rem)
            {
                if( filho.getPai() == null ||
                    filho.getPai().equals(this) == false)
                {
                    filho.setPai(null);
                }
            }
        }
        // MOTHER
        else
        {
            rem = this.filhosComoMae.remove(filho);

            if(rem)
            {
                if( filho.getMae() == null ||
                    filho.getMae().equals(this) == false)
                {
                    filho.setMae(null);
                }
            }
        }

        return rem;
    }

    // Just to print the same message.
    private void isUsuarioNula(Usuario p)
    {
        if(p == null)
        {
            throw new IllegalArgumentException("Usuario passada em argumento encontra-se nula.");
        }
    }

    @Override
    public boolean equals(Object o)
    {
        if (o == null) 
        {
            return false;
        }
        else if (o == this) 
        {
            return true;
        }
        else if (o.getClass() != this.getClass()) 
        {
            return false;
        }

        Usuario c = (Usuario) o;

        // This ensures consistent data work, and prevents something from happening silently, without us knowing why it happened.
        if(c.getCPF() == null || c.getCPF().length() <= 0)
        {
            throw new IllegalStateException("Valor de CPF inexistente. Uma comparação não é possível.");
        }

        return c.getCPF().equals(this.getCPF());
    }

    @Override
    public int hashCode()
    {
        // I'm using Apacho Commons Lang.
        return new HashCodeBuilder()
                .append(this.getCPF()).toHashCode();
    }
}

数据库已经创建。我正在我的个人电脑上对此进行测试。

编辑 2

我想分享我的项目。不幸的是,我不知道如何使用 Github,而且我的帖子有将近 30k 个字符,所以我将我的项目(使用 Eclipse Mars 2 制作)作为 war 文件上传。以下是链接:

http://www.megafileupload.com/8hon/Sistema_Teste_001.war(点击免费用户下载下载war文件)

mirror(点击下载此文件下载)

为了提供帮助,每个包都包含一个名为“package-info”的文件。如果您有任何疑问,请查看此文件。除此之外,已添加英文 cmets 以进行澄清。

我很抱歉。我知道以这种方式下载我的项目不是很方便,但这是我当时找到的唯一解决方案。这样你就可以完全看到我的项目了。

并回答您的问题,我正在以正常方式测试此代码,作为一个可执行的 Java 程序。 Q 类正在生成,我的 IDE 没有指责任何语法错误或任何东西。我右键单击我的项目并选择“运行方式...”->“3 Java 应用程序”来运行。要生成我的 Q 类,我单击“Run As...”->“8 Maven generate-sources”。

【问题讨论】:

  • 我认为您的课程命名和课程位置存在一些问题。您是否有一个名为 Usuario 且带有 @Entity 注释的实体?
  • @M.Rizzo 嗨!感谢您的评论。所以,我更新了我的问题。请你看一下好吗?你怎么看?
  • 看起来不错。您是否检查了输出目录 target/generated-sources/java 以及正在生成并驻留在文件夹中的 queryDSL Q 类。此外,有关如何运行测试的任何信息都会有所帮助。您是否将测试仅作为 maven 构建的一部分运行?
  • @M.Rizzo 再次感谢您的时间和关注。我进行了编辑(编辑 2)。请你看一下好吗?你现在怎么想?你一直很有礼貌。谢谢你,真的!
  • 我无法对这些下载执行任何操作,因为它们被检测为潜在恶意。如果你能进入 Github 我会看看。感谢您提供更多详细信息。

标签: java spring hibernate jpa querydsl


【解决方案1】:

好吧,我很尴尬地说我没有早点发现这个问题。您查询的语法实际上是错误的

return new JPAQueryFactory(this._em)
        .select(QUsuario.usuario)
        .where(QUsuario.usuario.id.eq(id))
        .fetchOne();  

应该是

 return new JPAQueryFactory(this._em)
        .selectFrom(QUsuario.usuario)
        .where(QUsuario.usuario.id.eq(id))
        .fetchOne(); 

它的 selectFrom 而不是 select。

【讨论】:

  • 嗯,我使用的Querydsl版本(4.1.4)没有selectFrom的方法。相反,它有两种方法:selectfrom。将两者放在一起后......一切都像手套一样工作!!!谢谢你!我永远不会忘记你的帮助!我很抱歉。你不是唯一一个没有看到它的人。我们在同一条船上。感谢您这些天的关注和耐心,真的。干杯! :]
  • JPAQuery 没有 selectFromJPAQueryFactory 有。我相信异常消息虽然正确,但不是很有帮助。如果他们添加了诸如“您使用过 from 吗?”之类的内容。这也建议解决问题,这确实很好。
  • 也遇到了这个问题。显然你必须像这样使用 select(field).from(entity): return new ArrayList(new JPAQueryFactory(getSessionFactory().getCurrentSession()) .select(qMyEntity.idInternal).from(qMyEntity) .where(qMyEntity .status.eq(WAITING) .and(qMyEntity.deleteDateInternal.isNull())) .fetch());
【解决方案2】:

我怀疑生成的源代码不在您的 Eclipse 项目的构建路径上。因此,当您运行 Java 应用程序时,它无法找到 Q 源文件/类。右键单击您的 Eclipse Mars 项目并选择“属性”选项。确保您位于“源”选项卡上并单击“添加文件夹”并选择目标/生成的源/java 文件夹并单击“确定”。这会将生成的源代码添加到您的 Eclipse Mars 项目中。然后尝试运行您的 Java 主类。

【讨论】:

  • 从昨天开始我一直在尝试使用 github,但没有成功。我想你现在可以看到一切了。都在这里:github.com/loagit/sistema_teste_001/tree/teste 我照你说的做了。也没有运气。对不起。但是,请看一下我的 git repo。再次感谢您!
  • 到目前为止,我还没有在不使用 Querydsl 的情况下测试到数据库的连接。我尝试使用纯 JPA 和 EntityManager 正常执行此操作。我发现了一个新错误。在我的 Spring 设置 (spring-config.xml) 中缺少以下内容:&lt;tx: annotation-driven transaction-manager = "transactionManager" /&gt; 我能够在不使用 Querydsl 的情况下连接并插入新记录。我认为这可以解决我的情况,但是,当再次尝试使用 Querydsl 时,我遇到了同样的问题。这几天我一直在努力解决这个问题……这让我很生气……
猜你喜欢
  • 2020-07-18
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多