vico
vico

Reputation: 18171

Create Hibernate table index using Java code

I have Hibernate with SQLLight database in Java project. I use simple Java class to perform database actions:

public class Db
{
    private SessionFactory sessionFactory;
    private Session session;

private Db()
    {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    private void open()
    {
        session = sessionFactory.openSession();
        session.beginTransaction();
    }
...
}

Evrything works fine, but now I need to create index on one in my table fields - DocName.

CREATE TABLE [Doc] ( [Id] INTEGER PRIMARY KEY AUTOINCREMENT, [DocName] TEXT, [Job] TEXT)

I need to create index inside of my java code and apply it to existing database file. How to do this?

This should be done with java 1.4 .

Upvotes: 0

Views: 883

Answers (1)

Igoranze
Igoranze

Reputation: 1486

You should use Code First (here is a decent tutorial ).

Hibernate can run as a JPA provider. With JPA, which is similar to Entity Framework, you create POJOs and annotate their fields to provide directives to the JPA provider about how to handle persistence.

In code this would look like this in your DAO:

@Id // @Id indicates that this it a unique primary key
@GeneratedValue // @GeneratedValue indicates that value is automatically generated by the server
private Long id;

@Column(length = 255) // the optional @Column allows us makes sure that the name is limited to a suitable size and is unique
private String docName;

@Column(length = 255)
private String job;

To index docName, you need to add a Index via annotation to the DAO: More info

@Table(name = "Doc", indexes = { @Index("docName")})
@Entity
class Doc{
      @Index(docName = "docName")
      private String docName;

}

Upvotes: 1

Related Questions