No Hibernate Exception on the same insert of data

Posted by Mark Estrada on Stack Overflow See other posts from Stack Overflow or by Mark Estrada
Published on 2010-12-24T11:16:54Z Indexed on 2010/12/25 10:54 UTC
Read the original article Hit count: 274

Filed under:
|
|

Hi All,

Hibernate Newbie here. I am quite unsure why I am not getting any exception when I am executing below code. On first attempt, this code creates the Book Entry on my Book Table. But my concern is that when I execute below code again, no error was pop out by Hibernate. I was in fact expecting some sort of Violation of Primary Key Constraints as what I have bee doing in JDBC code.

public class BookDao {
    public void createBook(Book bookObj) {
        Session session = HibernateUtil.getSessionFactory()
                .getCurrentSession();
        session.beginTransaction();
        session.saveOrUpdate(bookObj);
        session.getTransaction().commit();
    }
}

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

public class BookDBStarter {
    public static void main(String[] args) {
        Book bookHF = new Book();
        bookHF.setIsbn("HF-12345");
        bookHF.setName("Head First HTML");
        bookHF.setPublishDate(new Date());

        BookDao daoBook = new BookDao();
        daoBook.createBook(bookHF);
    }
}

Is this normal hibernate way? And how will I know if my insert is successful? Any thoughts?

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate