Hibernate为MySQL生成错误的内部联接查询

时间:2022-08-22 15:39:53

I'm developing my first project with JPA, with MySQL as my database and Hibernate 4.3.8 as my JPA provider in a Spring 4 web project.

我正在用JPA开发我的第一个项目,MySQL是我的数据库,Hibernate 4.3.8是我在Spring 4 web项目中的JPA提供者。

In my Spring config, I set the database and the dialect:

在我的Spring配置中,我设置了数据库和方言:

HibernateJpaVendorAdapter hjpaVA = new HibernateJpaVendorAdapter();
hjpaVA.setDatabase(Database.MYSQL);
hjpaVA.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");

I try to get this query that gives me trouble:

我试图让这个问题给我带来麻烦:

TypedQuery<KundeDTO> query = entityManager.createQuery("select new zdb.dto.KundeDTO(k.id, k.firma.firmenname, k.regnr, k.kategorie) 
from Kunde k where k.id = :id", KundeDTO.class);

This is the SQL that Hibernate generates:

这是Hibernate生成的SQL:

select kunde0_.`id` as col_0_0_, firma1_.`firmenname` as col_1_0_, kunde0_.`regnr` as col_2_0_, kunde0_.id_kategorie as col_3_0_ 
from `zdb_e`.`Kunde` kunde0_, `zdb_e`.`Firma` firma1_ 
inner join `zdb_e`.`Kategorie` kategorie2_ on kunde0_.id_kategorie=kategorie2_.`id` 
where kunde0_.id_firma=firma1_.`id` and kunde0_.`id`=1;

Note that there are no parentheses on the inner join!

请注意,内连接上没有括号!

Running this statement results in the following error:

运行此语句会导致以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
Unknown column 'kunde0_.id_kategorie' in 'on clause'

The reason for the exception is detailed here: mysql-unknown-column-in-on-clause

此处详细说明了异常的原因:mysql-unknown-column-in-on-clause

When I add the parentheses to the where and the inner join clauses and run the statement directly against the database it works:

当我将括号添加到where和内部连接子句并直接对数据库运行语句时,它可以工作:

select kunde0_.`id` as col_0_0_, firma1_.`firmenname` as col_1_0_, kunde0_.`regnr` as col_2_0_, kunde0_.id_kategorie as col_3_0_ 
from (`zdb_e`.`Kunde` kunde0_, `zdb_e`.`Firma` firma1_ )
inner join `zdb_e`.`Kategorie` kategorie2_ on 
( kunde0_.id_kategorie=kategorie2_.`id` ) 
where kunde0_.id_firma=firma1_.`id` and kunde0_.`id`=1;

So, how can I persuade Hibernate to generate the query like that?

那么,我如何说服Hibernate生成这样的查询呢?

update: here are the entities

更新:这是实体

Kunde

@Entity
public class Kunde implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;

    private Integer regnr;

    @OneToOne(optional=false)
    @JoinColumn(name="id_firma", nullable = false)
    private Firma firma;

    @OneToOne(optional=false)
    @JoinColumn(name="id_kategorie", nullable = false)
    private Kategorie kategorie;

    @OneToOne(optional=false)
    @JoinColumn(name="id_lieferregion", nullable = false)
    private Lieferregion lieferregion;

    // getters and setters....
}

Firma

@Entity
@Table(name = "Firma")
public class Firma implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Integer id;

    @Column(name="firmenname")
    private String firmenname;
    @Column(name="uid")
    private String uid;

    @OneToOne(optional=false)
    @JoinColumn(name="id_anschrift", nullable = false)
    private Anschrift anschrift;

    @OneToMany(mappedBy="id_firma", fetch=FetchType.EAGER)
    private List<Person> personen;

    public Firma() {
        personen = new ArrayList<Person>();
    }
    // getters and setters....
}

Kategorie

@Entity
public class Kategorie implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;

    private Integer nummer;
    private String bezeichnung;

    public Kategorie() {
    }

    public Kategorie(int kategorieId, int kategorieNummer, String kategorieBezeichnung) {
        this.id = kategorieId;
        this.nummer = kategorieNummer;
        this.bezeichnung = kategorieBezeichnung;
    }
    // getters and setters....
}

DB schemas

CREATE TABLE kategorie 
    (id INTEGER NOT NULL AUTO_INCREMENT, 
    nummer INTEGER NOT NULL, 
    bezeichnung VARCHAR(100) NOT NULL,
    PRIMARY KEY (id),        
    UNIQUE (nummer, bezeichnung)
    );

CREATE TABLE firma
    (ID INTEGER NOT NULL AUTO_INCREMENT, 
    firmenname VARCHAR(50) NOT NULL,
    uid VARCHAR(20) NOT NULL,
    url VARCHAR(100) NOT NULL,
    id_anschrift INTEGER NOT NULL,
    id_logo INTEGER,
    PRIMARY KEY (id),
    UNIQUE (uid),
    UNIQUE (firmenname),
    UNIQUE (id_anschrift),
    CONSTRAINT firma_fk1 FOREIGN KEY (id_anschrift) REFERENCES ANSCHRIFT (ID),
    CONSTRAINT firma_fk2 FOREIGN KEY (id_logo) REFERENCES logo (ID));

CREATE TABLE kunde 
    (id INTEGER NOT NULL AUTO_INCREMENT, 
    regnr INTEGER NOT NULL,
    id_kategorie INTEGER NOT NULL,
    id_firma INTEGER NOT NULL,
    id_benutzer INTEGER,
    id_lieferregion INTEGER NOT NULL,
    PRIMARY KEY (id), 
    UNIQUE (regnr, id_kategorie),
    UNIQUE (id_firma),
    UNIQUE (id_benutzer),
    CONSTRAINT kunde_fk1 FOREIGN KEY (id_firma) REFERENCES firma (id),
    CONSTRAINT kunde_fk2 FOREIGN KEY (id_benutzer) REFERENCES benutzer (id),
    CONSTRAINT kunde_fk3 FOREIGN KEY (id_kategorie) REFERENCES kategorie (id),
    CONSTRAINT kunde_fk4 FOREIGN KEY (id_lieferregion) REFERENCES lieferregion (id)
    );

upon further testing

经过进一步测试

The problem are the missing parentheses on the from clause.

问题是from子句中缺少括号。

Going directly against the db:

直接针对db:

select k.id, k.regnr, f.firmenname from (Kunde k, Firma f) JOIN kategorie kat on k.id_kategorie = kat.id where k.id = 1 and k.id_firma = f.id;

works!

select k.id, k.regnr, f.firmenname from Kunde k, Firma f JOIN kategorie kat on k.id_kategorie = kat.id where k.id = 1 and k.id_firma = f.id;

Doesn't work: Unknown column 'k.id_kategorie' in 'on clause'

不起作用:'on子句'中的未知列'k.id_kategorie'

Why do I even need the parentheses on the from clause?
And how can I make Hibernate put them in?

为什么我甚至需要from子句的括号?我怎样才能让Hibernate把它们放进去?

1 个解决方案

#1


I didn't get it to work with JPQL, so I did as jgr suggested in the comments and wrote my own sql native query:

我没有让它与JPQL一起工作,所以我在评论中建议jgr,并编写了我自己的sql本机查询:

String sql = "select k.id, f.firmenname, k.regnr, kat.id, kat.nummer, kat.bezeichnung from (zdb_e.Kunde k, zdb_e.Firma f) JOIN zdb_e.kategorie kat on k.id_kategorie = kat.id where k.id = :id and k.id_firma = f.id;";
Query query =  entityManager.createNativeQuery(sql, schemaName), "KundenListeRow");
query.setParameter("id", id);
return (KundeDTO) query.getSingleResult();

For the mapping into my Pojo KundeDTO I added @SqlResultSetMapping to the Kunde Entity:

为了映射到我的Pojo KundeDTO,我将@SqlResultSetMapping添加到了Kunde Entity:

@Entity
@SqlResultSetMapping(name = "KundenListeRow",
classes = {
    @ConstructorResult(targetClass = KundeDTO.class,
            columns = {
                    @ColumnResult(name = "id"),
                    @ColumnResult(name = "firmenname"),
                    @ColumnResult(name = "regnr"),
                    @ColumnResult(name = "kat.id"),
                    @ColumnResult(name = "kat.nummer"),
                    @ColumnResult(name = "kat.bezeichnung")
                    }
            )
  })
public class Kunde implements Serializable {
     ....
}

And the corresponding constructor in the DTO:

和DTO中相应的构造函数:

public class KundeDTO {
    int id;
    String firmenname;
    Kategorie k;
    int regnr;

    public KundeDTO(int id, String firmenname, int regnr, int kategorieId, int kategorieNummer, String kategorieBezeichnung) {
        this.id = id;
        this.firmenname = firmenname;
        this.regnr = regnr;
        this.k = new Kategorie(kategorieId, kategorieNummer, kategorieBezeichnung);
    }
    public KundeDTO() {
    }
}

As I said, it works. But it is not ideal. With JPQL I could use a TypedQuery and not have to deal with the resultSetMapping.

正如我所说,它有效。不过这是不理想的。使用JPQL我可以使用TypedQuery而不必处理resultSetMapping。

Of course, I still don't know why my JPQL doesn't work. :-)

当然,我仍然不知道为什么我的JPQL不起作用。 :-)

#1


I didn't get it to work with JPQL, so I did as jgr suggested in the comments and wrote my own sql native query:

我没有让它与JPQL一起工作,所以我在评论中建议jgr,并编写了我自己的sql本机查询:

String sql = "select k.id, f.firmenname, k.regnr, kat.id, kat.nummer, kat.bezeichnung from (zdb_e.Kunde k, zdb_e.Firma f) JOIN zdb_e.kategorie kat on k.id_kategorie = kat.id where k.id = :id and k.id_firma = f.id;";
Query query =  entityManager.createNativeQuery(sql, schemaName), "KundenListeRow");
query.setParameter("id", id);
return (KundeDTO) query.getSingleResult();

For the mapping into my Pojo KundeDTO I added @SqlResultSetMapping to the Kunde Entity:

为了映射到我的Pojo KundeDTO,我将@SqlResultSetMapping添加到了Kunde Entity:

@Entity
@SqlResultSetMapping(name = "KundenListeRow",
classes = {
    @ConstructorResult(targetClass = KundeDTO.class,
            columns = {
                    @ColumnResult(name = "id"),
                    @ColumnResult(name = "firmenname"),
                    @ColumnResult(name = "regnr"),
                    @ColumnResult(name = "kat.id"),
                    @ColumnResult(name = "kat.nummer"),
                    @ColumnResult(name = "kat.bezeichnung")
                    }
            )
  })
public class Kunde implements Serializable {
     ....
}

And the corresponding constructor in the DTO:

和DTO中相应的构造函数:

public class KundeDTO {
    int id;
    String firmenname;
    Kategorie k;
    int regnr;

    public KundeDTO(int id, String firmenname, int regnr, int kategorieId, int kategorieNummer, String kategorieBezeichnung) {
        this.id = id;
        this.firmenname = firmenname;
        this.regnr = regnr;
        this.k = new Kategorie(kategorieId, kategorieNummer, kategorieBezeichnung);
    }
    public KundeDTO() {
    }
}

As I said, it works. But it is not ideal. With JPQL I could use a TypedQuery and not have to deal with the resultSetMapping.

正如我所说,它有效。不过这是不理想的。使用JPQL我可以使用TypedQuery而不必处理resultSetMapping。

Of course, I still don't know why my JPQL doesn't work. :-)

当然,我仍然不知道为什么我的JPQL不起作用。 :-)