简体   繁体   中英

Hibernate generate pk ID using naming strategy

I'm using Hibernate JPA. I'd like to extend a base class containing my pk generator and some hash equals code, however my company is using table_name_id to describe ID's in the physical database making this seemingly impossible. I was just told I could use hibernates naming strategy to dynamically prefix the table name to my variable, however I haven't found a good example illustrating how to accomplish this. Would someone be able to point me to some example code or documentation on how to achieve this.

superclass

@MappedSuperclass
public abstract class Base implements Serializable {

    @Id
    @GeneratedValue(strategy = AUTO)
    @Column(name="ID", nullable = false)
    private Integer id;

    ....
}

Subclass A

@Entity
@Table(name="TABLE_A")
public class TableA extends Base {
// physical model needs base pk id to be prefixed with table_a resulting in table_a_id.
...
}

Subclass B

@Entity
@Table(name="TABLE_B")
public class TableB extends Base {
// physical model needs base pk id to be prefixed with table_b resulting in table_b_id.
...
}

I just do exactly the same thing which ensures that the generated column name for all PKs will have the format tablename_id .

By default when using hibernate in JPA mode , it uses EJB3NamingStrategy as its default naming strategy.By creating the following custom NamingStrategy which extending EJB3NamingStrategy , you can change the naming strategy for the primary key only and keep other naming strategies specified by the JPA standard remain unchanged.

public class CustomNamingStrategy extends EJB3NamingStrategy {

    private static final long serialVersionUID = -1953826881322136108L;
    private String currentTableName;

    public String propertyToColumnName(String propertyName) {

        if (propertyName.equalsIgnoreCase("id")) {
            return currentTableName + "_id";
        } else {
            return StringHelper.unqualify(propertyName);
        }
    }

    public String tableName(String tableName) {
        currentTableName = tableName;
        return tableName;
    }
}

Please note that you have to remove @Column(name="ID") from all of your @Entity such that hibernate will use the custom NamingStrategy to generate the column name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM