Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querydsl - Exception in thread "main" java.lang.IllegalArgumentException: No sources given

I'm building a system using Spring MVC, Thymeleaf, JPA (Hibernate), and 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):

<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>

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:

@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. 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:

@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

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. Here are the links:

http://www.megafileupload.com/8hon/Sistema_Teste_001.war (click on free user download to download the war file)

mirror (click on download this file to download)

To help, each package contains a file named "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. The Q classes are being generated, and my IDE is not accusing any syntax errors or anything. I'm right clicking my project and choosing "Run As..." -> "3 Java Application" to run. To generate my Q classes I'm clicking on "Run As..." -> "8 Maven generate-sources".

like image 386
Loa Avatar asked Jan 19 '17 17:01

Loa


1 Answers

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.

like image 67
M. Rizzo Avatar answered Oct 18 '22 09:10

M. Rizzo