Question

I'm new to the API. It appears to me that you have to construct objects via the 'context' object like this:

ServerRuntime cayenneRuntime = new ServerRuntime("cayenne-project.xml");
context = cayenneRuntime.newContext() 
...
MyEntity entity=context.newObject(MyEntity.class);

Rather than just creating Java Objects in the usual new() way:

MyEntity entity=new MyEntity();

But I want to create a constructor for my 'MyEntity' class that would do something like:

public MyEntity(String inputFile) {
...
do setters based on information derived from inputFile (size, time created etc).
...

How can I achieve this - ideally I want to keep the logic on the class MyEntity itself, rather than having a 'wrapper' class somewhere else to instantiate the object and perform the setting.... I guess I could have a 'helper' method which just the settings on a previously instantiated instance...but is there an idiom I'm missing here...?

Était-ce utile?

La solution

You got it right about creating the object via 'context.newObject(..)' - this is the best way to do it and will keep you out of trouble. Still you can actually have your own constructor (provided you also maintain a default constructor for the framework to use):

public MyEntity(String inputFile) {
   ...
}

public MyEntity() {
}

Then you can create your object first, and add it to the context after that:

MyEntity e = new MyEntity(inputFile);
context.registerNewObject(e);

As far as idioms go, a very common one is to avoid business logic in persistent objects. ORM models are often reused in more than one application, and behavior you add to the entities doesn't uniformly apply everywhere. The other side of this argument is that anything but simplest methods depend on the knowledge of the surrounding environment - something you don't want your entities to be aware of.

Instead one would write a custom service layer that sits on top of the entities and contains all the business logic (often used with a dependency injection container). Services are not wrappers of entities (in fact services are often singletons). You can think of them as configurable strategy objects. In the Java world such layered design and this type of separation of concerns is very common and is probably the most flexible approach.

But if you want to hack something quickly, and don't envision it to grow into a complex multi-module system, then using a custom constructor or a static factory method in the entity is just fine of course.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top