Auto increment in FLUENT Nhibernate and PostgreSQL

Hai, I'm new to Fluent Nhibernate.

I have a PostgreSQL database and I want to create an auto-incremented generated identifier. I have not seen an automatic function increment in PostgreSQL, and I understand that in order to use automatic increment in PostgreSQL, I have to create a sequence.

Is there any other way besides the sequence?

If this create sequenceis the only way, can you tell me how to display it? I tried using this and was not successful:

mapping.Id(x => x.Id, "id").GeneratedBy.Sequence("hibernate-sequence");

I created hibernate-sequencebefore using it.

Hi

+3
source share
3 answers

Strange, but with your code, the insert works fine if you call Save(Object)insteadSaveOrUpdate(Object)

Edit # 1

What worked for me.

Entity:

public class Human
{
    public virtual int ID { get; set; }
    public virtual string Name { get; set; }
}

public class HumanMap : ClassMap<Human>
{
    public HumanMap()
    {
        this.Id(x => x.ID).CustomSqlType("Serial").GeneratedBy.Native();
        this.Map(x => x.Name);
    }
}

And configuration with export schema:

static ISessionFactory CreateSF()
{
    return Fluently
    .Configure()
    .Database(PostgreSQLConfiguration.Standard.ConnectionString("Server=127.0.0.1;Port=5432;Database=fnhtest;User=postgres;Password=password"))
    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
    .ExposeConfiguration(cfg => { new SchemaExport(cfg).Create(false, true); })
    .BuildSessionFactory(); 
}
+5
source

I have not seen auto-increment functions in PostgreSQL

This data type is SERIAL, mentioned by Frank.



Just create this class as SERIAL, and you have an auto-increment column:

CREATE TABLE the_table (
  id serial not null primary key,
  other_column varchar (20), 
  ...
);

Then you will need to annotate these columns as "auto-increment" in Hibernate (since I do not use Hibernate, I can’t tell how exactly this is done).

+1
source
0

Source: https://habr.com/ru/post/1768204/


All Articles