'How to insert data into the database using spring + hibernate?

see i m havving user.java for the user info.

@Entity(name = "user")
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id")
    private String id;  
    @Column(name = "password")
    private String password;
//getter and setter for this..
}

this is my userdao

public class UserDao {
    public interface UserDAO {
        public String insert(User user);

    }
}

and this is the impl class for inserting into database see this was my code.please check it and tell me what i m doing wrong

@Repository
@Transactional
public class UserImpl implements UserDAO {

    private DataSource dataSource;

    @Autowired
    SessionFactory sessionFactory;
    @Resource(name = "sessionFactory")
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public String insert(User use) {

        Session session = this.sessionFactory.openSession();
        try{

            Session sess = this.sessionFactory.getCurrentSession();              
            session.save(reg);


                        return (String)user.getUserName(); 
                        }catch(Exception e){
                            System.out.println("in catch"+e.getMessage());
                            e.printStackTrace();

    }

    }
}




} 

and in my controller after successful registration i m inserting data to the database by this

 userDao.insert(user);

but i m not getting output means not any data is inserting into the database.why this..? this is my mvc configuration

<context:component-scan base-package="com.user.xyz" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/images/, /resources/css/" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />

    </bean>


Solution 1:[1]

Remember this: You don't have any exist session, but you use getCurrentSession(). To use this method, you must have a session already. try this:

Session session = this.sessionFactory.openSession();

Now you had a session for your transaction.

You should declare sessionFactory in an xml file (hibernate.xml or spring.xml), then use @Autowire to get it and open new session.

Solution 2:[2]

You have 2 choices:

A. force hibernate to flush any changes you have made in session:

session.save(user);
session.flush();

B. make whole method run in transaction - this is much better of course. When transaction is commited - hibernate will flush any changes to database just if you would do manually.

for example:

Transaction tx = null;

try {

  session.beginTransaction();

  session.save(user);
  ....

  tx.commit();

} catch (RuntimeException e) {
  tx.rollback();
  throw e;
}

Solution 3:[3]

If you have multiple DAO calls in a single request, then session.getCurrentSession() is useful, but I guess that is not your case. If there is only a single DAO call per request then session.openSession() is the right way.

Take care that when using session.openSession(), you also have to close your session afterwards.

The best thing to do is open a session for each incoming request (using a filter is the easiest way to do this) and then calling sessionFactory.getCurrentSession() in all your DAOs to get the current session. I guess your problem is you didn't specify the filter. That way all your DAOs will be easily reusable and you don't need to close your session afterwards.

You can found more information in the docs: Hibernate documentation

Solution 4:[4]

I have also faced the same issue, and got the solution. For now check below points-

  1. Check for appropriate jar files you are using
  2. Check for manifest.mf in META-INF folder for application info.
  3. Check your hibernate configuration in configuration file for hibernate template configuration.
  4. At last if everything is OK then use session.flush() before insert.

    Session session = sessionFactory.openSession();
     Transaction tx = session.beginTransaction();
        {
           {
                //... your logic
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
            }
        }
    
    tx.commit();
    session.close()
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phong Nguyen
Solution 2 przemek hertel
Solution 3 Mathias G.
Solution 4 Sai prateek