Mochamad Fazar
Mochamad Fazar

Reputation: 45

Auto Increment in FLuent Nhibernate and PostgreSQL

I`m a newbie in Fluent Nhibernate.

I have a PostgreSQL database and what I want is a generated id with auto increment. I have not seen feature auto increment in PostgreSQL and I understand that to use auto increment in PostgreSQL I have to create a sequence.

Is there another way besides sequences?

If create sequence is the only way, can you tell me how I should mapping it? I tried to use this and had no success:

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

I have created hibernate-sequence before using it.

Regards

Upvotes: 3

Views: 5166

Answers (3)

Dmitriy
Dmitriy

Reputation: 1972

Strange, but with your code an insertion works fine, if you call Save(Object) instead of SaveOrUpdate(Object)

Edit #1

That's 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 schema export:

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(); 
}

Upvotes: 6

user330315
user330315

Reputation:

I have not seen feature auto increment in PostgreSQL

That's the SERIAL datatype mentioned by Frank.



Just create the colum in question 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 need to annotate that columns as an "auto increment" in Hibernate (as I don't use Hibernate, I can't tell you how exactly that is done).

Upvotes: 1

Frank Heikens
Frank Heikens

Reputation: 126991

Just use the datatype SERIAL.

Upvotes: 0

Related Questions