更改Naturald参数名称后出错

时间:2018-05-08 07:03:35

标签: java database hibernate rename liquibase

我已使用liquibase更改了NaturalId列名(从“name”更改为“query_name”):

<changeSet id="rename_name_to_query_name">
    <preConditions onFail="CONTINUE">
        <columnExists tableName="pm_dbqueries" columnName="name" />
        <not>
            <columnExists tableName="pm_dbqueries" columnName="query_name" />
        </not>
    </preConditions>
    <renameColumn
        columnDataType="varchar(40)"
        newColumnName="query_name"
        oldColumnName="name"
        tableName="pm_dbqueries"/>
</changeSet>

它工作正常,名称已更改...我还在java中更新了我的Entity类:

@Entity
@Table( name = "pm_dbqueries", uniqueConstraints = { @UniqueConstraint(columnNames = "id"),
                                                      @UniqueConstraint(columnNames = "query_name") } )
@SequenceGenerator( name = "pm_dbqueries_seq", sequenceName = "pm_dbqueries_seq" )
public class DBQuery
{   
    @Id
    @GeneratedValue( strategy = GenerationType.AUTO, generator = "pm_dbqueries_seq" )
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @NaturalId
    @Column(name = "query_name", unique = true, nullable = false, length = 40)
    private String queryName;

    @Column(name = "query", unique = false, nullable = false, length = 4000)
    private String query;

    public Long getId()
    {
        return id;
    }

    public void setId( Long id )
    {
        this.id = id;
    }

    public String getQueryName()
    {
        return queryName;
    }

    public void setQueryName( String queryName )
    {
        this.queryName = queryName;
    }

    public String getQuery()
    {
        return query;
    }

    public void setQuery( String query )
    {
        this.query = query;
    }
}

但事情是......当我试图执行此操作时:

return (DBQuery) sessionFactory.getCurrentSession().byNaturalId(DBQuery.class).using( "query_name", name ).load();

出现错误:

org.hibernate.HibernateException: No value specified for natural-id property XXX.DBQuery#queryName
    at org.hibernate.event.spi.ResolveNaturalIdEvent.<init>(ResolveNaturalIdEvent.java:102)
    at org.hibernate.event.spi.ResolveNaturalIdEvent.<init>(ResolveNaturalIdEvent.java:52)
    at org.hibernate.internal.SessionImpl$BaseNaturalIdLoadAccessImpl.resolveNaturalId(SessionImpl.java:2466)
    at org.hibernate.internal.SessionImpl$NaturalIdLoadAccessImpl.load(SessionImpl.java:2581)

在这些变化之前它运作良好。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

尝试此操作,因为您需要在此处使用属性名称而非列名称。它之前工作得很早,因为两者之间没有区别(name == name)。

return (DBQuery) sessionFactory.getCurrentSession().byNaturalId(DBQuery.class).using( "queryName", name ).load();