-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: Hibernate query return single result after data insertation
PostPosted: Thu Mar 15, 2012 3:35 pm 
Newbie

Joined: Thu Mar 15, 2012 2:48 pm
Posts: 13
Hello there, i'm using Hibernate and Spring together, once i try to insert a row to my table, in any next select i receive only one row...
but after restarting server, all rows include new rows and old rows will get shown....

I set my DAO through Bean files and it's like this:

Code:
package com.bedkaco.portlets.teacher.dao;

import com.bedkaco.portlets.teacher.model.Teacher;
import org.hibernate.Hibernate;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

/**
* Created by IntelliJ IDEA.
* User: Farnoush
* Date: 12/21/11
* Time: 11:18 AM
* To change this template use File | Settings | File Templates.
*/
public class TeacherDao extends HibernateDaoSupport {
    public Teacher getTeacher(long teachid) {
        Teacher teacher =
                (Teacher)getHibernateTemplate().get(Teacher.class, teachid);
        Hibernate.initialize(teacher);
        return teacher;
    }

    public List getTeacherByCondition(String condition, String orderby, int limit) {
        String query = "from Teacher";
        if (condition.length() > 0)
            query += " where " + condition;
        if (orderby.length() > 0)
            query += " order by " + orderby;

        HibernateTemplate hibernateTemplate = getHibernateTemplate();
        if (limit > 0)
            hibernateTemplate.setMaxResults(limit);

        return hibernateTemplate.find(query);
    }

    public void saveTeacher(Teacher teacher) {
        getHibernateTemplate().saveOrUpdate(teacher);
    }

    public void removeTeacher(Teacher teacher) {
        getHibernateTemplate().delete(teacher);
    }
}


Code:
package com.bedkaco.portlets.teacher.factories;

import com.bedkaco.portlets.teacher.dao.TeacherDao;
import com.bedkaco.portlets.teacher.model.Teacher;

import java.util.List;

/**
* Created by IntelliJ IDEA.
* User: Farnoush
* Date: 12/21/11
* Time: 11:18 AM
* To change this template use File | Settings | File Templates.
*/
public class TeacherFactory {
    private TeacherDao teacherDao;

    public TeacherDao getTeacherDao() {
        return teacherDao;
    }

    public void setTeacherDao(TeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }

    public Teacher getTeacher(long teachid) {
        return teacherDao.getTeacher(teachid);
    }

    public List getTeachers() {
        return getTeacherByCondition("", "", 0);
    }

    public List getTeachers(String orderby, int limit) {
        return getTeacherByCondition("", orderby, limit);
    }

    public List getTeacherByCondition(String condition, String orderby, int limit) {
        return teacherDao.getTeacherByCondition(condition, orderby, limit);
    }

    public void saveTeacher(Teacher teacher) {
        teacherDao.saveTeacher(teacher);
    }

    public void removeTeacher(Teacher teacher) {
        teacherDao.removeTeacher(teacher);
    }
}


Code:
package com.bedkaco.portlets.teacher.model;
// Generated Oct 11, 2010 4:28:33 PM by Hibernate Tools 3.2.4.GA

import javax.persistence.*;

/**
* SPRStudent generated by hbm2java
*/
@Entity
@Table(name = "teacher", schema = "public")
public class Teacher implements java.io.Serializable {

   private long teachid;
   private String fistname;
   private String lastname;
   private String rate;

   public Teacher() {
   }

   @Id
   @Column(name = "teachid", unique = true, nullable = false)
    public long getTeachid() {
        return teachid;
    }

    public void setTeachid(long teachid) {
        this.teachid = teachid;
    }

    @Column(name = "firstname", length = 150)
   public String getFistname() {
        return fistname;
    }

    public void setFistname(String fistname) {
        this.fistname = fistname;
    }

    @Column(name = "lastname", length = 150)
    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Column(name = "rate", length = 150)
    public String getRate() {
        return rate;
    }

    public void setRate(String rate) {
        this.rate = rate;
    }
}


Code:
    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

        String action="view";
        String code="-1";
        String error="";

        /*
         * Set Actions
         */
        boolean actionPerformed=false;
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements() && !actionPerformed){
           
            String s = (String)enumeration.nextElement();
           
            if( s.contains("btn_req_insert") ){
                command = new TeacherForm("","","","","","","","0","",false,"","");

                action="insert";
                code="-1";
                actionPerformed=true;
            }
            else if ( s.contains("btn_req_edit_")){
                try{
                    code=s.substring(13);//take the number after edit : edit_?????

                    UserAccount userAccount = userAccountFactory.getUserAccount(Long.valueOf(code));

                    ((TeacherForm)command).setActive(userAccount.getEnabled() == 1);
                    ((TeacherForm)command).setEmail(userAccount.getEmail());
                    ((TeacherForm)command).setFirstname(userAccount.getFirstname());
                    ((TeacherForm)command).setGroupCode(String.valueOf(userAccount.getGroup().getGroupcode()));
                    ((TeacherForm)command).setLastname(userAccount.getLastname());
                    ((TeacherForm)command).setMajorCode(userAccount.getMajor().getReshtecode());
                    ((TeacherForm)command).setPassword(userAccount.getPasswordHash());
                    ((TeacherForm)command).setPersonalCode(String.valueOf(userAccount.getStno()));
                    ((TeacherForm)command).setRole(userAccount.getRoleid());
                    ((TeacherForm)command).setSex(userAccount.getSex());
                    ((TeacherForm)command).setTel(userAccount.getPhone());
                    ((TeacherForm)command).setUsername(userAccount.getUsername());

                    action="edit";
                    actionPerformed=true;
                } catch (Exception ex){}
            }
            else if ( s.contains("btn_req_delete_")){
                action="prompt";
                code=s.substring(15);//take the number after delete : delete_?????
                actionPerformed=true;
            }
            else if(s.contains("btn_yes_delete_")){
                action="view";
                Long userID = Long.valueOf(s.substring(15));
                try{
                    UserAccount userAccount = userAccountFactory.getUserAccount(userID);

                    userAccountFactory.removeUserAccount(userAccount);
                }catch (Exception ex) {
                    error = ex.getMessage();
                }
                code="-1";
                actionPerformed=true;
            }
            else if(s.contains("btn_no_delete_")){
                action="view";
                code="-1";
                actionPerformed=true;
            }
            else if(s.contains("btn_do_cancel")){
                action="view";
                code="-1";
                actionPerformed=true;
            }
            else if(s.contains("btn_do_edit_")){
                //Add eidt codes
                try{
                    if(userAccountFactory.getUserAccount(Long.valueOf(((TeacherForm) command).getPersonalCode()))!=null)
                    {
                        UserAccount userAccount = userAccountFactory.getUserAccount(Long.valueOf(((TeacherForm) command).getPersonalCode()));
                        userAccount.setUsername(((TeacherForm)command).getUsername());
                        userAccount.setEmail(((TeacherForm)command).getEmail());
                        userAccount.setEnabled(((TeacherForm)command).isActive()?1:0);
                        userAccount.setFirstname(((TeacherForm)command).getFirstname());
                        userAccount.setLastname(((TeacherForm)command).getLastname());
                        userAccount.setGroup(new Group(Long.valueOf(((TeacherForm)command).getGroupCode())));
                        userAccount.setMajor(new Major(((TeacherForm)command).getMajorCode()));
                        userAccount.setPhone(((TeacherForm)command).getTel());
                        userAccount.setPasswordHash(((TeacherForm)command).getPassword());
                        userAccount.setRoleid(((TeacherForm)command).getRole());
                        userAccount.setSex(((TeacherForm)command).getSex());
                        userAccount.setStno(Long.valueOf(((TeacherForm) command).getPersonalCode()));
                        userAccount.setId(Long.valueOf(((TeacherForm) command).getPersonalCode()));
                        userAccountFactory.saveUserAccount(userAccount);
                    }
                }
                catch (Exception ignored){}
                action="view";
                code="-1";
               
                actionPerformed=true;
            }
            else if(s.contains("btn_do_insert_")){
                //Add InsertCodes
                try{
                    // If both user name and user ID are not exist then insert new user...
                    if(userAccountFactory.getUserAccount(Long.valueOf(((TeacherForm)command).getPersonalCode()))==null
                       && userAccountFactory.getUserAccountsByUsername(((TeacherForm)command).getUsername())==null)
                    {
                        UserAccount userAccount = new UserAccount();
                        userAccount.setUsername(((TeacherForm)command).getUsername());
                        userAccount.setEmail(((TeacherForm)command).getEmail());
                        userAccount.setEnabled(((TeacherForm)command).isActive()?1:0);
                        userAccount.setFirstname(((TeacherForm)command).getFirstname());
                        userAccount.setLastname(((TeacherForm)command).getLastname());
                        userAccount.setGroup(new Group(Long.valueOf(((TeacherForm)command).getGroupCode())));
                        userAccount.setMajor(new Major(((TeacherForm)command).getMajorCode()));
                        userAccount.setPhone(((TeacherForm)command).getTel());
                        userAccount.setPasswordHash(((TeacherForm)command).getPassword());
                        userAccount.setRoleid(((TeacherForm)command).getRole());
                        userAccount.setSex(((TeacherForm)command).getSex());
                        userAccount.setStno(Long.valueOf(((TeacherForm) command).getPersonalCode()));
                        userAccount.setId(Long.valueOf(((TeacherForm) command).getPersonalCode()));
                        userAccountFactory.saveUserAccount(userAccount);
                    }
                }
                catch (Exception ex){}
                action="view";
                code="-1";
               
                actionPerformed=true;
            }
        }

        // Base
        Map model = errors.getModel();

        ModelAndView mav = new ModelAndView(getSuccessView(), getCommandName(), command);
        mav.addAllObjects(errors.getModel());


        //Definitions
        List<UserAccount> teacherList = userAccountFactory.getUserAccountsByRoleid("" ,0 , UserAccountFactory.QueryAction.Or, "2", "3", "6");
        List<Major> majorList = (List<Major>)majorFactory.getMajors();
        List<Group> groupList = (List<Group>)groupFactory.getGroups();

        UserAccountFactory userAccountFactory2 = new UserAccountFactory();

        //Mapping

        mav.addObject("teacher_list", teacherList);
        mav.addObject("major_list", majorList);
        mav.addObject("group_list", groupList);
        mav.addObject("major_factory", majorFactory);

        if(!error.isEmpty()){
            mav.addObject("error_msg", error);
            error="";
        }

        //for finding edit/delete object
        if(!code.equals("-1")){
            try{
                UserAccount userAccount = userAccountFactory.getUserAccount(Long.valueOf(code));

                mav.addObject("teacher", userAccount);
                mav.addObject("user_account", userAccount);
                mav.addObject("code", code);

            }catch (Exception er){
                action="view";
            }
        }

        mav.addObject("action", action);
        return mav;
    }


Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
        "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>org.postgresql.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:postgresql://127.0.0.1:5432/trainee</value>
        </property>
        <property name="username">
            <value>postgres</value>
        </property>
        <property name="password">
            <value>postgres</value>
        </property>
    </bean>

    <!-- Hibernate SessionFactory -->

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">validate</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.bedkaco.portlets.certificate.model.Certificate</value>
                <value>com.bedkaco.portlets.description.model.Description</value>
                <value>com.bedkaco.portlets.determine_training_score.model.DetermineTrainingScore</value>
                <value>com.bedkaco.portlets.education_calendar.model.EducationCalendar</value>
                <value>com.bedkaco.portlets.exception_student.model.ExceptionStudent</value>
                <value>com.bedkaco.portlets.faq.model.Faq</value>
                <value>com.bedkaco.portlets.form1.model.Form1</value>
                <value>com.bedkaco.portlets.form1_details.model.Form1Details</value>
                <value>com.bedkaco.portlets.form2.model.Form2</value>
                <value>com.bedkaco.portlets.group.model.Group</value>
                <value>com.bedkaco.portlets.head_of_training_report.model.HeadOfTrainingReport</value>
                <value>com.bedkaco.portlets.log.model.Log</value>
                <value>com.bedkaco.portlets.major.model.Major</value>
                <value>com.bedkaco.portlets.opinion_offer.model.Opinionoffer</value>
                <value>com.bedkaco.portlets.preforme1.model.PreForm1</value>
                <value>com.bedkaco.portlets.report_file.model.Reportfile</value>
                <value>com.bedkaco.portlets.setting.model.Setting</value>
                <value>com.bedkaco.portlets.student.model.Student</value>
                <value>com.bedkaco.portlets.student_ready.model.StudentReady</value>
                <value>com.bedkaco.portlets.system_log.model.SystemLog</value>
                <value>com.bedkaco.portlets.teacher.model.Teacher</value>
                <value>com.bedkaco.portlets.user_account.model.UserAccount</value>
                <value>com.bedkaco.portlets.user_role.model.UserRole</value>
                <value>com.bedkaco.portlets.weekly_report.model.WeeklyReport</value>

            </list>
        </property>
    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="certificateDao" class="com.bedkaco.portlets.certificate.dao.CertificateDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="descriptionDao" class="com.bedkaco.portlets.description.dao.DescriptionDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="determineTrainingScoreDao" class="com.bedkaco.portlets.determine_training_score.dao.DetermineTrainingScoreDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="educationCalendarDao" class="com.bedkaco.portlets.education_calendar.dao.EducationCalendarDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="exceptionStudentDao" class="com.bedkaco.portlets.exception_student.dao.ExceptionStudentDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="faqDao" class="com.bedkaco.portlets.faq.dao.FaqDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="form1Dao" class="com.bedkaco.portlets.form1.dao.Form1Dao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="form1DetailsDao" class="com.bedkaco.portlets.form1_details.dao.Form1DetailsDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="form2Dao" class="com.bedkaco.portlets.form2.dao.Form2Dao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="groupDao" class="com.bedkaco.portlets.group.dao.GroupDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="headOfTrainingReportDao" class="com.bedkaco.portlets.head_of_training_report.dao.HeadOfTrainingReportDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="logDao" class="com.bedkaco.portlets.log.dao.LogDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="majorDao" class="com.bedkaco.portlets.major.dao.MajorDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="opinionofferDao" class="com.bedkaco.portlets.opinion_offer.dao.OpinionofferDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="preForm1Dao" class="com.bedkaco.portlets.preforme1.dao.PreForm1Dao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="reportfileDao" class="com.bedkaco.portlets.report_file.dao.ReportfileDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="settingDao" class="com.bedkaco.portlets.setting.dao.SettingDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="studentDao" class="com.bedkaco.portlets.student.dao.StudentDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="studentReadyDao" class="com.bedkaco.portlets.student_ready.dao.StudentReadyDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="systemLogDao" class="com.bedkaco.portlets.system_log.dao.SystemLogDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="teacherDao" class="com.bedkaco.portlets.teacher.dao.TeacherDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="userAccountDao" class="com.bedkaco.portlets.user_account.dao.UserAccountDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="userRoleDao" class="com.bedkaco.portlets.user_role.dao.UserRoleDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>

    <bean id="weeklyReportDao" class="com.bedkaco.portlets.weekly_report.dao.WeeklyReportDao">
        <property name="sessionFactory">
            <ref local="sessionFactory"/>
        </property>
    </bean>
</beans>


Code:
   <!-- Teachers List -->
    <bean name="/teachers_list.html" class="com.bedkaco.web.teachers_list.controller.TeachersListController">
        <property name="formView" value="teachers_list"/>
        <property name="successView" value="teachers_list"/>

        <property name="userAccountFactory">
            <bean class="com.bedkaco.portlets.user_account.factories.UserAccountFactory">
                <property name="userAccountDao" ref="userAccountDao"/>
            </bean>
        </property>
        <property name="majorFactory">
            <bean class="com.bedkaco.portlets.major.factories.MajorFactory">
                <property name="majorDao" ref="majorDao"/>
            </bean>
        </property>
        <property name="groupFactory">
            <bean class="com.bedkaco.portlets.group.factories.GroupFactory">
                <property name="groupDao" ref="groupDao"/>
            </bean>
        </property>
    </bean>


Top
 Profile  
 
 Post subject: Re: Hibernate query return single result after data insertation
PostPosted: Fri Mar 16, 2012 5:06 am 
Expert
Expert

Joined: Tue Jun 16, 2009 3:36 am
Posts: 990
Hi deadManN,

I don't know Spring very well,
but from what you are reporting, it seems that
HibernateTemplate by default does not flush before doing the actual query.
New persisted objects (= now yet commited) can only be seen by queries if preceeded by a (either exclicit or implicit) flush call.


Top
 Profile  
 
 Post subject: Re: Hibernate query return single result after data insertation
PostPosted: Fri Mar 16, 2012 10:56 am 
Newbie

Joined: Thu Mar 15, 2012 2:48 pm
Posts: 13
And i'm the one who dont know Hibernate well, i just using old data model, from an other project, and transfer the project from JSF Based Framework to Spring Based Framework...

i also tried using flush manualy, also refresh or some thing with alike name...

in my other classes it work well, so i think it may be caused with my model :|


Top
 Profile  
 
 Post subject: Re: Hibernate query return single result after data insertation
PostPosted: Sat Mar 17, 2012 3:14 am 
Newbie

Joined: Thu Mar 15, 2012 2:48 pm
Posts: 13
any one can help? (take the post to the top of list :D)


Top
 Profile  
 
 Post subject: Re: Hibernate query return single result after data insertation
PostPosted: Wed Mar 21, 2012 8:08 am 
Newbie

Joined: Thu Mar 15, 2012 2:48 pm
Posts: 13
i'm going vacation, i hope to see the answer till then i back


Top
 Profile  
 
 Post subject: Re: Hibernate query return single result after data insertation
PostPosted: Fri Mar 23, 2012 5:52 pm 
Newbie

Joined: Fri Mar 23, 2012 5:42 pm
Posts: 1
I have the same issue that you have. I'm using hiberante 3.3.2 + spring 3 + tomcat 6 and after upgrading from postgres 8.4 to postgres 9.1.3 I got this issue. I changed the jdbc version from 8.4 to 9.1, but I didn't fix the issue. Should I move to to hibernate 3.6?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.