Domanda

Ho l'applicazione Web di esempio Hibernate 4.3.5 + Derby Database 10.10.1.1.1+ GlassFish4.0 con IDE Netbeans 8.0beta.

Ho la prossima eccezione:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:95)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3633)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3522)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
... 72 more 
.

Form da index.xhtml

<h:panelGrid id="panel1" columns="2" border="1"
                 cellpadding="5" cellspacing="1">
        <f:facet name="header">
            <h:outputText value="Add Customer Information"/>
        </f:facet>
        <h:outputLabel value="First Name:"/>
        <h:inputText value="#{customer.firstName}" id="fn"/>
        <h:outputLabel value="Last Name:"/>
        <h:inputText value="#{customer.lastName}" id="ln"/>
        <h:outputLabel value="Email:"/>
        <h:inputText value="#{customer.email}" id="eml"/>
        <h:outputLabel value="Date of Birth:"/>
        <h:inputText value="#{customer.sd}" id="s"/>
        <f:facet name="footer">
            <h:outputLabel value="#{customer.msg}" id="msg" styleClass="msg"/>
            <h:commandButton value="Save" action="#{customer.saveCustomer}">
            </h:commandButton>
        </f:facet>
    </h:panelGrid> 
.

cliente.java

    package com.javaknowledge.entity;

    import com.javaknowledge.dao.CustomerDao;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.persistence.*;    

    @ManagedBean
    @SessionScoped

    public class Customer implements java.io.Serializable {

    private Integer custId;
    private String firstName;
    private String lastName;
    private String email;
    private Date dob;
    private String sd, msg, selectedname;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    public Customer() {
    }

    public Customer(String firstName, String lastName, String email, Date dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.dob = dob;
    }

    public String getSd() {
        return sd;
    }

    public void setSd(String sd) {
        this.sd = sd;
    }

    public Integer getCustId() {
        return this.custId;
    }

    public void setCustId(Integer custId) {
        this.custId = custId;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    @Column(name = "EMAIL")
    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "DOB")
    public Date getDob() {
        return this.dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getSelectedname() {
        return selectedname;
    }

    public void setSelectedname(String selectedname) {
        this.selectedname = selectedname;
    }

    public void saveCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.addCustomer(this);
        this.msg = "Member Info Saved Successfull!";
        clearAll();
    }
    public void updateCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.updateCustomer(this);
        this.msg = "Member Info Update Successfull!";
        clearAll();
    }
    public void deleteCustomer() {
        CustomerDao dao = new CustomerDao();
        dao.deleteCustomer(custId);
        this.msg = "Member Info Delete Successfull!";
        clearAll();
    }

    public List<Customer> getAllCustomers() {
        List<Customer> users = new ArrayList<Customer>();
        CustomerDao dao = new CustomerDao();
        users = dao.getAllCustomers();
        return users;
    }

    public void fullInfo() {
        CustomerDao dao = new CustomerDao();
        List<Customer> lc = dao.getCustomerById(selectedname);
        System.out.println(lc.get(0).firstName);
        this.custId = lc.get(0).custId;
        this.firstName = lc.get(0).firstName;
        this.lastName = lc.get(0).lastName;
        this.email = lc.get(0).email;
        this.dob = lc.get(0).dob;
        this.sd = sdf.format(dob);
    }

    private void clearAll() {
        this.firstName = "";
        this.lastName = "";
        this.sd = "";
        this.email = "";
        this.custId=0;
    }

   }
.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/derbyDB</property>
    <property name="hibernate.connection.username">user1</property>
    <property name="hibernate.connection.password">user1</property>
    <property name="hibernate.hbm2ddl.auto">create</property>

    <property name="c3p0.min_size">1</property>
    <property name="c3p0.max_size">5</property>
    <property name="c3p0.timeout">300</property>
    <property name="c3p0.max_statements">50</property>
    <property name="c3p0.idle_test_period">300</property>

    <mapping class="com.javaknowledge.entity.Customer" resource="com/javaknowledge/entity/Customer.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
.

customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.javaknowledge.entity.Customer" table="CUSTOMERV" schema="APP">
        <id name="custId" type="java.lang.Integer">
            <column name="cust_id" />
            <generator class="increment" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="45" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="45" not-null="true" />
        </property>
        <property name="email" type="string">
            <column name="email" length="45" not-null="true" />
        </property>
        <property name="dob" type="date">
            <column name="dob" length="10" not-null="true" />
        </property>
   </class>
</hibernate-mapping>
.

È stato utile?

Soluzione

Alla fine ho trovato un errore!Spero che sia utile a qualcuno.Quando si esegue una richiesta al database (nel mio caso IT Apache Derby), il nome della base è necessario scrivere la prima lettera maiuscola in maiuscolo in minuscolo.

Questa è la query errata:

session.createQuery("select first_name from CUSTOMERV").
.

Questa è la query valida

session.createQuery("select first_name from Customerv"). 
.

e l'entità di classe deve essere lo stesso nome come database, ma non ne sono sicuro.

Altri suggerimenti

In HQL Query, non scrivere il nome della tabella , scrivi il tuo nome Entity Class Nome nella tua query come

String s = "from Entity_class name";
query qry = session.createUqery(s);
.

hibernate.cfg.xml Il file dovrebbe avere la mappatura per le tabelle come di seguito.Controlla se manca nel tuo file.

......
<hibernate-configuration>
......
......
  <session-factory>
......
<mapping class="com.test.bean.dbBean.testTableHibernate"/>
......
 </session-factory>

</hibernate-configuration>
.....
.

Se si utilizzano le annotazioni JPA per creare le entità e quindi assicurarsi che il nome della tabella sia mappato con l'annotazione @TAble anziché @Entity.

in modo errato mappato:

@Entity(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
   ....
   ....
}
.

Entità correttamente mappata:

@Entity
@Table(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
   ....
   ....
}
.

nessuna delle altre soluzioni funzionava per me.

Anche se non penso che sia la migliore pratica, ho dovuto aggiungilo nel codice come questo

configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

qui

public static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();

    configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}
.

potrebbe essere questo renderà più chiaro, e naturalmente ha senso anche.

@Entity
@Table(name = "users")

/**
 * 
 * @author Ram Srinvasan
 * Use class name in NamedQuery
 * Use table name in NamedNativeQuery
 */
@NamedQueries({ @NamedQuery(name = "findUserByName", query = "from User u where u.name= :name") })

@NamedNativeQueries({ @NamedNativeQuery(name = "findUserByNameNativeSQL", query = "select * from users u where u.name= :name", resultClass = User.class) })
public class User implements Principal {
...
}
.

C'è un'altra possibilità di ottenere questa eccezione anche abbiamo usato il nome della classe I.e., se abbiamo due classi con lo stesso nome in diversi pacchetti.Otterremo questo problema.

Penso che ibernati possa ottenere ambiguità e getta questa eccezione, quindi la soluzione è usare il nome completo qualificato (come com.test.customustomer )

Ho aggiunto questa risposta che aiuterà nello scenario come ho detto.Ho ottenuto lo stesso scenario rimasto bloccato per un po 'di tempo.

Anch'io ho affrontato un problema simile quando ho iniziato a lavorare su Hibernate.Tutto sommato, posso dire è nella creatività è necessario passare il nome della classe di entità non il nome della tabella a cui è mappata l'entità.

Nel mio caso con Data Spring JPA Ho appena dimenticato di aggiungere nativeQuery = true

@Query( value = "update some_table set some_field_id = null where org_id = :orgId", nativeQuery = true)
.

Se a nessuna possibilità utilizzando Java per la configurazione, potrebbe essere necessario controllare la Dichiarazione di sotto bean se si dispone di modifiche al livello del pacchetto.Ad esempio: il pacchetto com.abc.spring è stato modificato in com.bbc.spring

@Bean
    public SessionFactory sessionFactory() {

        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
        //builder.scanPackages("com.abc.spring");    //Comment this line as this package no longer valid.
        builder.scanPackages("com.bbc.spring");
        builder.addProperties(getHibernationProperties());

        return builder.buildSessionFactory();
    }
.

Significa che il tuo tavolo non è mappato al JPA. Entrambi il nome della tabella è sbagliato (forse caso sensibile), oppure è necessario inserire una voce nel file XML.

Happy CoDing :)

Altre persone che utilizzano lezioni di mappatura per ibernate, assicurarsi che siano indirizzate correttamente a modello pacchetto nella dichiarazione di fagioli sessionFactory nella parte seguente:

<property name="packagesToScan" value="com.mblog.model"></property>
.

Il problema parzialmente è stato risolto.Oltre a creare JDBC / Resource (DB Derby) ha dovuto creare il pool di connessione JDBC per la risorsa DB nella console di amministrazione del Glassfish e controllarlo sul Pinging.Ora tutto il funzionamento crudo funziona bene.Controllo, oggetto cliente nel database che aggiunge correttamente, aggiorna ed elimina anche.Ma nel registro di output del pesce Glassfish ha la stessa eccezione:

SEVERE:   org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped [select concat(first_name, ' ', last_name) as name from CUSTOMERV]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
    .......

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
.

dovrebbe utilizzare il nome della classe di entità per il metodo EM.Createequy o Dovrebbe usare il metodo EM.CreataNativeQuery per la query nativa senza classe di entità

con classe di entità:

em.creakeyery ("Seleziona first_name da customerver")

senza classe di entità o query nativa:

em.creaenativequery ("Selezionare c.first_name da customerver c")

Nel mio caso: Molla Boot 2, più dataSource (predefinito e personalizzato).entityManager.createQuery Go Storge: 'Entity non è mappato'

Sebbene Debug, scopro che l'unità UnityManager è sbagliato (dovrebbe essere personalizzato, ma il fatto è predefinito) Il modo giusto:

@PersistenceContext(unitName = "customer1") // !important, 
private EntityManager em;
.

Il customer1 è dalla seconda classe di configurazione DataSource:

@Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier("customer1DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.xxx.customer1Datasource.model")
            .persistenceUnit("customer1")
            // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
            // injects an EntityManager.
            // It's generally better to use PersistenceContext unless you really need to
            // manage the EntityManager lifecycle manually.
            // 【4】
            .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}
.

Allora, l'EntityManager ha ragione.

Ma, em.persist (entità) non funziona, e la transazione non funziona.

Un altro punto importante è:

@Transactional("customer1TransactionManager") // !important
public Trade findNewestByJdpModified() {
    //test persist,working right!
    Trade t = new Trade();
    em.persist(t);
    log.info("t.id" + t.getSysTradeId());

    //test transactional, working right!
    int a = 3/0;
}
.

customer1TransactionManager è dalla seconda classe di configurazione DataSource:

@Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
        @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}
.

L'intera seconda classe di configurazione DataSource è:

package com.lichendt.shops.sync;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "customer1EntityManagerFactory", transactionManagerRef = "customer1TransactionManager",
        // 【1】这里写的是DAO层的路径 ,如果你的DAO放在 com.xx.DAO下面,则这里写成 com.xx.DAO
        basePackages = { "com.lichendt.customer1Datasource.dao" })
public class Custom1DBConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "customer1DatasourceProperties")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource")
    public DataSourceProperties customer1DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "customer1DataSource")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource") //
    // 【2】datasource配置的前缀,对应上面 【mysql的yaml配置】
    public DataSource dataSource() {
        // return DataSourceBuilder.create().build();
        return customer1DataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "customer1EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("customer1DataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.lichendt.customer1Datasource.model") // 【3】这里是实体类的包路径
                .persistenceUnit("customer1")
                // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
                // injects an EntityManager.
                // It's generally better to use PersistenceContext unless you really need to
                // manage the EntityManager lifecycle manually.
                // 【4】
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
    }

    @Bean(name = "customer1TransactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}
.

In Apache Derby DB, astenersi dall'uso dei nomi delle tabelle come "utente" o così perché sono prenotate parole chiave su Apache Derby ma funzionerà bene su MySQL.

Nella query, è necessario specificare il nome della classe di entità che si desidera recuperare i dati dalla clausola FROL della query.

List<User> users=session.createQuery("from User").list();
.

Qui, l'utente è il nome della mia classe di entità Java (considera l'involucro del nome come in Java importa.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top