java Hibernate 查询不再存在于表中的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6371987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:38:27  来源:igfitidea点击:

Hibernate querying on fields that do not exist in table anymore

javahibernateormjpa

提问by Noam Nevo

I have an entity that has a many to one mapping to another entity. Here is the mapping:

我有一个实体,它具有到另一个实体的多对一映射。这是映射:

@JoinColumn(name = "user_id", referencedColumnName = "id")
 @ManyToOne 
private User user;

In the object (and table) user I used to have a field called authorityId. I removed that field from the table and the object. Now, when I user find()on the object Hibernate generates a query including the old fields and not including new fields that I have added to the table (and mapped in the object).

在对象(和表)用户中,我曾经有一个名为 authorityId 的字段。我从表和对象中删除了该字段。现在,当我find()在对象上使用 Hibernate 时,会生成一个查询,包括旧字段,但不包括我添加到表中(并映射到对象中)的新字段。

Please note that this does not happen all the time, most of the time the query runs fine but every once and a while I get the exception MySQLSyntaxErrorException: Unknown column.

请注意,这不会一直发生,大多数时候查询运行良好,但每隔一段时间我都会收到异常MySQLSyntaxErrorException: Unknown column

I cannot find a reason for this, any ideas?

我找不到原因,有什么想法吗?

the find I use is the find(Long id)of theJPA: entry = auditLogDAO.find(id);

我使用的 find 是find(Long id)theJPA 的:entry = auditLogDAO.find(id);

The code of the User object:

User对象的代码:

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

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="id",unique=true, nullable=false )
    @GeneratedValue( strategy = IDENTITY )
    private Long id;

    @Column(name ="username",unique=true, nullable=false)
    @Field(index = Index.TOKENIZED, store = Store.NO)
    private String username;

    @Column
    private String password;

    @Column
    private int enabled;

    @OneToOne
    @JoinColumn(name = "current_account", referencedColumnName = "id")
    private Account currentAccount;

    @OneToOne
    @JoinColumn(name = "original_account", referencedColumnName = "id")
    private Account originalAccount;

    @OneToMany
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private List<Authority> authorities;

    @Column(name="first_name")
    @Field(index = Index.TOKENIZED, store = Store.NO)
    private String firstName;

    @Column(name="last_name")
    @Field(index = Index.TOKENIZED, store = Store.NO)
    private String lastName;

    @Column(name="email",unique=true, nullable=false )
    @Field(index = Index.TOKENIZED, store = Store.NO)
    private String email;

    @Column(name="switch_allowed")
    private Boolean switchAllowed;

    @Lob
    @Column(name = "additional_emails")
    private String additionalEmails;

The Authority table:

权限表:

@Entity
@Table(name = "authorities")
public class Authority implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "id")
    @GeneratedValue( strategy = IDENTITY )
    private Long id;

    @Column(name = "user_id")
    private Long userId;

    @Column(name = "authority")
    private String authority;

Full stack trace (if you can see, in the query generated by hibernate there is user6_.authority_id, a column that does not exist anymore in the mapping):

完整的堆栈跟踪(如果你能看到,在 hibernate 生成的查询中有 user6_.authority_id,一个在映射中不再存在的列):

org.springframework.dao.InvalidDataAccessResourceUsageException: could not load an entity: [com.legolas.model.AuditLog#3048]; SQL [select auditlog0_.id as id26_8_, auditlog0_.account_id as account8_26_8_, auditlog0_.date as date26_8_, auditlog0_.domain_object_id as domain3_26_8_, auditlog0_.event_type as event4_26_8_, auditlog0_.notified as notified26_8_, auditlog0_.object_type as object6_26_8_, auditlog0_.object_xml as object7_26_8_, auditlog0_.user_id as user9_26_8_, account1_.id as id7_0_, account1_.account_type as account2_7_0_, account1_.name as name7_0_, account1_1_.adserver_id as adserver3_8_0_, account1_1_.stamping_method as stamping1_8_0_, account1_3_.advertiser_id as advertiser2_30_0_, account1_4_.brand_id as brand2_54_0_, account1_5_.in_use as in1_58_0_, account1_5_.order_by as order2_58_0_, account1_6_.agency_id as agency2_60_0_, case when account1_1_.account_id is not null then 1 when account1_2_.account_id is not null then 2 when account1_3_.account_id is not null then 3 when account1_4_.account_id is not null then 4 when account1_5_.account_id is not null then 5 when account1_6_.account_id is not null then 6 when account1_.id is not null then 0 end as clazz_0_, adserver2_.id as id0_1_, adserver2_.name as name0_1_, case when adserver2_1_.adserver_id is not null then 1 when adserver2_2_.adserver_id is not null then 2 when adserver2_.id is not null then 0 end as clazz_1_, advertiser3_.account_id as id7_2_, advertiser3_1_.account_type as account2_7_2_, advertiser3_1_.name as name7_2_, advertiser3_.agency_id as agency2_60_2_, brand4_.account_id as id7_3_, brand4_1_.account_type as account2_7_3_, brand4_1_.name as name7_3_, brand4_.advertiser_id as advertiser2_30_3_, agency5_.account_id as id7_4_, agency5_1_.account_type as account2_7_4_, agency5_1_.name as name7_4_, user6_.id as id6_5_, user6_.additional_emails as additional2_6_5_, user6_.authority_id as authority10_6_5_, user6_.email as email6_5_, user6_.enabled as enabled6_5_, user6_.first_name as first5_6_5_, user6_.last_name as last6_6_5_, user6_.original_authority as original11_6_5_, user6_.password as password6_5_, user6_.switch_allowed as switch8_6_5_, user6_.username as username6_5_, authority7_.id as id5_6_, authority7_.account_id as account2_5_6_, authority7_.authority as authority5_6_, authority7_.username as username5_6_, authority8_.id as id5_7_, authority8_.account_id as account2_5_7_, authority8_.authority as authority5_7_, authority8_.username as username5_7_ from audit_log auditlog0_ left outer join accounts account1_ on auditlog0_.account_id=account1_.id left outer join publishers account1_1_ on account1_.id=account1_1_.account_id left outer join agencies account1_2_ on account1_.id=account1_2_.account_id left outer join brands account1_3_ on account1_.id=account1_3_.account_id left outer join products account1_4_ on account1_.id=account1_4_.account_id left outer join data_vendors account1_5_ on account1_.id=account1_5_.account_id left outer join advertisers account1_6_ on account1_.id=account1_6_.account_id left outer join adservers adserver2_ on account1_1_.adserver_id=adserver2_.id left outer join ad_server_agency adserver2_1_ on adserver2_.id=adserver2_1_.adserver_id left outer join ad_server_publisher adserver2_2_ on adserver2_.id=adserver2_2_.adserver_id left outer join advertisers advertiser3_ on account1_3_.advertiser_id=advertiser3_.account_id left outer join accounts advertiser3_1_ on advertiser3_.account_id=advertiser3_1_.id left outer join brands brand4_ on account1_4_.brand_id=brand4_.account_id left outer join accounts brand4_1_ on brand4_.account_id=brand4_1_.id left outer join agencies agency5_ on account1_6_.agency_id=agency5_.account_id left outer join accounts agency5_1_ on agency5_.account_id=agency5_1_.id left outer join users user6_ on auditlog0_.user_id=user6_.id left outer join authorities authority7_ on user6_.authority_id=authority7_.id left outer join authorities authority8_ on user6_.original_authority=authority8_.id where auditlog0_.id=?]; nested exception is org.hibernate.exception.SQLGrammarException: could not load an entity: [com.legolas.model.AuditLog#3048] at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:100) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:368) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy317.find(Unknown Source) at com.legolas.notifications.jobs.NotificationJob.asapNotification(NotificationJob.java:133) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273) at org.springframework.scheduling.support.MethodInvokingRunnable.run(MethodInvokingRunnable.java:65) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:51) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:165) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:636) Caused by: org.hibernate.exception.SQLGrammarException: could not load an entity: [com.legolas.model.AuditLog#3048] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.loadEntity(Loader.java:1957) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76) at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3270) at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496) at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477) at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1080) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:997) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:990) at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:554) at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:529) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240) at $Proxy236.find(Unknown Source) at com.legolas.dao.GenericDAOWithJPA.find(GenericDAOWithJPA.java:55) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155) ... 23 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'user6_.authority_id' in 'field list' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:532) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1885) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:93) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1869) at org.hibernate.loader.Loader.doQuery(Loader.java:718) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270) at org.hibernate.loader.Loader.loadEntity(Loader.java:1953) ... 51 more

org.springframework.dao.InvalidDataAccessResourceUsageException:无法加载实体:[com.legolas.model.AuditLog#3048];SQL [选择auditlog0_.id为id26_8_,auditlog0_.account_id为account8_26_8_,auditlog0_.date为date26_8_,auditlog0_.domain_object_id为domain3_26_8_,auditlog0_.event_type为event4_26_8_,auditlog0_.event_type为event4_26_8_,auditlog0_.event_type为event4_26_8_,auditlog0_.account_id为auditlog26_86_86_86_86_6_86_86_86_86_86_86_86_86_806_806_86_86_86_86_86_86_86_86_86_86_86_86_86_06_6_86对象,auditlog0_.user_id如user9_26_8_,account1_.id如id7_0_,account1_.account_type如account2_7_0_,account1_.name如name7_0_,account1_1_​​.adserver_id如adserver3_8_0_,account1_1_​​.stamping_method如stamping1_8_0_,account1_3_.advertiser_id如advertiser2_30_0_,account1_4_.brand_id如brand2_54_0_,account1_5_ .in_use 作为 in1_58_0_, account1_5_。id 其中 auditlog0_.id=?]; 嵌套异常是 org.hibernate.exception.SQLGrammarException: 无法加载实体:[com.legolas.model.AuditLog#3048] at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629) at org. springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:100) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractIfEntityManagerFactoryBean.java:368) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractIfEntityManagerFactoryBean.java:368) at org.springframework.orm.jpa. ChainedPersistenceExceptionTranslator.java:58) 在 org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) 在 org.springframework.dao.support。

采纳答案by joostschouten

I suspect you still have your Authority (authorities table) mapped which has a relationship with your User. This will most likely map to authority_id causing your problem. Either fix the Authority mapping or remove it completely. If this is not the case you will have a classloading problem loading an older version of your model.

我怀疑您仍然映射了与您的用户有关系的权限(权限表)。这很可能会映射到导致您的问题的 authority_id。修复权威映射或完全删除它。如果不是这种情况,您将在加载旧版本模型时遇到类加载问题。

回答by Steve Saporta

I had the same problem: I deleted a column from one of my database tables, changed all the Java/Hibernate code so that it no longer referred to that column, but still got this error at runtime.

我遇到了同样的问题:我从我的一个数据库表中删除了一个列,更改了所有 Java/Hibernate 代码,使其不再引用该列,但在运行时仍然出现此错误。

In my case, the problem had to do with a dependent project. That is, the Java code was in a separate project, on which my main project depended. To make Eclipse and Tomcat acknowledge the changes in the dependent project, I did two things in the main project.

就我而言,问题与依赖项目有关。也就是说,Java 代码位于一个单独的项目中,我的主项目依赖于该项目。为了让Eclipse和Tomcat承认依赖项目的变化,我在主项目中做了两件事。

  1. Properties | Java Build Path | Projects. Remove the dependent project. Close the dialog box. Return to Properties | Java Build Path | Projects and re-add the dependent project.

  2. Properties | Deployment Assembly | Projects. Remove the dependent project. Close the dialog box. Return to Properties | Assembly | Projects and re-add the dependent project.

  1. 属性 | Java 构建路径 | 项目。删除依赖项目。关闭对话框。返回属性 | Java 构建路径 | 项目并重新添加依赖项目。

  2. 属性 | 部署组装 | 项目。删除依赖项目。关闭对话框。返回属性 | 组装 | 项目并重新添加依赖项目。

Then restart the Tomcat server.

然后重启Tomcat服务器。