开发者

No Hibernate Exception on the same insert of data

开发者 https://www.devze.com 2023-01-31 21:48 出处:网络
Hibernate Newbiehere.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.

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) {
            开发者_Python百科// 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?


Lets assume that booknumber is the primary key, I hope you mention it as a primary key.Then in the createBook() method you started very well but you use session.saveOrUpdate(bookObj); statement. Because of this you are not getting any kind of key violation exception. While saving it is looking for the record if it is not present then it will save it in db but if it is present then it will update that record and hence you wont receive any kind of exception. Instead of that if you use session.save(bookObj); statement then it will definitely give you primary key exception if you define primary key properly.


You need to publish more info like the primary key of the table book. You will not get a Hibernate Exception when using saveOrUpdate unless you modify the primary key value of the already saved object.

0

精彩评论

暂无评论...
验证码 换一张
取 消