facebook

JPA Save not working

  1. MyEclipse Archived
  2.  > 
  3. Database Tools (DB Explorer, Hibernate, etc.)
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #315335 Reply

    Glenn Puckett
    Participant

    I generated a Web application and then reverse engineered a MySQL database into the Web ap using JPA and Hibernate. So far I have been able to use the findAll() method to return a list of table contents. But when I go to an input form, fill out the data and then attempt to do a save() method it does not work. I get no errors and even get a log message that the data was saved successfully. Then I go out to the mySQL database and the data is not there.

    The table has an auto increment primary key and has a foreign key relationship with a couple of other tables.
    Here is the DDL for the table:

    
    CREATE TABLE `admin_craft_tbl` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `code` char(10) NOT NULL,
      `name` varchar(90) NOT NULL,
      `descr` varchar(120) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    The following modules were genereated:

    
    /**
     * AbstractAdminCraftTbl entity provides the base persistence definition of the
     * AdminCraftTbl entity. @author MyEclipse Persistence Tools
     */
    @MappedSuperclass
    public abstract class AbstractAdminCraftTbl implements java.io.Serializable {
    
        // Fields
    
        private Integer id;
        private String code;
        private String name;
        private String descr;
        private Set<WizardDetailTbl> wizardDetailTbls = new HashSet<WizardDetailTbl>(
                0);
        private Set<ProjLaborTbl> projLaborTbls = new HashSet<ProjLaborTbl>(0);
    
        // Constructors
    
        /** default constructor */
        public AbstractAdminCraftTbl() {
        }
    
        /** minimal constructor */
        public AbstractAdminCraftTbl(String code, String name, String descr) {
            this.code = code;
            this.name = name;
            this.descr = descr;
        }
    
        /** full constructor */
        public AbstractAdminCraftTbl(String code, String name, String descr,
            Set<WizardDetailTbl> wizardDetailTbls,
            Set<ProjLaborTbl> projLaborTbls) {
            this.code = code;
            this.name = name;
            this.descr = descr;
            this.wizardDetailTbls = wizardDetailTbls;
            this.projLaborTbls = projLaborTbls;
        }
    
        // Property accessors
        @Id
        @GeneratedValue(strategy = IDENTITY)
        @Column(name = "id", unique = true, nullable = false)
        public Integer getId() {
            return this.id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        @Column(name = "code", nullable = false, length = 10)
        public String getCode() {
            return this.code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        @Column(name = "name", nullable = false, length = 90)
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Column(name = "descr", nullable = false, length = 120)
        public String getDescr() {
            return this.descr;
        }
    
        public void setDescr(String descr) {
            this.descr = descr;
        }
    
        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "adminCraftTbl")
        public Set<WizardDetailTbl> getWizardDetailTbls() {
            return this.wizardDetailTbls;
        }
    
        public void setWizardDetailTbls(Set<WizardDetailTbl> wizardDetailTbls) {
            this.wizardDetailTbls = wizardDetailTbls;
        }
    
        @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "adminCraftTbl")
        public Set<ProjLaborTbl> getProjLaborTbls() {
            return this.projLaborTbls;
        }
    
        public void setProjLaborTbls(Set<ProjLaborTbl> projLaborTbls) {
            this.projLaborTbls = projLaborTbls;
        }
    
    }
    
    
    /**
     * AdminCraftTbl entity. @author MyEclipse Persistence Tools
     */
    @Entity
    @Table(name = "admin_craft_tbl", catalog = "myproj")
    public class AdminCraftTbl extends AbstractAdminCraftTbl implements
            java.io.Serializable {
    
        // Constructors
    
        /** default constructor */
        public AdminCraftTbl() {
        }
    
        /** minimal constructor */
        public AdminCraftTbl(String code, String name, String descr) {
            super(code, name, descr);
        }
    
        /** full constructor */
        public AdminCraftTbl(String code, String name, String descr,
                Set<WizardDetailTbl> wizardDetailTbls,
                Set<ProjLaborTbl> projLaborTbls) {
            super(code, name, descr, wizardDetailTbls, projLaborTbls);
        }
    
    }
    
    
    /**
     * A data access object (DAO) providing persistence and search support for
     * AdminCraftTbl entities. Transaction control of the save(), update() and
     * delete() operations must be handled externally by senders of these methods or
     * must be manually added to each of these methods for data to be persisted to
     * the JPA datastore.
     * 
     * @see mm.myproj.jpa.AdminCraftTbl
     * @author MyEclipse Persistence Tools
     */
    
    public class AdminCraftTblDAO implements IAdminCraftTblDAO {
        // property constants
        public static final String CODE = "code";
        public static final String NAME = "name";
        public static final String DESCR = "descr";
    
        private EntityManager getEntityManager() {
            return EntityManagerHelper.getEntityManager();
        }
    
        /**
         * Perform an initial save of a previously unsaved AdminCraftTbl entity. All
         * subsequent persist actions of this entity should use the #update()
         * method. This operation must be performed within the a database
         * transaction context for the entity's data to be permanently saved to the
         * persistence store, i.e., database. This method uses the
         * {@link javax.persistence.EntityManager#persist(Object)
         * EntityManager#persist} operation.
         * 
         * <pre>
         * EntityManagerHelper.beginTransaction();
         * AdminCraftTblDAO.save(entity);
         * EntityManagerHelper.commit();
         * </pre>
         * 
         * @param entity
         *            AdminCraftTbl entity to persist
         * @throws RuntimeException
         *             when the operation fails
         */
        public void save(AdminCraftTbl entity) {
            EntityManagerHelper.log("saving AdminCraftTbl instance", Level.INFO,
                    null);
            try {
                getEntityManager().persist(entity);
                EntityManagerHelper.log("save successful", Level.INFO, null);
            } catch (RuntimeException re) {
                EntityManagerHelper.log("save failed", Level.SEVERE, re);
                throw re;
            }
        }
    
        /**
         * Delete a persistent AdminCraftTbl entity. This operation must be
         * performed within the a database transaction context for the entity's data
         * to be permanently deleted from the persistence store, i.e., database.
         * This method uses the
         * {@link javax.persistence.EntityManager#remove(Object)
         * EntityManager#delete} operation.
         * 
         * <pre>
         * EntityManagerHelper.beginTransaction();
         * AdminCraftTblDAO.delete(entity);
         * EntityManagerHelper.commit();
         * entity = null;
         * </pre>
         * 
         * @param entity
         *            AdminCraftTbl entity to delete
         * @throws RuntimeException
         *             when the operation fails
         */
        public void delete(AdminCraftTbl entity) {
            EntityManagerHelper.log("deleting AdminCraftTbl instance", Level.INFO,
                    null);
            try {
                entity = getEntityManager().getReference(AdminCraftTbl.class,
                        entity.getId());
                getEntityManager().remove(entity);
                EntityManagerHelper.log("delete successful", Level.INFO, null);
            } catch (RuntimeException re) {
                EntityManagerHelper.log("delete failed", Level.SEVERE, re);
                throw re;
            }
        }
    
        /**
         * Persist a previously saved AdminCraftTbl entity and return it or a copy
         * of it to the sender. A copy of the AdminCraftTbl entity parameter is
         * returned when the JPA persistence mechanism has not previously been
         * tracking the updated entity. This operation must be performed within the
         * a database transaction context for the entity's data to be permanently
         * saved to the persistence store, i.e., database. This method uses the
         * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
         * operation.
         * 
         * <pre>
         * EntityManagerHelper.beginTransaction();
         * entity = AdminCraftTblDAO.update(entity);
         * EntityManagerHelper.commit();
         * </pre>
         * 
         * @param entity
         *            AdminCraftTbl entity to update
         * @return AdminCraftTbl the persisted AdminCraftTbl entity instance, may
         *         not be the same
         * @throws RuntimeException
         *             if the operation fails
         */
        public AdminCraftTbl update(AdminCraftTbl entity) {
            EntityManagerHelper.log("updating AdminCraftTbl instance", Level.INFO,
                    null);
            try {
                AdminCraftTbl result = getEntityManager().merge(entity);
                EntityManagerHelper.log("update successful", Level.INFO, null);
                return result;
            } catch (RuntimeException re) {
                EntityManagerHelper.log("update failed", Level.SEVERE, re);
                throw re;
            }
        }
    
        public AdminCraftTbl findById(Integer id) {
            EntityManagerHelper.log(
                    "finding AdminCraftTbl instance with id: " + id, Level.INFO,
                    null);
            try {
                AdminCraftTbl instance = getEntityManager().find(
                        AdminCraftTbl.class, id);
                return instance;
            } catch (RuntimeException re) {
                EntityManagerHelper.log("find failed", Level.SEVERE, re);
                throw re;
            }
        }
    
        /**
         * Find all AdminCraftTbl entities with a specific property value.
         * 
         * @param propertyName
         *            the name of the AdminCraftTbl property to query
         * @param value
         *            the property value to match
         * @param rowStartIdxAndCount
         *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
         *            row index in the query result-set to begin collecting the
         *            results. rowStartIdxAndCount[1] specifies the the maximum
         *            number of results to return.
         * @return List<AdminCraftTbl> found by query
         */
        @SuppressWarnings("unchecked")
        public List<AdminCraftTbl> findByProperty(String propertyName,
                final Object value, final int... rowStartIdxAndCount) {
            EntityManagerHelper.log(
                    "finding AdminCraftTbl instance with property: " + propertyName
                            + ", value: " + value, Level.INFO, null);
            try {
                final String queryString = "select model from AdminCraftTbl model where model."
                        + propertyName + "= :propertyValue";
                Query query = getEntityManager().createQuery(queryString);
                query.setParameter("propertyValue", value);
                if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
                    int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
                    if (rowStartIdx > 0) {
                        query.setFirstResult(rowStartIdx);
                    }
    
                    if (rowStartIdxAndCount.length > 1) {
                        int rowCount = Math.max(0, rowStartIdxAndCount[1]);
                        if (rowCount > 0) {
                            query.setMaxResults(rowCount);
                        }
                    }
                }
                return query.getResultList();
            } catch (RuntimeException re) {
                EntityManagerHelper.log("find by property name failed",
                        Level.SEVERE, re);
                throw re;
            }
        }
    
        public List<AdminCraftTbl> findByCode(Object code,
                int... rowStartIdxAndCount) {
            return findByProperty(CODE, code, rowStartIdxAndCount);
        }
    
        public List<AdminCraftTbl> findByName(Object name,
                int... rowStartIdxAndCount) {
            return findByProperty(NAME, name, rowStartIdxAndCount);
        }
    
        public List<AdminCraftTbl> findByDescr(Object descr,
                int... rowStartIdxAndCount) {
            return findByProperty(DESCR, descr, rowStartIdxAndCount);
        }
    
        /**
         * Find all AdminCraftTbl entities.
         * 
         * @param rowStartIdxAndCount
         *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
         *            row index in the query result-set to begin collecting the
         *            results. rowStartIdxAndCount[1] specifies the the maximum
         *            count of results to return.
         * @return List<AdminCraftTbl> all AdminCraftTbl entities
         */
        @SuppressWarnings("unchecked")
        public List<AdminCraftTbl> findAll(final int... rowStartIdxAndCount) {
            EntityManagerHelper.log("finding all AdminCraftTbl instances",
                    Level.INFO, null);
            try {
                final String queryString = "select model from AdminCraftTbl model";
                Query query = getEntityManager().createQuery(queryString);
                if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
                    int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
                    if (rowStartIdx > 0) {
                        query.setFirstResult(rowStartIdx);
                    }
    
                    if (rowStartIdxAndCount.length > 1) {
                        int rowCount = Math.max(0, rowStartIdxAndCount[1]);
                        if (rowCount > 0) {
                            query.setMaxResults(rowCount);
                        }
                    }
                }
                return query.getResultList();
            } catch (RuntimeException re) {
                EntityManagerHelper.log("find all failed", Level.SEVERE, re);
                throw re;
            }
        }
    
    }
    

    I am deploying the exploded WAR in JBoss 4.2.3.GA.

    I have the following code in mysql-ds.xml:

    
    local-tx-datasource>
    
        <jndi-name>jdbc/DATADS</jndi-name>
        <connection-url>jdbc:mysql://localhost/mydata</connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
    
        <user-name>root</user-name>
        <password>xxxxxxxx</password>
    
        <min-pool-size>20</min-pool-size>
        <max-pool-size>100</max-pool-size>
        <idle-timeout-minutes>5</idle-timeout-minutes>
    
        <exception-sorter-class-name>com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter</exception-sorter-class-name>
    
        <valid-connection-checker-class-name>com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker</valid-connection-checker-class-name>
    
        <metadata>
          <type-mapping>mySQL</type-mapping>
        </metadata>
    
      </local-tx-datasource>
    

    Also in the persistence.xml file I have:

    
    <persistence-unit name="MYAPPU" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
    
        **** list of table classes including *****
    
        <class>mm.myproj.jpa.GroupUserAccessTbl</class>
        <class>mm.myproj.jpa.AbstractAdminCraftTbl</class>
        <properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost/MYDATA" />
            <property name="hibernate.connection.username" value="root" />
            <property name="hibernate.connection.password" value="xxxxxxx" />
        </properties>
    </persistence-unit>
    

    I am at a total loss. I have debugged the DAO and verified that the param is populated with valid data. I also couldn’t find anything in the logs. So I am not sure where to start here. Any help or suggestions would be enormously appreciated. I am at a point where if I can’t get this resolved quickly I’ll have to go back to writing my own sql and do the updates the old fashioned way. I’d rather not have to do that.

    #315337 Reply

    Glenn Puckett
    Participant

    I did figure this out. Being new to Struts 2 and JPA I follow the tutorials to the letter. Either I totally overlooked the transaction helper or the tutorial didn’t bother to explain it’s use. I’ll have to go back and double check before commenting more on that. But I finally discovered a reference to the EntityManagerHelper class and wrapped a transaction around the save action, added a commit and the update hit the table.

    #315350 Reply

    support-swapna
    Moderator

    WGPuckett,

    Glad that it is working.
    Do let us know if you have any other issues.

Viewing 3 posts - 1 through 3 (of 3 total)
Reply To: JPA Save not working

You must be logged in to post in the forum log in