0

This is my model class.Here we are using setters and getters methods to initialize variables:

package org.koushik.javabrains.dto;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id 
    private int userId;
    private String userName;
    public int getUserId() {
         return userId;
    }
    public void setUserId(int userId) {
         this.userId = userId;
    }
    public String getUserName() {
            return userName;
    }
    public void setUserName(String userName) {
            this.userName = userName;
    }    
}

This is my model object and assigning values to the variables created in model class:

package org.koushik.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
//import org.hibernate.Transaction;
import org.koushik.javabrains.dto.UserDetails;

public class HibernateTest {
    public static void main(String arg[])
    {
        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("First User");

        SessionFactory sessionFactory = new Configuration().configure()
                                        .buildSessionFactory();
        Session session = sessionFactory.openSession();

        session.beginTransaction();
        session.save(user);
        session.beginTransaction().commit();
    }
}
1
  • What exactly is your question? Commented Jun 18, 2014 at 3:43

2 Answers 2

2

Replace

session.beginTransaction().commit(); 

with

session.getTransaction().commit();

Note using Spring's @Transactional would remove the need to manage the transactions yourself

Sign up to request clarification or add additional context in comments.

Comments

0

you are trying to begin transaction within a transaction by calling begin transaction

while committing again, this causes above exception.

and message clearly says nested transaction is not supported.

so

create single transaction for a session like below and use the same thorough out your session

Transaction tx = session.beginTransaction();

session.save(user);

tx.commit();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.