Announcement Announcement Module
Collapse
No announcement yet.
Hibernate return value after insert Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate return value after insert

    I was under the impression there was a way to get a return value after using one of the getHibernateTemplate() functions that inserts an object in the db. What I'd like is the id of the row that was just updated. I could have sworn I saw an example that you didn't need to do a find() after the saveOrUpdate() to get the object, or was I just dreaming that?

  • #2
    I finally figured out where I saw the code from. This is from Spring Live:


    in the user manager:

    Code:
    public User saveUser(User user){
        dao.saveUser(user);
        return user;
    }
    in the user DAO:
    Code:
    public void saveUser(User user){
        getHibernateTemplate().saveOrUpdate(user);
    }
    Lets assume that the id for the user isn't set before it gets inserted into the db (because it's an auto-increment)...My question is, if I were to call the manager's saveUser, and it returned a User object, if I were to call user.getId(), would that be the id that was generated in hibernate or is it null?

    Comment


    • #3
      After you call saveUser, the user instance you passed in becomes a database object, i.e., from transient to persistent - so, yes, you can directly access user.getUserId() and get the id value.

      Comment


      • #4
        To answer the first part of your question. If you call getHibernateTemplate().save(user) the return value will be the id hibernate used to save the object.

        Comment


        • #5
          thanks guys

          Comment


          • #6
            Hiya guys,
            I'm having a similar problem in my app with getting a return Id after an insert. I'm very new to Hibernate, so the problem is probably quite simple to solve, I just can't seem to work it out.

            My test code is:

            Code:
            Flight flight = new Flight();
            flight.setAirline("Tullamarine");
            flight.setAirportFrom("Melbourne");
            flight.setAirportTo("Singapore");
            flight.setDateTimeFrom(DateUtils.parseIso8601DateTime("2006-10-10T18:00:00"));
            flight.setDateTimeTo(DateUtils.parseIso8601DateTime("2006-10-11T18:00:00"));
            flightDao.save(flight);
            int id = flight.getFlightId();
            My DAO code is:
            Code:
            getHibernateTemplate().saveOrUpdate(flight);
            I'm using annotations in my entity bean. Annotations:
            Code:
            @Id
            @Column(name="flightId", unique=true, nullable=false, insertable=true, updatable=true)
            private int flightId;
            I'm using MySQL and spring 2, Hibernate 3.2
            The save is going back to the database properly, but when I check the id after the save, it is zero. Any help would be greatly appreciated.

            Cheers,
            Ben

            Comment


            • #7
              I know this might seem like a stupid question, but is zero the wrong answer? If its the first entry then zero could be fine. Regardless paste your class and hbm code and we can have a look.

              Comment


              • #8
                The autoincrement field is above zero I've run the test a few times, and keeps on inserting, the id in the db is above zero, but the returned id when I check it in the test is always zero.

                My dao.xml is::

                Code:
                <beans>
                    <import resource="applicationContext-hibernate.xml"/>
                    
                	<bean id="customerDao" class="com.ozwake.travel.dao.CustomerDao">
                		<property name="sessionFactory" ref="sessionFactory"/>
                	</bean>
                	<bean id="flightDao" class="com.ozwake.travel.dao.FlightDao">
                		<property name="sessionFactory" ref="sessionFactory"/>
                	</bean>
                	<bean id="newsItemDao" class="com.ozwake.travel.dao.NewsItemDao">
                		<property name="sessionFactory" ref="sessionFactory"/>
                	</bean>
                </beans>
                And my applicationContext-hibernate.xml is:

                Code:
                <beans>
                	<bean id="travelRiseDataSource"
                		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                		<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
                		<property name="url"><value>jdbc:mysql://localhost:3307/test</value></property>
                		<property name="username" value="root"/>
                		<property name="password" value="xxxx"/>
                	</bean>
                
                	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
                		<property name="dataSource" ref="travelRiseDataSource"/>
                		<property name="hibernateProperties">
                			<props>
                				<prop key="hibernate.connection.pool_size">0</prop>
                				<prop key="hibernate.show_sql">true</prop>
                				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>			
                			</props>
                		</property>
                		<property name="annotatedClasses">
                			<list>
                				<value>com.ozwake.travel.model.Customer</value>
                				<value>com.ozwake.travel.model.Flight</value>
                				<value>com.ozwake.travel.model.NewsItem</value>
                			</list>
                		</property>
                	</bean>
                </beans>
                I'm not using any hibernate config, just spring and annotations.
                Thanks!

                Comment


                • #9
                  What about the code for the actual domain object? Flight or whatever it was called.

                  Comment


                  • #10
                    The code for the model object Flight.java is:

                    Code:
                    package com.ozwake.travel.model;
                    
                    import java.util.Date;
                    import javax.persistence.Column;
                    import javax.persistence.Entity;
                    import javax.persistence.Id;
                    import javax.persistence.Table;
                    
                    @Entity
                    @Table(name="flights"
                        ,catalog="test"
                    , uniqueConstraints = {  }
                    )
                    
                    public class Flight  implements java.io.Serializable {
                    @Id
                    @Column(name="flightId", unique=true, nullable=false, insertable=true, updatable=true)
                    private int flightId;
                     
                    @Column(name="airportFrom", unique=false, nullable=false, insertable=true, updatable=true, length=45)
                    private String airportFrom;
                     
                    @Column(name="airportTo", unique=false, nullable=false, insertable=true, updatable=true, length=45)	 
                    private String airportTo;
                     
                    @Column(name="dateTimeFrom", unique=false, nullable=false, insertable=true, updatable=true, length=19)	 
                    private Date dateTimeFrom;
                     
                    @Column(name="dateTimeTo", unique=false, nullable=false, insertable=true, updatable=true, length=19)     
                    private Date dateTimeTo;
                     
                    @Column(name="airline", unique=false, nullable=false, insertable=true, updatable=true, length=45)     
                    private String airline;
                    
                    
                        public Flight() {
                        }
                    
                        public Flight(int flightId, String airportFrom, String airportTo, Date dateTimeFrom, Date dateTimeTo, String airline) {
                            this.flightId = flightId;
                            this.airportFrom = airportFrom;
                            this.airportTo = airportTo;
                            this.dateTimeFrom = dateTimeFrom;
                            this.dateTimeTo = dateTimeTo;
                            this.airline = airline;
                        }
                       
                     
                        public int getFlightId() {
                            return this.flightId;
                        }
                        
                        public void setFlightId(int flightId) {
                            this.flightId = flightId;
                        }
                        
                        public String getAirportFrom() {
                            return this.airportFrom;
                        }
                        
                        public void setAirportFrom(String airportFrom) {
                            this.airportFrom = airportFrom;
                        }
                    
                    
                        public String getAirportTo() {
                            return this.airportTo;
                        }
                        
                        public void setAirportTo(String airportTo) {
                            this.airportTo = airportTo;
                        }
                    
                    
                        public Date getDateTimeFrom() {
                            return this.dateTimeFrom;
                        }
                        
                        public void setDateTimeFrom(Date dateTimeFrom) {
                            this.dateTimeFrom = dateTimeFrom;
                        }
                    
                    
                        public Date getDateTimeTo() {
                            return this.dateTimeTo;
                        }
                        
                        public void setDateTimeTo(Date dateTimeTo) {
                            this.dateTimeTo = dateTimeTo;
                        }
                    
                    
                        public String getAirline() {
                            return this.airline;
                        }
                        
                        public void setAirline(String airline) {
                            this.airline = airline;
                        }
                      
                    }

                    Comment


                    • #11
                      Ok, fixed the problem. The id in my table was an autoincrement field. I specified that the id should be an IDENTITY and it worked. Hibernate started populating the Id field after a save. Annotations now looks like this.

                      Code:
                      @Id
                      @GeneratedValue(strategy=GenerationType.IDENTITY)	
                      @Column(name="flightId", unique=true, nullable=false, insertable=true, updatable=true)
                      private int flightId;
                      Thanks for your responses Karl.

                      Comment

                      Working...
                      X