Hibernate5生成的映射文件导致findByExample无法正确查询到结果

工作环境:SpringMvc(4.3.5.release)+Hibernate(5.2.6.final)+SQL Server 2008 r2

构建工具:Maven


问题描述:

在使用Hibernate生成的Dao中的findByExample方法无法查询到任何值。


这是数据库的表格:

 这是生成的实体类:

package com.aocshallo.orm;
// Generated 2017-1-16 16:30:18 by Hibernate Tools 5.2.0.CR1

import java.io.Serializable;

/**
 * CompanyInfo generated by hbm2java
 */
public class CompanyInfo implements java.io.Serializable {

    private Integer id;
    /**
     * 单位名称
     */
    private Serializable name;
    /**
     * 单位代码
     */
    private Serializable code;

    public CompanyInfo() {
    }

    public CompanyInfo(Serializable name, Serializable code) {
        this.name = name;
        this.code = code;
    }

    public Integer getId() {
        return this.id;
    }

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

    public Serializable getName() {
        return this.name;
    }

    public void setName(Serializable name) {
        this.name = name;
    }

    public Serializable getCode() {
        return this.code;
    }

    public void setCode(Serializable code) {
        this.code = code;
    }

}

除了注释,其它都是自动生成的。可以看到属性默认生成的类型都是Serializable。

下面是对应的hbm.xml文件内容。

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 2017-1-16 16:30:18 by Hibernate Tools 5.2.0.CR1 -->
<hibernate-mapping>
    <class name="com.aocshallo.orm.CompanyInfo" table="CompanyInfo" schema="dbo" catalog="SignWebData" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="Id" />
            <generator class="identity" />
        </id>
        <property name="name" type="serializable">
            <column name="Name" not-null="true" />
        </property>
        <property name="code" type="serializable">
            <column name="Code" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

结果就是使用findByPoperty 没有结果。

package com.aocshallo.orm;

public class CompanyDao extends CompanyInfoHome implements ICompanyDao {

    @Override
    public CompanyInfo findByName(String name) {
        CompanyInfo ci = new CompanyInfo();
        ci.setName(name);
        
        return super.findByExample(ci).get(0);
    }

}

经过测试,将POJO中的Serializable 替换成实际的类型,再将hbm.xml中的对应字段更改成正确的字段,就可以正常查询到结果。

原文地址:https://www.cnblogs.com/aocshallo/p/6322568.html