0

本当の問題は、最近永続化されたエンティティの ID を取得できないことだと思います (方法がわかりません)。私は eclipseLink 2.1 と mysql 5.1.7 を使用しているので、エンティティ クラスはそのままにしておきます

多対多の結合テーブルは ProductosVentas です。スペイン語のネーミングでごめんなさい

私を助けてください

ここに私のスクリプトがあります

public static void main(String args[]) {
    EntityManager em = EclipseLinkUtil.getEntityManagerFactory();
    em.getTransaction().begin();
    try {
        Query query = em
            .createQuery("from Productos p where p.nombre like 'Lavado de motor' ");
        Productos selledItem = (Productos) query.getSingleResult();
        query = em.createNativeQuery("select curdate() ");
        java.sql.Date sellingDate = (Date) query.getSingleResult();
        Ventas v1 = new Ventas();
        v1.setCondicionventaIdcondicionventa(new Condicionventa(1));
        v1.setFecha(sellingDate);
        List<Productosventas> selledItemTableList = new ArrayList<>();
        v1.setProductosventasCollection(selledItemTableList);
        Productosventas p = new Productosventas();
        p.setVentas(v1);
        p.setCantidad(1);
        p.setProductos(selledItem);
        selledItemTableList.add(p);
        em.persist(v1);
        em.persist(p);
        em.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
}

エラー

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:

列 'ventas_idventa' を null にすることはできません エラー コード: 1048 呼び出し: productosventas に INSERT (cantidad、ventas_idventa、productos_idProductos、PriceModifiers_idPriceModifier) 値 (?、?、?、?) bind => [4 つのパラメーターがバインドされています]

それらは私のエンティティです

@Entity
@Table(name = "productos")
@XmlRootElement
public class Productos implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "productos")
    private Collection<Productosventas> productosventasCollection;
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idProductos")
    private Integer idProductos;
    // [properties]
    @JoinColumn(name = "PriceModifiers_idPriceModifier",
            referencedColumnName = "idPriceModifier")
    @ManyToOne(optional = false)
    private Pricemodifiers priceModifiersidPriceModifier;
    @JoinColumn(name = "AreaServicio_idAreaServicio",
            referencedColumnName = "idAreaServicio")
    @ManyToOne(optional = false)
    private Areaservicio areaServicioidAreaServicio;
    @JoinColumn(name = "formaventa_idFormaVenta",
            referencedColumnName = "idFormaVenta")
    @ManyToOne(optional = false)
    private Formaventa formaventaidFormaVenta;

    // geters and setters
    @XmlTransient
    public Collection<Productosventas> getProductosventasCollection() {
        return productosventasCollection;
    }

    public void setProductosventasCollection(
            Collection<Productosventas> productosventasCollection) {
        this.productosventasCollection = productosventasCollection;
    }
}

@Entity
@Table(name = "ventas")
@XmlRootElement
public class Ventas implements Serializable {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "ventas")
    private Collection<Productosventas> productosventasCollection;
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idventa")
    private Integer idventa;
    @Column(name = "fecha")
    @Temporal(TemporalType.TIMESTAMP)
    private Date fecha;
    @JoinColumn(name = "condicionventa_idcondicionventa",
            referencedColumnName = "idcondicionventa")
    @ManyToOne(optional = false)
    private Condicionventa condicionventaIdcondicionventa;
    @JoinColumn(name = "climas_idclimas", referencedColumnName = "idclimas")
    @ManyToOne(optional = false)
    private Climas climasIdclimas;
    @JoinColumn(name = "cliente_idcliente", referencedColumnName = "idcliente")
    @ManyToOne(optional = false)
    private Cliente clienteIdcliente;
    @JoinColumn(name = "cars_numberplate", referencedColumnName = "numberplate")
    @ManyToOne(optional = false)
    private Cars carsNumberplate;

    // getters and setters
    @XmlTransient
    public Collection<Productosventas> getProductosventasCollection() {
        return productosventasCollection;
    }

    public void setProductosventasCollection(
            Collection<Productosventas> productosventasCollection) {
        this.productosventasCollection = productosventasCollection;
    }
}

@Entity
@Table(name = "productosventas")
@XmlRootElement
public class Productosventas implements Serializable {

    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected ProductosventasPK productosventasPK;
    @Column(name = "cantidad")
    private Integer cantidad;
    @JoinColumn(name = "PriceModifiers_idPriceModifier",
            referencedColumnName = "idPriceModifier")
    @ManyToOne(optional = false)
    private Pricemodifiers priceModifiersidPriceModifier;
    @JoinColumn(name = "ventas_idventa", referencedColumnName = "idventa",
            insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Ventas ventas;
    @JoinColumn(name = "productos_idProductos",
            referencedColumnName = "idProductos", insertable = false,
            updatable = false)
    @ManyToOne(optional = false)
    private Productos productos;

    public Productosventas() {}

    public Productosventas(ProductosventasPK productosventasPK) {
        this.productosventasPK = productosventasPK;
    }

    public Productosventas(int ventasIdventa, int productosidProductos) {
        this.productosventasPK = new ProductosventasPK(ventasIdventa,
            productosidProductos);
    }

    public ProductosventasPK getProductosventasPK() {
        return productosventasPK;
    }

    public void setProductosventasPK(ProductosventasPK productosventasPK) {
        this.productosventasPK = productosventasPK;
    }

    // geters and setters
}

@Embeddable
public class ProductosventasPK implements Serializable {

    @Basic(optional = false)
    @Column(name = "ventas_idventa")
    private int ventasIdventa;
    @Basic(optional = false)
    @Column(name = "productos_idProductos")
    private int productosidProductos;

    public ProductosventasPK() {}

    public ProductosventasPK(int ventasIdventa, int productosidProductos) {
        this.ventasIdventa = ventasIdventa;
        this.productosidProductos = productosidProductos;
    }

    // geters and setters

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) ventasIdventa;
        hash += (int) productosidProductos;
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are
        // not set
        if (!(object instanceof ProductosventasPK)) {
            return false;
        }
        ProductosventasPK other = (ProductosventasPK) object;
        if (this.ventasIdventa != other.ventasIdventa) {
            return false;
        }
        if (this.productosidProductos != other.productosidProductos) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "tiendita.entities.ProductosventasPK[ ventasIdventa="
            + ventasIdventa + ", productosidProductos=" + productosidProductos
            + " ]";
    }
}

編集

私は最初にフラッシュしようとしました(クリスに感謝します)が、それは醜くて長くて不必要に見えます...これは派手な方法のようですが、休止状態で書かれているのはあまりにも悪いです。私はeclipselinkを使用しています. このコードが同じように書けることを願っています。

session.beginTransaction();

Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");

Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
//new category, need save to get the id first
session.save(category1);

StockCategory stockCategory = new StockCategory();
stockCategory.setStock(stock);
stockCategory.setCategory(category1);
stockCategory.setCreatedDate(new Date()); //extra column
stockCategory.setCreatedBy("system"); //extra column

stock.getStockCategories().add(stockCategory);

session.save(stock);

session.getTransaction().commit();

これは非常に初歩的なようです

EntityManager em = EclipseLinkUtil.getEntityManagerFactory();

em.getTransaction().begin();
try {

    Query query = em.createQuery("from Productos p where p.nombre like 'Lavado de motor' ");
    Productos selledItem = (Productos) query.getSingleResult();

    query = em.createNativeQuery("select curdate() ");
    java.sql.Date sellingDate = (Date) query.getSingleResult();

    Ventas v1 = new Ventas();
    v1.setCondicionventaIdcondicionventa(new Condicionventa(1));
    v1.setFecha(sellingDate);

    List<Productosventas> selledItemTableList = new ArrayList<>();
    v1.setProductosventasCollection(selledItemTableList);
    em.persist(v1);
    em.flush();

    Productosventas p = new Productosventas();
    p.setProductosventasPK(new ProductosventasPK(v1.getIdventa(), selledItem.getIdProductos()));
    p.setCantidad(1);
    p.setProductos(selledItem);
    selledItemTableList.add(p);

    p = new Productosventas();
    p.setProductosventasPK(new ProductosventasPK(v1.getIdventa(), selledItem.getIdProductos()));
    p.setCantidad(2);
    selledItemTableList.add(p);
    selledItem.setProductosventasCollection(selledItemTableList);

    em.persist(selledItem);
    em.getTransaction().commit();

} catch (Exception e) {
    e.printStackTrace();
    em.getTransaction().rollback();
} finally {
    em.close();
}

私が一番嫌いなのはこれです

    em.persist(v1);
    em.flush();
    Productosventas p = new Productosventas();
    p.setProductosventasPK(new ProductosventasPK(v1.getIdventa(), selledItem.getIdProductos()));
    p.setCantidad(1);
    p.setProductos(selledItem);

2回目の編集

public class ProductosventasPK implements Serializable {

     private int ventas;

    private int productos;

    public ProductosventasPK() {
    }

    public ProductosventasPK(int ventasIdventa, int productosidProductos) {
        this.ventas = ventasIdventa;
        this.productos = productosidProductos;
    }
    // geters and setters

    @Override
    public String toString() {
        return "tiendita.entities.ProductosventasPK[ ventasIdventa=" + ventas
            + ", productosidProductos=" + productos + " ]";
    }

}

@Entity
@IdClass(ProductosventasPK.class)
@Table(name = "productosventas", catalog = "tiendita", schema = "")
public class Productosventas implements Serializable {
@JoinColumn(name = "productos_idProductos", referencedColumnName = "idProductos",
        insertable = true, updatable = true)
    @Id
    @ManyToOne(optional = false, cascade = CascadeType.MERGE)
    private Productos productos;
    @JoinColumn(name = "ventas_idventa", referencedColumnName = "idventa",
        insertable = true, updatable = true)
    @Id
    @ManyToOne(optional = false)
    private Ventas ventas;

    ProductosventasPK productosventasPK;
//important parts

}

残りはまったく同じままです

最終編集

[EL 警告]: 2013-09-25 17:14:14.291--ServerSession(1770214826)--例外 [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions .DatabaseException 内部例外: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 不明な列 'PRODUCTOSVENTASPK' 'フィールド リスト' エラー コード: 1054 呼び出し: SELECT cantidad, PRODUCTOSVENTASPK, PriceModifiers_idPriceModifier, productos_idProductos, ventas_idventa FROM tiendita.productosventas WHERE (productos_idProductos = ?) bind => [1 パラメータ バインド] クエリ: ReadAllQuery(name="productosventasList" referenceClass=Productosventas sql="SELECT cantidad, PRODUCTOSVENTASPK, PriceModifiers_idPriceModifier, productos_idProductos, ventas_idventa FROM tiendita.productosventas WHERE (productos_idProductos = ?)") BUILD SUCCESSFUL (合計時間: 3 秒)

public class Productosventas implements Serializable {

    private static final long serialVersionUID = 1L;
    @Column(name = "cantidad")
    private Integer cantidad;
    @JoinColumn(name = "PriceModifiers_idPriceModifier", referencedColumnName = "idPriceModifier")
    @ManyToOne
    private Pricemodifiers priceModifiersidPriceModifier;
    @JoinColumn(name = "productos_idProductos", referencedColumnName = "idProductos", insertable = true, updatable = true)
    @Id
    @ManyToOne(optional = false, cascade = CascadeType.MERGE)
    private Productos productos;
    @JoinColumn(name = "ventas_idventa", referencedColumnName = "idventa", insertable = true, updatable = true)
    @Id
    @ManyToOne(optional = false)
    private Ventas ventas;
    @Transient//transistent worked like a charm
    ProductosventasPK productosventasPK;
...rest of the class }

今、私は私が望むように挿入します

public static void prueba2() {
    EntityManager em = EclipseLinkUtil.getEntityManagerFactory();
    em.getTransaction().begin();
    try {
        Query query = em.createQuery("from Productos p where p.nombre like 'Lavado de motor' ");
        Productos selledItem = (Productos) query.getSingleResult();
        query = em.createQuery("from Productos p where p.nombre like 'Lavado de ventana' ");
        Productos selledItem2 = (Productos) query.getSingleResult();

    // query = em.createNativeQuery("select curdate() ");
    //java.sql.Date sellingDate = (Date) query.getSingleResult();
        java.util.Date sellingDate = new java.util.Date();

        Ventas v1 = new Ventas();
        v1.setCondicionventaIdcondicionventa(new Condicionventa(1));
        v1.setFecha(sellingDate);

        List<Productosventas> selledItemTableList = new ArrayList<>();
        Productosventas pdv = new Productosventas();
        Productosventas pdv2 = new Productosventas();
        em.persist(v1);

        pdv.setCantidad(2);
        pdv.setProductos(selledItem);
        pdv.setVentas(v1);
        pdv2.setCantidad(2);
        pdv2.setProductos(selledItem2);
        pdv2.setVentas(v1);

        selledItem.getProductosventasList().add(pdv);
        selledItem.getProductosventasList().add(pdv2);

        v1.setProductosventasList(selledItemTableList);


        em.getTransaction().commit();

    } catch (Exception e) {
        em.getTransaction().rollback();
    } finally {
        em.close();
    }
}
4

1 に答える 1

1

Productosventas で使用する ID 値を取得するには、参照されたエンティティを永続化してから、flush を呼び出してプロバイダーに SQL 挿入を発行させる必要があります。その場合にのみ、ID 戦略を使用するときにデータベースから ID を設定できますが、テーブルの順序付けでは通常、事前割り当てが許可されているため、持続呼び出しで使用できます。その後、エンティティからそれらを取得し、Productosventas の embeddedid 内に設定できます。

JPA 2.0 機能を使用できる場合の代替手段は、派生 ID を使用することです。Productosventas の場合は、priceModifiersidPriceModifier を @MapsId("productosidProductos") でマークするだけで、プロバイダーは ID を割り当てるときにリレーションシップを使用して embeddedid フィールドを設定します。他の関係についても同じことを行うと、3 つのエンティティすべてを同時に永続化でき、3 つすべてのフラッシュまたはコミット後に ID 値が設定されます。

http://wiki.eclipse.org/EclipseLink/Examples/JPA/2.0/DerivedIdentifiers http://wiki.eclipse.org/EclipseLink/Development/JPA_2.0/mappedbyid

于 2013-09-23T11:52:04.377 に答える