简体   繁体   English

Spring Hibernate在查询中添加_

[英]Spring Hibernate adding _ in the query

I am havgin a problem creating classes. 我很困难创建类。

Vehiculo (Vechicle) Vehiculo(Vechicle)

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;


/**
 * The persistent class for the vehiculo database table.
 * 
 */
@Entity
@Table(name="vehiculo")
@NamedQuery(name="Vehiculo.findAll", query="SELECT v FROM Vehiculo v")
public class Vehiculo implements Serializable {
    private static final long serialVersionUID = 1L;
    private int idvehiculo;
    private int capacidad;
    private String matricula;
    private int vacante;
    private List<PersonaFisica> personaFisicas;
    private TipoVehiculo tipoVehiculo;

    public Vehiculo() {
    }


    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false, name= "idvehiculo")
    public int getIdvehiculo() {
        return this.idvehiculo;
    }

    public void setIdvehiculo(int idvehiculo) {
        this.idvehiculo = idvehiculo;
    }


    @Column(nullable=false)
    public int getCapacidad() {
        return this.capacidad;
    }

    public void setCapacidad(int capacidad) {
        this.capacidad = capacidad;
    }


    @Column(length=12)
    public String getMatricula() {
        return this.matricula;
    }

    public void setMatricula(String matricula) {
        this.matricula = matricula;
    }


    @Column(nullable=false)
    public int getVacante() {
        return this.vacante;
    }

    public void setVacante(int vacante) {
        this.vacante = vacante;
    }


    //bi-directional many-to-one association to PersonaFisica
    @OneToMany(mappedBy="vehiculo")
    public List<PersonaFisica> getPersonaFisicas() {
        return this.personaFisicas;
    }

    public void setPersonaFisicas(List<PersonaFisica> personaFisicas) {
        this.personaFisicas = personaFisicas;
    }

    public PersonaFisica addPersonaFisica(PersonaFisica personaFisica) {
        getPersonaFisicas().add(personaFisica);
        personaFisica.setVehiculo(this);

        return personaFisica;
    }

    public PersonaFisica removePersonaFisica(PersonaFisica personaFisica) {
        getPersonaFisicas().remove(personaFisica);
        personaFisica.setVehiculo(null);

        return personaFisica;
    }


    //bi-directional many-to-one association to TipoVehiculo
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="tipo_vehiculo_idTipoVehiculo", nullable=false, referencedColumnName="idTipoVehiculo")
    public TipoVehiculo getTipoVehiculo() {
        return this.tipoVehiculo;
    }

    public void setTipoVehiculo(TipoVehiculo tipoVehiculo) {
        this.tipoVehiculo = tipoVehiculo;
    }

}

VehicleType 车辆类型

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;


/**
 * The persistent class for the tipo_vehiculo database table.
 * 
 */
@Entity
@Table(name="tipo_vehiculo")
@NamedQuery(name="TipoVehiculo.findAll", query="SELECT t FROM TipoVehiculo t")
public class TipoVehiculo implements Serializable {
    private static final long serialVersionUID = 1L;
    private int idTipoVehiculo;
    private String codigo;
    private String descripcion;
    private List<Vehiculo> vehiculos;

    public TipoVehiculo() {
    }


    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(unique=true, nullable=false,name="idTipoVehiculo")
    public int getIdTipoVehiculo() {
        return this.idTipoVehiculo;
    }

    public void setIdTipoVehiculo(int idTipoVehiculo) {
        this.idTipoVehiculo = idTipoVehiculo;
    }


    @Column(nullable=false, length=20)
    public String getCodigo() {
        return this.codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }


    @Column(length=140)
    public String getDescripcion() {
        return this.descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }


    //bi-directional many-to-one association to Vehiculo
    @OneToMany(mappedBy="tipoVehiculo")
    public List<Vehiculo> getVehiculos() {
        return this.vehiculos;
    }

    public void setVehiculos(List<Vehiculo> vehiculos) {
        this.vehiculos = vehiculos;
    }

    public Vehiculo addVehiculo(Vehiculo vehiculo) {
        getVehiculos().add(vehiculo);
        vehiculo.setTipoVehiculo(this);

        return vehiculo;
    }

    public Vehiculo removeVehiculo(Vehiculo vehiculo) {
        getVehiculos().remove(vehiculo);
        vehiculo.setTipoVehiculo(null);

        return vehiculo;
    }

}

The problem is, when hibernate tries to do the query, it does: 问题是,当hibernate尝试执行查询时,它会:

select vehiculo0_.idvehiculo as idvehicu1_25_, vehiculo0_.capacidad as capacida2_25_, 
        vehiculo0_.matricula as matricul3_25_, vehiculo0_.tipo_vehiculo_id_tipo_vehiculo as tipo_veh5_25_, 
        vehiculo0_.vacante as vacante4_25_ 
 from vehiculo vehiculo0_

as you can see, the atribute is called: tipo_vehiculo_idTipoVehiculo, but in the query it keeps adding "_" looking like this: tipo_vehiculo_id_tipo_vehiculo .... 正如你所看到的,atribute被称为:tipo_vehiculo_idTipoVehiculo,但在查询中它不断添加“_”,如下所示:tipo_vehiculo_id_tipo_vehiculo ....

Looking in internet i have seen that i can use a new NamingStrategy to avoid this situation, the class i have found is this: 在互联网上看,我已经看到我可以使用新的NamingStrategy来避免这种情况,我发现的类是这样的:

package net.petrikainulainen.hibernate.util;
import org.hibernate.cfg.ImprovedNamingStrategy;

/**
 * A custom naming strategy implementation which uses following naming conventions:
 * <ul>
 *     <li>Table names are lower case and in plural form. Words are separated with '_' character.</li>
 *     <li>Column names are lower case and words are separated with '_' character.</li>
 * </ul>
 * @author Petri Kainulainen
 */
public class CustomNamingStrategy extends ImprovedNamingStrategy {

    private static final String PLURAL_SUFFIX = "s";

    /**
     * Transforms class names to table names by using the described naming conventions.
     * @param className
     * @return  The constructed table name.
     */
    @Override
    public String classToTableName(String className) {
        String tableNameInSingularForm = super.classToTableName(className);
        return transformToPluralForm(tableNameInSingularForm);
    }

    private String transformToPluralForm(String tableNameInSingularForm) {
        StringBuilder pluralForm = new StringBuilder();

        pluralForm.append(tableNameInSingularForm);
        pluralForm.append(PLURAL_SUFFIX);

        return pluralForm.toString();
    }
}

But i dont see anywhere about the "_" .. i have also tried addind the next code, to see if it works, but nothing yet. 但我没有看到关于“_”的任何地方..我也试过addind下一个代码,看它是否有效,但还没有。

      @Override
        public String propertyToColumnName(String propertyName) {
            // TODO Auto-generated method stub
            return propertyName;
        }

         @Override
        public String columnName(String columnName) {
            // TODO Auto-generated method stub
            return columnName;
        }

I am using HIbernate+JPA, Spring with an application.yml that looks like this: and all the possible types of org.hibernate.dialect, but no results 我正在使用HIbernate + JPA,Spring和一个看起来像这样的application.yml:以及所有可能的org.hibernate.dialect类型,但没有结果

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/gotowork_db?useSSL=false
    username: root
    password: root
  jpa:
    show-sql: true
    hibernate:
      naming:
        strategy: es.gfi.CustomNamingStrategy
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQLDialect

Is there a way to avoid the camelCap changing to "_" ???... and not having to change the DB column names? 有没有办法避免camelCap更改为“_”???并且不必更改DB列名称?

Thanks 谢谢

Try this piece of code where in as per your requirement you can do a logical check and replace column name text accordingly. 尝试这段代码,根据您的要求,您可以进行逻辑检查并相应地替换列名文本。

public class Temp extends ImprovedNamingStrategy {

    @Override
    public String columnName(String columnName) {
        if(columnName.contains("id_tipo_vehiculo")){
            String replacedString = columnName.replace("id_tipo_vehiculo", "idTipoVehiculo");
            return replacedString;
        }else{
            return columnName; 
        }
    }

}

Just found the problem after hours of testing the thing is that the naming strategy used, changes all the capital letters for a "_"+lowercase when creating the query. 刚刚发现问题经过几个小时的测试后,使用的命名策略在创建查询时将所有大写字母更改为“_”+小写。

As you can see in the code in the question in the 正如您在问题中的代码中所看到的那样

//bi-directional many-to-one association to TipoVehiculo
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="tipo_vehiculo_idTipoVehiculo", nullable=false, referencedColumnName="idTipoVehiculo")
    public TipoVehiculo getTipoVehiculo() {
        return this.tipoVehiculo;
    }

it does: tipo_vehiculo_id_tipo_vehiculo, making the query look like: 它确实:tipo_vehiculo_id_tipo_vehiculo,使查询看起来像:

SELECT 
    vehiculo0_.idvehiculo AS idvehicu1_25_,
    vehiculo0_.capacidad AS capacida2_25_,
    vehiculo0_.matricula AS matricul3_25_,
    vehiculo0_.tipo_vehiculo_id_tipo_vehiculo AS tipo_veh5_25_,
    vehiculo0_.vacante AS vacante4_25_
FROM
    vehiculo vehiculo0_

so i have changed to this way: 所以我改变了这种方式:

//bi-directional many-to-one association to TipoVehiculo
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="tipo_vehiculo_idtipovehiculo", nullable=false)
    public TipoVehiculo getTipoVehiculo() {
        return this.tipoVehiculo;
    }

As you can see in the name i removed all the Uppercases for lower, and since MySQL is not case sensitive its the same thing, even though in the table all its attributes use capital letters in it. 正如您在名称中所看到的,我删除了所有较低的大写字母,并且由于MySQL不区分大小写,所以即使在表中它的所有属性都使用大写字母。 This happens in all the clases where the name in the @joincolumn. 这种情况发生在@joincolumn中名称的所有分支中。 Making hibernate create the correct query so it can by executed correctly: 使hibernate创建正确的查询,以便正确执行:

SELECT 
    vehiculo0_.idvehiculo AS idvehicu1_25_,
    vehiculo0_.capacidad AS capacida2_25_,
    vehiculo0_.matricula AS matricul3_25_,
    vehiculo0_.tipo_vehiculo_idtipovehiculo AS tipo_veh5_25_,
    vehiculo0_.vacante AS vacante4_25_
FROM
    vehiculo vehiculo0_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM