我對休眠真的很陌生,并試圖了解它是如何作業的。但知道我面臨著這個問題。
首先,我有這樣的映射:
@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 不支持 annotation 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
&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,我在其中呼叫休眠函式:
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 并且資料庫中沒有物體:
如果您知道,可能是什么問題,請告訴我。我真的很感激!
uj5u.com熱心網友回復:
我認為原因是缺少 id 的設定器:
public long setId(long id) {
this.id = id;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508211.html
下一篇:在SQL中映射列值