hibernate 休眠不保存实体

htrmnn0y  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(144)

我对休眠还是个新手,并试图理解它是如何工作的。但我知道我面临着这个问题。
首先,我有这样的Map:

@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;
    }
}

但是,当我尝试用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!).

所以我决定注意,为什么Hibernate不自动递增id,并认识到PostgreSQL不支持注解GenerationType.IDENTITY。所以我把它改为GenerationType.SEQUENCE。错误已消失,但实体未保存。
下面是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>

以下是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;
    }
}

下面是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));
        }
    }
}

程序执行后,它输出NULL,并且数据库中没有实体:

如果你知道,会有什么问题,请告诉我。我真的会感激它的!

pn9klfpd

pn9klfpd1#

我认为ID丢失的原因是:

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

相关问题