5

I want to add some custom code to my greenDAO entities. I saw there is something like protected regions. But I don't like the idea to check in the generated classes to my git repository. I'd like to use inheritance for this.

i.e. I have an entity User. So I want greenDAO to generate a class called UserBase. This I want to extend by User and implement a method like this:

public String getFullName() {
    return this.first + " " + this.last;
}

Where first and last are managed properties.

But I have no idea how to tell greenDAO to use the class User instead of the generated entity UserBase. Is there any way to do this?

keineantwort
  • 873
  • 8
  • 15

2 Answers2

7

I found a way how to solve this:

you can enter a parent for each entity:

Entity user = schema.addEntity("User");
...
user.setSuperclass("UserBase");

So you can implement the UserBase as an abstract class.

public abstract class UserBase {

  public String getFullName() {
    return getFirst() + " " + getLast();
  }

  public abstract int getFirst();
  public abstract int getLast();
}

The disadvantage here is, that you have to declare the generated getters as abstract methods to access them.

keineantwort
  • 873
  • 8
  • 15
  • Thank you for posting this! I had the same exact issue and this is GOLD! I was struggling to extend my Dao as well until you posted this method. – AutoM8R Dec 05 '15 at 19:16
  • Thanks, this is a great solution. But for me I wanted to override an automatic getter and this superclass solution will not do it :-( – dowi May 22 '18 at 13:22
7

The common approach is to use "keep sections" in the generated entities. Keep sections allow to add members and methods directly in the generated entity. Check here for details: http://greendao-orm.com/documentation/modelling-entities/

Markus Junginger
  • 6,950
  • 31
  • 52
  • "Keep sections" or in MDD terms "protected regions" have several disadvantages: * you have to checkin the generated code into you vcs * you have to keep the code clean. somewhere has to be a signature for keep section. If you break this signature (like an accident or code formatting) you will loose you code – keineantwort Jun 29 '13 at 20:53