JPA将字段映射到对象而不在DB中创建表

时间:2013-04-03 13:55:24

标签: hibernate jpa mapping native-sql

我正在使用JPA,JSF,Spring。

我有时会使用我必须使用的本机SQL。它们通常与其他表连接。我不想为此目的在DB中创建表,我不想将字段映射到我自己的对象。因此,对于此JPA具有和ResultSetMapping,但您已使用Entity和Entity在DB中创建表。

如何使用JPA将字段映射到我的没有crating表(没有实体)的对象或者DB中的任何内容?

这是一个简单的临时代码。

由于

import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.Id;
import javax.persistence.SqlResultSetMapping;

@SqlResultSetMapping(
        name="CustomerResultSetMapping",
        entities = @EntityResult(
                entityClass = Customer.class,
                fields = {
                    @FieldResult( name ="LONG_ID"           ,   column ="LONG_ID"               ),
                    @FieldResult( name ="STRING_NAME"       ,   column ="STRING_NAME"           ),
                    @FieldResult( name ="STRING_ADDRESS"    ,   column ="STRING_ADDRESS"        ),
                    @FieldResult( name ="BIGDECIMAL_PRICE"  ,   column ="BIGDECIMAL_PRICE"      ),
                    @FieldResult( name ="INT_AGE"           ,   column ="INT_AGE"               )
                }
        )
)

@Entity
public class Customer  {

    @Id         Long LONG_ID                ;
    @Column     String STRING_NAME          = "";
    @Column     BigDecimal BIGDECIMAL_PRICE = BigDecimal.ZERO;
    @Column     Integer INT_AGE             = 0;

    /////// getters and setters



}

Dao使用Native Oracle SQL获取数据

public List getCustomerAddress(Long customerId)  {
    try {

        String sql = "" +
                " SELECT LONG_ID," +
                "        STRING_NAME," +
                "        A.ADDRESS AS STRING_ADDRESS," +
                "        INT_AGE," +
                "         (  PRICE * NUM_TIME * (CASE WHEN NUM_TIME = 0 THEN 1 WHEN NUM_TIME IS NULL THEN 1 ELSE NUM_TIME END))  AS BIGDECIMAL_PRICE" +
                "   FROM T_CUSTOMER C, T_ADDRESS A" +
                "   WHERE C.ADDRESS_ID = A.ID AND C.ID = :CUSTOMER_ID" +
                " ";
        Query query = entityManager.createNativeQuery(sql,"CustomerResultSetMapping");
        query.setParameter("CUSTOMER_ID", customerId);
        List resultList = query.getResultList();
        return resultList;

    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

3 个答案:

答案 0 :(得分:1)

这是我的工作解决方案。

Integer,Float,Long,...必须是BigDecimal

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.transform.Transformers;

public class PojoCustomer  {

    BigDecimal  LONG_ID          ; // Long          LONG_ID             = 0L  ;
    String      STRING_NAME      ; // String        STRING_NAME         = "";
    BigDecimal  BIGDECIMAL_PRICE ; // BigDecimal    BIGDECIMAL_PRICE    = BigDecimal.ZERO;
    BigDecimal  INT_AGE          ; // Integer       INT_AGE             = 0;

    /////// getters and setters


}

DAO使用Native Oracle SQL获取数据

public List getCustomerAddress(Long customerId)  {
    try {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append(" SELECT LONG_ID, ");
        sqlBuilder.append("        STRING_NAME, ");
        sqlBuilder.append("        A.ADDRESS AS STRING_ADDRESS, ");
        sqlBuilder.append("        INT_AGE, ");
        sqlBuilder.append("         (  PRICE * NUM_TIME * (CASE WHEN NUM_TIME = 0 THEN 1 WHEN NUM_TIME IS NULL THEN 1 ELSE NUM_TIME END))  AS BIGDECIMAL_PRICE ");
        sqlBuilder.append("   FROM T_CUSTOMER C, T_ADDRESS A ");
        sqlBuilder.append("   WHERE C.ADDRESS_ID = A.ID AND C.ID = :CUSTOMER_ID ");

        SQLQuery createSQLQuery = getNewSession().createSQLQuery(sqlBuilder.toString());
        createSQLQuery.setParameter("CUSTOMER_ID", customerId);

        createSQLQuery.addScalar("LONG_ID");
        createSQLQuery.addScalar("STRING_NAME");
        createSQLQuery.addScalar("BIGDECIMAL_PRICE");
        createSQLQuery.addScalar("INT_AGE");

        ResultTransformer aliasToBean = Transformers.aliasToBean(PojoCustomer.class);
        List resultWithAliasedBean = createSQLQuery.setResultTransformer(aliasToBean).list();

        return resultWithAliasedBean;

    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

答案 1 :(得分:1)

你可以尝试

Query query = entityManager.createQuery("SELECT NEW PojoCustomer(c.LONG_ID, c.STRING_NAME, C.INT_AGE) from T_CUSTOMER c");

然后

query.getResultList();

应返回List

当然,您需要为类PojoCustomer创建适当的构造函数。

答案 2 :(得分:-1)

module.exports = {

"server": {
    "protocol"      : "https",
    "host"          : "localhost:5000"
    },

'jawbone' : {
    'key'           : '6f**********', 
    'secret'        : '9b918*********************',
    'callback'      : '/sleeps',
    'scope'         : ['basic_read','extended_read','move_read','sleep_read']
    }

};

休眠:

package ferro.model;

import java.math.BigDecimal;

import javax.persistence.Entity;
import javax.persistence.Id;


@Entity
public class Venclipro implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String registro;
    private String ord_Ped;
    private int prod_Dscto_Remate;
    private String cod_Vta;
    private int item;
    private String prodCon;
    private String anio;
    private String mes;
    private String cat;
    private String descripcion;
    private String subc;
    private String subDescripcion;
    private String producto;
    private String marca;
    private String prod_Descripcion;
    private String vendedor;
    private String cd_Vdr;
    private String cliente;
    private String nombre_Cli;
    private String tdoc;
    private String serie;
    private String nroDoc;
    private BigDecimal tc_Venta;
    private BigDecimal tc_Inv;
    private String cond_Pago;
    private String cod_Mon;
    private String moneda;
    private BigDecimal vta_Unid;
    private BigDecimal vta_Neta;
    private BigDecimal dscto;
    private BigDecimal total_Cprom;
    private BigDecimal vta_Sin_Dscto;
    private String factura;

    public Venclipro() {

    }

    public Venclipro(String registro, String ord_Ped, int prod_Dscto_Remate,
            String cod_Vta, int item, String prodCon, String anio, String mes,
            String cat, String descripcion, String subc, String subDescripcion,
            String producto, String marca, String prod_Descripcion,
            String vendedor, String cd_Vdr, String cliente, String nombre_Cli,
            String tdoc, String serie, String nroDoc, BigDecimal tc_Venta,
            BigDecimal tc_Inv, String cond_Pago, String cod_Mon, String moneda,
            BigDecimal vta_Unid, BigDecimal vta_Neta, BigDecimal dscto,
            BigDecimal total_Cprom, BigDecimal vta_Sin_Dscto, String factura) {
        this.registro = registro;
        this.ord_Ped = ord_Ped;
        this.prod_Dscto_Remate = prod_Dscto_Remate;
        this.cod_Vta = cod_Vta;
        this.item = item;
        this.prodCon = prodCon;
        this.anio = anio;
        this.mes = mes;
        this.cat = cat;
        this.descripcion = descripcion;
        this.subc = subc;
        this.subDescripcion = subDescripcion;
        this.producto = producto;
        this.marca = marca;
        this.prod_Descripcion = prod_Descripcion;
        this.vendedor = vendedor;
        this.cd_Vdr = cd_Vdr;
        this.cliente = cliente;
        this.nombre_Cli = nombre_Cli;
        this.tdoc = tdoc;
        this.serie = serie;
        this.nroDoc = nroDoc;
        this.tc_Venta = tc_Venta;
        this.tc_Inv = tc_Inv;
        this.cond_Pago = cond_Pago;
        this.cod_Mon = cod_Mon;
        this.moneda = moneda;
        this.vta_Unid = vta_Unid;
        this.vta_Neta = vta_Neta;
        this.dscto = dscto;
        this.total_Cprom = total_Cprom;
        this.vta_Sin_Dscto = vta_Sin_Dscto;
        this.factura = factura;
    }

    @Id
    public String getRegistro() {
        return registro;
    }

    public void setRegistro(String registro) {
        this.registro = registro;
    }

    public String getOrd_Ped() {
        return ord_Ped;
    }

    public void setOrd_Ped(String ord_Ped) {
        this.ord_Ped = ord_Ped;
    }

    public int getProd_Dscto_Remate() {
        return prod_Dscto_Remate;
    }

    public void setProd_Dscto_Remate(int prod_Dscto_Remate) {
        this.prod_Dscto_Remate = prod_Dscto_Remate;
    }

    @Id
    public String getCod_Vta() {
        return cod_Vta;
    }

    public void setCod_Vta(String cod_Vta) {
        this.cod_Vta = cod_Vta;
    }

    public int getItem() {
        return item;
    }

    public void setItem(int item) {
        this.item = item;
    }

    public String getProdCon() {
        return prodCon;
    }

    public void setProdCon(String prodCon) {
        this.prodCon = prodCon;
    }

    public String getAnio() {
        return anio;
    }

    public void setAnio(String anio) {
        this.anio = anio;
    }

    public String getMes() {
        return mes;
    }

    public void setMes(String mes) {
        this.mes = mes;
    }

    public String getCat() {
        return cat;
    }

    public void setCat(String cat) {
        this.cat = cat;
    }

    public String getDescripcion() {
        return descripcion;
    }

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

    public String getSubc() {
        return subc;
    }

    public void setSubc(String subc) {
        this.subc = subc;
    }

    public String getSubDescripcion() {
        return subDescripcion;
    }

    public void setSubDescripcion(String subDescripcion) {
        this.subDescripcion = subDescripcion;
    }

    public String getProducto() {
        return producto;
    }

    public void setProducto(String producto) {
        this.producto = producto;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getProd_Descripcion() {
        return prod_Descripcion;
    }

    public void setProd_Descripcion(String prod_Descripcion) {
        this.prod_Descripcion = prod_Descripcion;
    }

    public String getVendedor() {
        return vendedor;
    }

    public void setVendedor(String vendedor) {
        this.vendedor = vendedor;
    }

    public String getCd_Vdr() {
        return cd_Vdr;
    }

    public void setCd_Vdr(String cd_Vdr) {
        this.cd_Vdr = cd_Vdr;
    }

    public String getCliente() {
        return cliente;
    }

    public void setCliente(String cliente) {
        this.cliente = cliente;
    }

    public String getNombre_Cli() {
        return nombre_Cli;
    }

    public void setNombre_Cli(String nombre_Cli) {
        this.nombre_Cli = nombre_Cli;
    }

    public String getTdoc() {
        return tdoc;
    }

    public void setTdoc(String tdoc) {
        this.tdoc = tdoc;
    }

    public String getSerie() {
        return serie;
    }

    public void setSerie(String serie) {
        this.serie = serie;
    }

    public String getNroDoc() {
        return nroDoc;
    }

    public void setNroDoc(String nroDoc) {
        this.nroDoc = nroDoc;
    }

    public BigDecimal getTc_Venta() {
        return tc_Venta;
    }

    public void setTc_Venta(BigDecimal tc_Venta) {
        this.tc_Venta = tc_Venta;
    }

    public BigDecimal getTc_Inv() {
        return tc_Inv;
    }

    public void setTc_Inv(BigDecimal tc_Inv) {
        this.tc_Inv = tc_Inv;
    }

    public String getCond_Pago() {
        return cond_Pago;
    }

    public void setCond_Pago(String cond_Pago) {
        this.cond_Pago = cond_Pago;
    }

    public String getCod_Mon() {
        return cod_Mon;
    }

    public void setCod_Mon(String cod_Mon) {
        this.cod_Mon = cod_Mon;
    }

    public String getMoneda() {
        return moneda;
    }

    public void setMoneda(String moneda) {
        this.moneda = moneda;
    }

    public BigDecimal getVta_Unid() {
        return vta_Unid;
    }

    public void setVta_Unid(BigDecimal vta_Unid) {
        this.vta_Unid = vta_Unid;
    }

    public BigDecimal getVta_Neta() {
        return vta_Neta;
    }

    public void setVta_Neta(BigDecimal vta_Neta) {
        this.vta_Neta = vta_Neta;
    }

    public BigDecimal getDscto() {
        return dscto;
    }

    public void setDscto(BigDecimal dscto) {
        this.dscto = dscto;
    }

    public BigDecimal getTotal_Cprom() {
        return total_Cprom;
    }

    public void setTotal_Cprom(BigDecimal total_Cprom) {
        this.total_Cprom = total_Cprom;
    }

    public BigDecimal getVta_Sin_Dscto() {
        return vta_Sin_Dscto;
    }

    public void setVta_Sin_Dscto(BigDecimal vta_Sin_Dscto) {
        this.vta_Sin_Dscto = vta_Sin_Dscto;
    }

    public String getFactura() {
        return factura;
    }

    public void setFactura(String factura) {
        this.factura = factura;
    }



}




@PersistenceUnit
EntityManagerFactory entityManagerFactory;

    @Test
    public void test() {

        EntityManager em = entityManagerFactory.createEntityManager();


Query query = em.createNativeQuery("SELECT * from UFN_REPORTE_VENTAS_DESDE_HASTA('20543886913','01/07/2015','21/07/2015','1')",
                        Venclipro.class);
        List<Venclipro> list = query.getResultList();


        System.err.println("tamaño : " + list.size());

        for (Venclipro obj : list) {
            System.err.println("Registro : " + obj.getRegistro() + " CD_VTA : "+ obj.getCod_Vta());
        }
}