简体   繁体   English

Hibernate 不保存实体

[英]Hibernate doesn't save entity

I'm really new to hibernate and try to understand how it works.我对 hibernate 真的很陌生,并尝试了解它是如何工作的。 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但是,当我尝试用session.save()保存这个实体时, hibernate 向我显示了类似的错误

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 .所以我决定注意,为什么 hibernate 不自动增加 id 并认识到 POSTGRESQL 不支持注释GenerationType.IDENTITY So I changet it to the GenerationType.SEQUENCE .所以我将其更改为GenerationType.SEQUENCE The error was gone, but entity wasn't saved.错误消失了,但实体没有保存。

So here's hibernate.cfg.xml所以这里是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这是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:这是Main.java ,我在这里调用 hibernate 函数:

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:程序执行后,它打印出我 null 并且数据库中没有实体:

在此处输入图像描述

If you know, what can be the problem, please tell me.如果您知道,可能是什么问题,请告诉我。 I'd really apreciate it!我真的很感激!

I think the reason is setter for id missing:我认为原因是缺少 id 的设置器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM