Miten
Miten

Reputation: 358

jpa + hibernate + standalone

I am unable to understand why the relationship is not being persisted and the program will not exit fine but keeps running in eclipse.

Below is my code with packagename excluded:

Main:

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;

import PanelDao;
import Panel;
import Panelbinary;


public class PanelService {
    static byte[] file;
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            // TODO Auto-generated method stub
            InputStream in = new Object().getClass().getClassLoader().getSystemResourceAsStream("Astrology.zip");
            BufferedInputStream bin = new BufferedInputStream(in);
            byte[] ba = new byte[1024];
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            int n = -1;
            while(-1 != (n = bin.read(ba))) {
                bout.write(ba, 0, n);
            }
            file = bout.toByteArray();
            System.out.println("Astrology.zip bytes:" + file.length);

            if(file.length > 0) {
                Panel p = new PanelService().uploadAstrologoyPanel();
                System.out.println("panel id=" + p.getId());
                System.out.println("panelbinaryid=" + p.getPanelbinaries().get(0).getId());

            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

    public Panel uploadAstrologoyPanel() {
        Panel p = new Panel();
        PanelDao pd = new PanelDao();

        Date d = new Date();
        p.setPanelcategoryid(new BigDecimal(1));//books
        p.setPanelbinarytypeid(new BigDecimal(5));//json
        p.setDescription("Astrology");
        p.setDisplayname("Astrology");
        p.setFilterid(new BigDecimal(1));//all devices
        p.setLabel("Astrology");
        p.setPackagename("com.jio.panel.astrology");
        p.setCreated(d);
        p.setModified(d);
        pd.create(p);

        Panelbinary pb = new Panelbinary();
        pb.setActive(new BigDecimal(0));
        pb.setArtifact(file);
        pb.setArtifactsize(new BigDecimal(file.length));
        pb.setUserversion("1");
        pb.setWidget(new BigDecimal(0));
        pb.setCreated(d);
        pb.setModified(d);
        pb.setIncversion(new BigDecimal(1));
        p.addPanelbinary(pb);
        //pb.setPanel(p);

        p = pd.update(p);
        pd.entityManager.close();
        return p;

    }   

}

PanelBinary Entity

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

import javax.persistence.*;


import org.hibernate.annotations.ForeignKey;


/**
 * The persistent class for the PANELBINARY_ database table.
 * 
 */
@Entity
@Table(
        name = "PANELBINARY_",
        uniqueConstraints = { @UniqueConstraint(
                name = "PB_PID_IV_UK",
                columnNames = { "PANELID", "INCVERSION" }),
                @UniqueConstraint(
                        name = "PB_PID_UV_UK",
                        columnNames = { "PANELID", "USERVERSION" }) })
@SequenceGenerator(
        name = "PANELBINARYSEQ",
        sequenceName = "PANELBINARYSEQ",
        allocationSize = 1,
        initialValue = 1)
@SuppressWarnings("serial")
public class Panelbinary implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "PANELBINARYSEQ", strategy = GenerationType.SEQUENCE)
    private long id;

    @Column(name = "ACTIVE", nullable = false)
    private BigDecimal active;

    @Lob
    @Basic(optional = false, fetch = FetchType.LAZY)
    @Column(name = "ARTIFACT", nullable = false)    private byte[] artifact;

    @Column(name = "ARTIFACTSIZE", nullable = true)
    private BigDecimal artifactsize;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED", nullable = false)
    private Date created;

    @Lob
    private byte[] icon;

    private BigDecimal iconsize;

    @Column(name = "INCVERSION", nullable = false)
    private BigDecimal incversion;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "MODIFIED", nullable = false)
    private Date modified;

    @Lob
    private byte[] thumbnail;

    private BigDecimal thumbnailsize;


    @Column(name = "USERVERSION", nullable = false, length = 50)
    private String userversion;

    @Column(name = "WIDGET", nullable = true)
    private BigDecimal widget;

    //bi-directional many-to-one association to Panel
    @ManyToOne(optional = false)
    @JoinColumn(name = "PANELID", nullable = false)
    @ForeignKey(name = "PB_PID_FK")
    private Panel panel;

    public Panelbinary() {
    }

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

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

    public BigDecimal getActive() {
        return this.active;
    }

    public void setActive(BigDecimal active) {
        this.active = active;
    }

    public byte[] getArtifact() {
        return this.artifact;
    }

    public void setArtifact(byte[] artifact) {
        this.artifact = artifact;
    }

    public BigDecimal getArtifactsize() {
        return this.artifactsize;
    }

    public void setArtifactsize(BigDecimal artifactsize) {
        this.artifactsize = artifactsize;
    }

    public Date getCreated() {
        return this.created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public byte[] getIcon() {
        return this.icon;
    }

    public void setIcon(byte[] icon) {
        this.icon = icon;
    }

    public BigDecimal getIconsize() {
        return this.iconsize;
    }

    public void setIconsize(BigDecimal iconsize) {
        this.iconsize = iconsize;
    }

    public BigDecimal getIncversion() {
        return this.incversion;
    }

    public void setIncversion(BigDecimal incversion) {
        this.incversion = incversion;
    }

    public Date getModified() {
        return this.modified;
    }

    public void setModified(Date modified) {
        this.modified = modified;
    }

    public byte[] getThumbnail() {
        return this.thumbnail;
    }

    public void setThumbnail(byte[] thumbnail) {
        this.thumbnail = thumbnail;
    }

    public BigDecimal getThumbnailsize() {
        return this.thumbnailsize;
    }

    public void setThumbnailsize(BigDecimal thumbnailsize) {
        this.thumbnailsize = thumbnailsize;
    }

    public String getUserversion() {
        return this.userversion;
    }

    public void setUserversion(String userversion) {
        this.userversion = userversion;
    }

    public BigDecimal getWidget() {
        return this.widget;
    }

    public void setWidget(BigDecimal widget) {
        this.widget = widget;
    }

    public Panel getPanel() {
        return this.panel;
    }

    public void setPanel(Panel panel) {
        this.panel = panel;
    }

}

Panel Entity

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.*;


/**
 * The persistent class for the PANEL_ database table.
 * 
 */
@Entity
@Table(
    name = "PANEL_",
    uniqueConstraints = @UniqueConstraint(
        name = "P_LABEL_PACKAGENAME_UK",
        columnNames = { "LABEL", "PACKAGENAME" }))
@SequenceGenerator(
    name = "PANELSEQ",
    sequenceName = "PANELSEQ",
    allocationSize = 1,
    initialValue = 1)
@SuppressWarnings("serial")
public class Panel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "PANELSEQ", strategy = GenerationType.SEQUENCE)
    private long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED", nullable = false)
    private Date created;

    @Column(name = "DESCRIPTION", length = 250)
    private String description;

    @Column(name = "DISPLAYNAME", length = 64)
    private String displayname;

    private BigDecimal filterid;

    private BigDecimal initialstateid;

    @Column(name = "LABEL", nullable = false, length = 100)
    private String label;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "MODIFIED", nullable = false)
    private Date modified;

    @Column(name = "PACKAGENAME", nullable = false, length = 250)
    private String packagename;

    private BigDecimal panelbinarytypeid;

    private BigDecimal panelcategoryid;

    private BigDecimal panelorder;

    //bi-directional many-to-one association to Panelbinary
    @OneToMany(mappedBy="panel")
    private List<Panelbinary> panelbinaries;

    public Panel() {
    }

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

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

    public Date getCreated() {
        return this.created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDisplayname() {
        return this.displayname;
    }

    public void setDisplayname(String displayname) {
        this.displayname = displayname;
    }

    public BigDecimal getFilterid() {
        return this.filterid;
    }

    public void setFilterid(BigDecimal filterid) {
        this.filterid = filterid;
    }

    public BigDecimal getInitialstateid() {
        return this.initialstateid;
    }

    public void setInitialstateid(BigDecimal initialstateid) {
        this.initialstateid = initialstateid;
    }

    public String getLabel() {
        return this.label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public Date getModified() {
        return this.modified;
    }

    public void setModified(Date modified) {
        this.modified = modified;
    }

    public String getPackagename() {
        return this.packagename;
    }

    public void setPackagename(String packagename) {
        this.packagename = packagename;
    }

    public BigDecimal getPanelbinarytypeid() {
        return this.panelbinarytypeid;
    }

    public void setPanelbinarytypeid(BigDecimal panelbinarytypeid) {
        this.panelbinarytypeid = panelbinarytypeid;
    }

    public BigDecimal getPanelcategoryid() {
        return this.panelcategoryid;
    }

    public void setPanelcategoryid(BigDecimal panelcategoryid) {
        this.panelcategoryid = panelcategoryid;
    }

    public BigDecimal getPanelorder() {
        return this.panelorder;
    }

    public void setPanelorder(BigDecimal panelorder) {
        this.panelorder = panelorder;
    }

    public List<Panelbinary> getPanelbinaries() {
        if(null == panelbinaries) {
            panelbinaries = new ArrayList<Panelbinary>();
        }
        return this.panelbinaries;
    }

    public void setPanelbinaries(List<Panelbinary> panelbinaries) {
        this.panelbinaries = panelbinaries;
    }

    public Panelbinary addPanelbinary(Panelbinary panelbinary) {
        getPanelbinaries().add(panelbinary);
        panelbinary.setPanel(this);

        return panelbinary;
    }

    public Panelbinary removePanelbinary(Panelbinary panelbinary) {
        getPanelbinaries().remove(panelbinary);
        panelbinary.setPanel(null);

        return panelbinary;
    }

}

DAO

import Panel;

public class PanelDao extends GenericDaoJpaImpl<Panel, Integer> {

    @Override
    public Panel create(Panel t) {

        try {
            entityManager.getTransaction().begin();
            super.create(t);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            entityManager.getTransaction().rollback();
        }
        return t;
    }



    @Override
    public Panel update(Panel t) {
        try {
            entityManager.getTransaction().begin();
            super.update(t);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();

            entityManager.getTransaction().rollback();
        }
        return t;
    }

    @Override
    public void delete(Panel t) {
        try {
            entityManager.getTransaction().begin();
            super.delete(t);
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();

            entityManager.getTransaction().rollback();
        }
    }
}

DAO Super class

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

public class GenericDaoJpaImpl<T, PK extends Serializable> 
implements GenericDao<T, PK> {
    static {
    EntityManagerFactory factory = Persistence
            .createEntityManagerFactory("dev2db");
          entityManager = factory.createEntityManager();
    }
    protected Class<T> entityClass;

    @PersistenceContext
    public static EntityManager entityManager;

    public GenericDaoJpaImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass()
                .getGenericSuperclass();
        this.entityClass = (Class<T>) genericSuperclass
                .getActualTypeArguments()[0];
    }

    @Override
    public T create(T t) {
        this.entityManager.persist(t);
        return t;
    }

    @Override
    public T read(PK id) {
        return this.entityManager.find(entityClass, id);
    }

    @Override
    public T update(T t) {
        return this.entityManager.merge(t);
    }

    @Override
    public void delete(T t) {
        t = this.entityManager.merge(t);
        this.entityManager.remove(t);
    }
}

super dao interface

import java.io.Serializable;

public interface GenericDao<T, PK extends Serializable> {
    T create(T t);
    T read(PK id);
    T update(T t);
    void delete(T t);
}

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="dev2db" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.archive.autodetection" value="class, hbm"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate" />

            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@host:1521:xxxx" />
            <property name="javax.persistence.jdbc.user" value="xxxx" />
            <property name="javax.persistence.jdbc.password" value="xxxx" />
        </properties>
    </persistence-unit>
</persistence>

log:

Astrology.zip bytes:267
Mar 04, 2014 1:01:10 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 04, 2014 1:01:10 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 04, 2014 1:01:10 PM org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
Mar 04, 2014 1:01:10 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: dev2db
    ...]
Mar 04, 2014 1:01:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Mar 04, 2014 1:01:10 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 04, 2014 1:01:10 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 04, 2014 1:01:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [oracle.jdbc.OracleDriver] at URL [jdbc:oracle:thin:@host:port:sid]
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=prodm6_fix, password=****}
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Mar 04, 2014 1:01:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Mar 04, 2014 1:01:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Mar 04, 2014 1:01:11 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000229: Running schema validator
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: HHH000102: Fetching database metadata
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: PRODM6_FIX.PANELBINARY_
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [icon, thumbnailsize, modified, id, userversion, artifact, thumbnail, created, iconsize, panelid, active, incversion, artifactsize, widget]
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: xxxx.PANEL_
Mar 04, 2014 1:01:12 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [panelorder, id, initialstateid, created, panelcategoryid, description, packagename, label, panelbinarytypeid, filterid, modified, displayname]
panel id=13
panelbinaryid=0

What I want to get is that panel and panelbinaryid both have valid value. I do not see panelbinary being persisted at all in db.

The program does not terminate either after inserting panel fine even though I close entity manager.

would be nice to easily add container managed transaction with some few lines of code and annotations instead of whole new way of doing it.

Regards,

Miten.

Upvotes: 0

Views: 837

Answers (1)

Julien
Julien

Reputation: 1097

1 - Regarding the persistence problem, this is because your association is managed by PanelBinary (defined by your attribute @OneToMany(mappedBy="panel") ) and is not cascaded down the relationship.

To make it work you need to :

  • set the panel property with the panel object in your PanelBinary object (which you did and commented!)
  • define the one-to-many relationship with a cascade attribute

    @OneToMany(cascade=ALL, mappedBy="panel")
    private List<Panelbinary> panelbinaries;
    

2 - To "easily" setup transactional behaviour using annotations, you should look at Spring documentation:

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations

Basically, you will need to define a spring config file defining datasource, transaction management and enabling transactional annotations. A tutorial can also be found here:

http://techannotation.wordpress.com/2012/05/29/5-minutes-with-jpa-transaction/

3 - No clue about the program not finishing.. the last logs shows it reached the end of the main method..

Upvotes: 1

Related Questions