Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hibernate doesn't save entity

I’m really new to hibernate and try to understand how it works. But know I faced with the problem.

First of all, I have such mapping:

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;

    public Author() {
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

But then, when I tried to save this entitye with session.save(), hibernate showed me error like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "author" violates not-null constraint
 Failing row contains (null, hello!).

So I decided to notice, why hibernate doesn’t increment the id automaticy and recognized that POSTGRESQL doesn’t suppert annotation GenerationType.IDENTITY. So I changet it to the GenerationType.SEQUENCE. The error was gone, but entity wasn’t saved.

So here’s hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.url">jdbc:postgresql://localhost:5432/hibernate?useSSL=false
      &amp;serverTimezone=UTC</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">4122</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="hibernate.entity.Author"/>
    <!-- DB schema will be updated if needed -->
    <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
  </session-factory>
</hibernate-configuration>

Here’s HibernateUtil.java

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    private static SessionFactory buildSessionFactory() {
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
                .build();
        SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
        return sessionFactoryBuilder.build();
    }
    public static SessionFactory getSessionFactory() {
        if(sessionFactory == null) {
            sessionFactory = buildSessionFactory();
        }
        return sessionFactory;
    }
}

And here’s the Main.java, where I call the hibernate functions:

public class Main {
    public static void main(String[] args) {
        try(Session session = HibernateUtil.getSessionFactory().openSession()) {
            Transaction tx = session.beginTransaction();
            Author author = new Author();
            author.setName("hello!");
            session.save(author);
            tx.commit();
            System.out.println(session.get(Author.class, 1L));
        }
    }
}

After program execution it prints me null and there is no entity in database:

enter image description here

If you know, what can be the problem, please tell me. I’d really apreciate it!

>Solution :

I think the reason is setter for id missing:

public long setId(long id) {
    this.id = id;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading