如何在 hibernate.cfg.xml 中连接 postgresql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25279423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:34:49  来源:igfitidea点击:

How to connect postgresql in hibernate.cfg.xml

javadatabasespringhibernatepostgresql

提问by user3819470

I am trying to insert some data into postgresql through hibernate. However, there are not much tutorial about configurate hibernate with postgresql (I know, it should be similar to mysql =))

我正在尝试通过休眠将一些数据插入到 postgresql 中。但是,关于使用postgresql配置hibernate的教程并不多(我知道,它应该类似于mysql =))

src/main/resources/hibernate.cfg.xml

src/main/resources/hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://127.0.0.1:5432/myDatabase</property>
<property name="connection.username">myUser</property>
<property name="connection.password">myPassword</property>

<!-- JDBC connection pool (use the build-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

<!-- thread is the short name for org.hibernate.context.ThreadLocalSessionContext -->
<property name="current_session_context_class">thread</property>

<!-- Set "true" to show SQL statements -->
<property name="hibernate.show_sql">true</property>

<!-- mapping class using annotation -->
<mapping class="com.hib.entities.Student"></mapping>
</session-factory>

</hibernate-configuration>

src/main/java/

源代码/主/Java/

package com.hib.init;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Hibernateutil {
private static final SessionFactory sessionF;
private static final ServiceRegistry serviceR;

static {
    Configuration conf = new Configuration();
    conf.configure();
    System.out.println("Begin");
    serviceR = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
    System.out.println("Ready???");
    try {
        sessionF = conf.buildSessionFactory(serviceR);
        System.out.println("Success??");
    }catch(Exception e) {
        throw new ExceptionInInitializerError(e);
    }
}

public static SessionFactory getSeeionFactory() {
    return sessionF;
}
}

src/main/java package com.hib.entities;

src/main/java 包 com.hib.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Student {

@Id
@GeneratedValue
private Integer id;
private String firstName;

private Integer age;

public Student() {}

public Student(Integer id, String firstName, Integer age) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.age = age;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}   
}

src/main/java

源代码/主/Java

package com.hib.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hib.entities.Student;
import com.hib.init.Hibernateutil;

public class DemoFirst {

public static void main(String[] args) {
    SessionFactory sessionFactory = Hibernateutil.getSeeionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Student student = new Student();
    student.setFirstName("Bob");
    student.setAge(26);

    session.save(student);
    session.getTransaction().commit();

    session.close();
}
}

And this is the error I got :

这是我得到的错误:

Success??
Hibernate: select nextval ('hibernate_sequence')
Aug 12, 2014 11:01:10 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42P01
Aug 12, 2014 11:01:10 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: relation "hibernate_sequence" does not exist
Position: 17
Exception in thread "main" org.hibernate.exception.SQLGrammarException: ERROR: relation        "hibernate_sequence" does not exist
Position: 17
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy9.executeQuery(Unknown Source)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:123)
at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:116)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:642)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:635)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:631)
at com.hib.demo.DemoFirst.main(DemoFirst.java:20)


Caused by: org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
Position: 17
at    org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2062)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1795)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:479)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:367)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:271)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 14 more

pom.xml

pom.xml

 <dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>8.4-701.jdbc4</version>
</dependency>

采纳答案by Michael Zhavzharov

According to thisthread you must set your Id annotation as follows:

根据线程,您必须按如下方式设置您的 Id 注释:

@GeneratedValue(strategy = GenerationType.IDENTITY)

回答by Vlad Mihalcea

You forgot to add the DDL auto generation property. You can use any of the following settings:

您忘记添加 DDL 自动生成属性。您可以使用以下任何设置:

<property name="hibernate.hbm2ddl.auto" value="update">
<property name="hibernate.hbm2ddl.auto" value="create">
<property name="hibernate.hbm2ddl.auto" value="create-drop">
  1. updateis going to create and then simply update the DDL schema
  2. createis going to create the schema if it doesn't exist
  3. create-dropwill create the schema when the SessionFactory is initialized and destroyit when the SessionFactory is destroyed. This is useful during integration testing.
  1. update将创建然后简单地更新 DDL 模式
  2. 创造是要创建模式,如果它不存在
  3. create-drop将在 SessionFactory 初始化时创建模式,并在 SessionFactory销毁销毁它。这在集成测试期间很有用。

回答by Cortwave

You should make mapping beetwen table-entity class, column- field. For example (table and columns should exist) :

您应该映射甜菜表-实体类,列-字段。例如(表和列应该存在):

@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue
@Column(name = "id")
private Integer id;

@Column(name = "first_name")
private String firstName;

@Column(name = "age")
private Integer age;

回答by Mayur Gupta

Because you are using @GeneratedValue()

因为您正在使用 @GeneratedValue()

It will look for how the database that you are using generates ids. For MySql or HSQSL, there are increment fields that automatically increment. In Postgres or Oracle, they use sequence tables. Since you didn't specify a sequence table name, it will look for a sequence table named hibernate_sequence and use it for default. So you probably don't have such a sequence table in your database and now you get that error.

它将查找您正在使用的数据库如何生成 id。对于 MySql 或 HSQSL,有自动递增的递增字段。在 Postgres 或 Oracle 中,它们使用序列表。由于您没有指定序列表名称,它将查找名为 hibernate_sequence 的序列表并将其用作默认值。所以你的数据库中可能没有这样的序列表,现在你得到了那个错误。

Either add a hibernate_sequence like

添加一个 hibernate_sequence 像

@GeneratedValue(strategy=SEQUENCE)

or your own sequence table and use the annotations to name your sequence table that you have like

或您自己的序列表并使用注释来命名您喜欢的序列表

@GeneratedValue(strategy=SEQUENCE, generator="student_id_seq") 

Hope that helps

希望有帮助

回答by Nilesh Jadav

Connect to Postgresql by Hibernate -> configuration in hibernate.cfg.xml would be :

通过 Hibernate 连接到 Postgresql -> hibernate.cfg.xml 中的配置将是:

<session-factory>

    <!-- SQL dialect -->
    <!-- <property name="dialect">org.hibernate.dialect.H2Dialect</property> -->

    <!-- Database connection settings -->

    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/db_name</property>
    <property name="connection.username">username</property>
    <property name="connection.password">db_assword</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>


    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>
    <!-- <property name="hbm2ddl.auto">validate</property> -->

    <!-- The mapping information of entities -->
    <!-- <mapping class="hibernate_example.envers.Book" /> -->
    <!-- <mapping class="hibernate_example.envers.Student" /> -->
    <!-- <mapping class="hibernate_example.envers.AuditEntity" /> -->


</session-factory>

回答by Scott

Your id should look like:

您的 ID 应如下所示:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_id_gen")
@SequenceGenerator(name = "my_id_gen", sequenceName = "my_id_seq")
private Long id;

The sequenceName property should refer to the proper sequence in your database. If you created the column as sequence type, then it should be tableName_columnName_seq.

sequenceName 属性应指代数据库中的正确序列。如果您将列创建为序列类型,那么它应该是 tableName_columnName_seq。