How can I create a table using hibernation in a specific sequence of columns?

I am using Hibernate to create a hibernate ORM tool in my project that automatically generates a dabase using my POJO class, but the generated table has a sequence of columns in sorted order. How can I create the table in the same order in which sequence I have defined the attributes in my Pojo class.

For example: If I have defined three attributes in the pojo class:

String  id ,name , address;

      

The generated table will have a sequence of columns: address, identifier, name. I want to have the same sequence of columns as: id, name, address in my database. How can i do this?

+3


source to share


2 answers


Your code should never depend on the ordering of columns in the database. There is actually technically no guarantee that the columns will be returned in a specific order when you SELECT *

. If you need columns in a specific order, specify it in SQL query

.



The hibernate command says this is a known limitation and cannot be ordered. But you shouldn't rely on hbm2ddl

when used Hibernate

in production, it is a rather limited thing, for example it can add a column but cannot remove it.

+5


source


Save the sequence of 3 items to achieve the desired order.


  • Attributes in Pojo
  • Their recipients and setters
  • Their entries in the hbm.xml file

Note . Make sure you are dropping the table before running the application to create a new table.

If any of these sequences are not supported, hibernation will create columns in alphabetical order.



In your case - for POJO

String  id ; //1st attribute 
String  name; //2nd  attribute 
String  address; //3rd attribute 


public String getId() //1st attribute getter 
{
    return id;
}

public void setId(String id) //1st attribute setter
{
    this.id = id;
}

public String getName() //2st attribute getter
{
    return name;
}
public void setName(String name) //2st attribute setter
{
    this.name = name;
}

public String getAddress() //3st attribute getter
{
    return address;
}
public void setAddress(String address) //3st attribute getter
{
    this.address = address;
}

      

In the ClassName.hbm.xml file

<property name="id" column="id" type="java.lang.String" length="20" />
<property name="name" column="name" type="java.lang.String" length="50"/>
<property name="address" column="address" type="java.sql.String" length="50"/>

      

-1


source







All Articles