Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom code generation for JPA entities from database

Tags:

java

jpa

entity

I'm here asking for a simple way to add some custom code in the JPA Entity generated by Eclipse from database.

Basically what I want to achieve is to add public String properties containing the names of the entity properties, and use them when I need to provide "property name" as String and be sure that there won't be runtime access errors.

Something like this

@Entity
@Table(name="clients")
@NamedQuery(name="ClientModel.findAll", query="SELECT c FROM ClientModel c")
public class ClientModel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="id_client")
    private long idClient;

    public String name;

    public ClienteModel() {
    }

    public long getIdClient() {
        return this.idClient;
    }

    public void setIdClient(long idClient) {
        this.idClient = idClient;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //CUSTOM CODE
    public static final String idClientProperty = "idClient";
    public static final String nameProperty = "name";
}

So i could use property name like

ClientModel.nameProperty

and be compile-time safe of his existence and in case of names refactoring after a further entity generation.

I'm aware of the existence of Telosys Tools & co., but I hoped there could be something simplier/faster (like a custom class provided as plugin in WSDL_to_entity generation with JAXB)

Thank you.

like image 751
MarcelloGarini Avatar asked Oct 30 '14 10:10

MarcelloGarini


People also ask

How eclipse generate entities from an existing database using JPA?

Right-click the JPA project in the Project Explorer and select JPA Tools > Generate Entities from Tables. On the Select Tables page of the Generate Entities from Tables wizard, select your database connection and schema. To create a new database connection, click Add connection.

Can we create JPA entity without @ID?

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it.


1 Answers

In the end I've used Telosys Tools, even if I didn't want to add another tool to my project, Is kinda easy to set up, just read here https://sites.google.com/site/telosystools/getting-started/21-configure-a-project

In my specific case i've added to the template "JPA_bean_with_links" this code during getters creation

#if ( $field.getter )    public static String ${field.getter}Property() {
        return "$field.name";
    }
#end
like image 115
MarcelloGarini Avatar answered Sep 30 '22 12:09

MarcelloGarini