简体   繁体   English

Querydsl - 线程“main”中的异常java.lang.IllegalArgumentException:没有给出的来源

[英]Querydsl - Exception in thread “main” java.lang.IllegalArgumentException: No sources given

I'm building a system using Spring MVC, Thymeleaf, JPA (Hibernate), and Querydsl. 我正在使用Spring MVC,Thymeleaf,JPA(Hibernate)和Querydsl构建一个系统。 While I was testing everything, I came across this exception: 当我测试一切时,我遇到了这个例外:

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)

Unfortunately, this is not very descriptive, and so, I do not know what to do. 不幸的是,这不是很具描述性,因此,我不知道该怎么做。 I've tried everything, but I do not find the solution. 我已经尝试了一切,但我没有找到解决方案。 And yes, thats all the message (the stacktrace). 是的,这就是所有消息(堆栈跟踪)。 Here are some files I'm using... 这是我正在使用的一些文件...

pom.xml (I may have some dependencies wrong, I don't know exactly): 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): 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: 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>

My main test class : 我的主要考试类

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();
    }
}

Service method : 服务方式

@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 method: 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
}

I'm learning how to use Querydsl. 我正在学习如何使用Querydsl。 If you need me to add any more code here, please say so. 如果您需要我在这里添加更多代码,请说明。 I already researched google, and also here in the community. 我已经研究了谷歌,也在社区。 Unfortunately I did not find anything about it. 不幸的是我没有发现任何相关信息。 Can somebody help me, please? 请问有人可以帮助我吗?

Thank you for your time and patience. 感谢您的时间和耐心。

EDIT 编辑

Here's my Domain Model Usuario Class: 这是我的Domain Model 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();
    }
}

The database is already created. 数据库已经创建。 I'm testing this on my personal pc. 我正在我的个人电脑上测试这个。

EDIT 2 编辑2

I would like to share my project. 我想分享我的项目。 Unfortunately I do not know how to use Github, and my post have almost 30k characters, so I uploaded my project (made with Eclipse Mars 2) as a war file. 不幸的是我不知道如何使用Github,我的帖子有近30k字符,所以我上传了我的项目(用Eclipse Mars 2制作)作为war文件。 Here are the links: 以下是链接:

http://www.megafileupload.com/8hon/Sistema_Teste_001.war (click on free user download to download the war file) http://www.megafileupload.com/8hon/Sistema_Teste_001.war (点击免费用户下载下载war文件)

mirror (click on download this file to download) 镜像 (点击下载此文件下载)

To help, each package contains a file named "package-info". 为了提供帮助,每个包都包含一个名为“package-info”的文件。 If in case you have any questions, check out this file. 如果您有任何疑问,请查看此文件。 Other than that, english comments have been added for clarification. 除此之外,还增加了英文评论以供澄清。

I'm so sorry. 我很抱歉。 I know it's not very convenient to download my project this way, but it was the only solution I found at the time. 我知道以这种方式下载我的项目并不是很方便,但这是我当时发现的唯一解决方案。 That way you can fully see my project. 这样你就可以完全看到我的项目了。

And answering your question, I'm testing this code in the normal way, as an executable Java program. 回答你的问题,我正在以正常的方式测试这段代码,作为一个可执行的Java程序。 The Q classes are being generated, and my IDE is not accusing any syntax errors or anything. 正在生成Q类,我的IDE没有指责任何语法错误或任何东西。 I'm right clicking my project and choosing "Run As..." -> "3 Java Application" to run. 我正确地点击我的项目并选择“Run As ...” - >“3 Java Application”来运行。 To generate my Q classes I'm clicking on "Run As..." -> "8 Maven generate-sources". 为了生成我的Q类,我点击“Run As ...” - >“8 Maven generate-sources”。

Well I'm embarrassed to say I didn't catch this sooner. 好吧,我很尴尬地说我没有早点抓住这个。 Your syntax on your query is actually wrong 您的查询语法实际上是错误的

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

should be 应该

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

Its selectFrom instead of select. 它的selectFrom而不是select。

My suspicion is that the generated sources are not on the build path within your Eclipse project. 我怀疑生成的源不在Eclipse项目的构建路径上。 Therefore when you run your Java application it is not able to find the Q source files/classes. 因此,当您运行Java应用程序时,它无法找到Q源文件/类。 Right click on your Eclipse Mars project and select the "Properties" option. 右键单击Eclipse Mars项目,然后选择“属性”选项。 Make sure you are on the "Source" tab and click "Add Folder" and select the target/generated-sources/java folder and Click "OK". 确保您位于“源”选项卡上并单击“添加文件夹”并选择目标/ generated-sources / java文件夹,然后单击“确定”。 This will add the generated-sources to your Eclipse Mars project. 这会将生成的源添加到Eclipse Mars项目中。 Then try running your Java main class. 然后尝试运行Java主类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 线程“主”java.lang.IllegalArgumentException 中的异常:无法将 Object 格式化为数字 - Exception in thread “main” java.lang.IllegalArgumentException: Cannot format given Object as a Number 线程“主”中的异常java.lang.IllegalArgumentException:非法的组件位置 - Exception in thread “main” java.lang.IllegalArgumentException: illegal component position 线程“ main”中的异常java.lang.IllegalArgumentException:image == null - Exception in thread “main” java.lang.IllegalArgumentException: image == null 线程“ main”中的异常java.lang.IllegalArgumentException:将窗口添加到容器 - Exception in thread “main” java.lang.IllegalArgumentException: adding a window to a container 蜂巢中“主”线程中的异常java.lang.IllegalArgumentException - Exception in thread “main” java.lang.IllegalArgumentException in hive 线程“主”中的异常java.lang.IllegalArgumentException:无效的ObjectId [7887978] - Exception in thread “main” java.lang.IllegalArgumentException: invalid ObjectId [7887978] 我在带有jsoup的线程“ main” java.lang.IllegalArgumentException中有一个异常 - I have an exception in thread “main” java.lang.IllegalArgumentException with jsoup 线程“ main”中的异常java.lang.IllegalArgumentException:in不能为null - Exception in thread “main” java.lang.IllegalArgumentException: in must not be null 线程“ main”中的异常java.lang.IllegalArgumentException:URI不是分层的 - Exception in thread “main” java.lang.IllegalArgumentException: URI is not hierar chical 线程“主”中的异常java.lang.IllegalArgumentException:setSelectedIndex:4超出范围 - Exception in thread “main” java.lang.IllegalArgumentException: setSelectedIndex: 4 out of bounds
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM