Can a Grails Domain Class inherit from a class that is not a domain class? - class

I tried to do this, but it insists on their being a table of the base class. I tried using tablePerHierarchy false as well and that didn't make any difference.
I have a few domain classes that share a bunch of methods that operate on an inherited transient field. I had hoped that just having the class over in the non-domain section "/src/..." would be enough for GORM to realize there isn't a base class in the database.
When I put the class in the src section I get a different error. It no longer maps the specific class.
Error 500: org.springframework.orm.hibernate3.HibernateQueryException: Summarypage is not mapped [from Summarypage where id = ?]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Summarypage is not mapped [from Summarypage where id = ?]

I figured it out. If the base class is an abstract class it does the right thing.
Thanks anyway everyone.

Related

What does "class Meta:" do in Django and Django REST Framework?

I am trying to figure out what class Meta: really do in Django.
I come across with the code below in DRF, but not sure why under class Meta: there is model = User and fields = [...]. Does it help to create a database?
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(
serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
And also what is the different with the class Meta: used in Django as below.
from django.db import models
class Ox(models.Model):
horn_length = models.IntegerField()
class Meta:
ordering = ["horn_length"]
verbose_name_plural = "oxen"
I have tried to get further understanding from both Django and DRF documentation however I did not see the explanation for model = ... and fields = [...] used in DRF class Meta.
Hope someone could help to explain the functioning principle behind. Thanks!
The Meta class is merely a convenient place to group metadata (meaning data about the data) that DRF needs to adjust its configuration, but keep this separate from the attributes of the class itself. This separation allows the Django Rest Framework (and the wider Django Framework ecosystem) to avoid clashes between configuration and the actual class definitions.
The use of an inner Meta class is a common pattern throughout Django, because this allows you to both keep this configuration separate from the fields of the class and keep it connected to the class in a way that's easy to read and easy for the framework to find. A DRF selialiser class should normally have one or more fields to help turn data into a serialized form, but the HyperlinkedModelSerializer base class can generate these fields for you if you tell it what model you wanted to serialise. The fields on the Meta class tell it you want to serialize specific fields from your User model.
By putting this configuration on the inner Meta class, they are kept in a separate namespace from the main class, but at the same time remain connected to the class they are meant to configure. Imagine a model that has a field named model and fields for example. If the HyperlinkedModelSerializer required that configuration is found in the subclass itself, you could never produce a serializer that could process something with model and fields fields!
If you wanted to know what the different options are you can use on the inner Meta class, you need to read the ModelSerialiser and HyperlinkedModelSerializer documentation in the API guide section.
For Django Models, you can refer to the Model Meta chapter of the Django documentation. As I stated above, it's the same concept but here the Meta class configures the database fields that the model supports and how the model relates to other database models you may have defined.
Last but not least, there is another answer here that confuses the term Meta with Python Metaclasses, which is a very different concept. While DRF and Django model classes lean heavily on metaclasses for their internal implementation, the class Meta: definition you use to configure the framework functionality, they are not metaclasses. They are plain classes that are only used because they make for a convenient namespace.
class Meta is used in DRF serializers to configure your serializer.
model defines the model to which your serializer is linked.
fields is a list of properties that you would like to serve in your API.
Use fields = ['__all__'] to serve all properties
Use exclude = ['your_excluded_prop_1', 'your_excluded_prop_2'] to exclude properties
The concept of Meta class comes from metaprogramming. The term metaprogramming refers to manipulating itself. Python supports a form of metaprogramming for classes called metaclasses. Meta class is mainly the inner class of your main class. Meta class is basically used to change the behavior of your main class attributes. It’s completely optional to add a Meta class to your Class. But in your Django project, you have already seen this metaclass concept available in different places like models.py, serializers.py, admin.py, etc.
Actually, this Meta class changes the common behavior of its main class like the model metaclass changing behavior using verbose_name, db_table, proxy, permissions, ordering etc, and a lot of other options. Meta class in serializer also does the exact same things it tells it the model to use and what fields to serialize by using fields, exclude, and model.
Good Luck :)

Zend Model access in singleton class - best approach

I'm looking for best pattern/approach to access one table data in singleton class (in ZF 1.x). In details:
I have one singleton class (just like Zend_Date for example) that make for me some basic abstract stuff very detached from application reality.
In this class, in two points, I need to access to one db table and I need to make some basic operation on it.
It's not a problem to use my regular ZF models class inside functions of this singleton. It works fine. Now it look like:
class My_ZF_Singleton
{
...
public function someFunctionInMySingleton()
{
...
$oModel = new Model_My_Model_Form_ZF_Application();
$oModel->letsDoSomeStuffWithDb();
...
}
...
}
But I feel in my bones that it's not a very good solution, not so glamour as I would like to be. It make my singleton class more attached to application then it should be. I would like to use some other pattern to access this db data then application model class. I would be very thankfull for any clue or better solution - it's not a "hey I'm stuck probem" or "hey I've got an error" - I'm just looking for better solution.
Not sure I quite understand your question or want the point might be, but I'll try.
In ZF1 the database adapter is typically a singleton already. Multiple databases maybe connected to but each will require a unique identification. Typical access to the default adapter setup in the application.ini or Bootstrap.php:
$adapter = Zend_Db_Table::getDefaultAdapter();
a common way to provide access to a single database table and give access to the Zend_Db_Table api is to build a DbTable model:
class Application_Model_DbTable_TableName extends Zend_DbTable_Abstract
{
protected $_name = 'Table_Name' //required if classname does not match table name
protected $_primary = 'primary_key_column_name'//optional, use if primary key is not 'id'
}
You can treat this class as an instance of the default database adapter for a single table (works really well in a mapper). You can also add functions to this class to override or add to the default Zend_Db_Table api.
I hope this at least comes close.

Avoid using DTO class?

I followed https://developers.google.com/web-toolkit/articles/mvp-architecture .
In their model, they use one class 'Contact' and a light version of that class called 'ContactDetails'.
Since I don't really need a light version, I removed ContactDetails and replaced it by Contact.
Now I run into exceptions like
Type 'org.eclipse.persistence.indirection.IndirectList' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = {IndirectList: not instantiated}
The reason is, as I found out here (http://stackoverflow.com/a/6778986/1141785), that the Contact class is a class which uses Persistence API techniques, which should not be sent to the wire.
So is the ContactDetails class my DTO class which should be sent through the wire?
Is there no way to avoid using this extra class?
The reason I want to avoid using the 'light' version is, that I want to edit the Contact class in a DataGrid using the FieldUpdater.
Do I have any advantages in my case when I use the DTO class?
How can I avoid that I have so many duplicated code in the Contact and ContactDetails classes, when they should by nearly the name?
When using JPA, you can have a class containing a List such as:
public class Contact implements IsSerializable {
// ...
private List<Address> addresses;
// ...
}
But when Contact is created, addresses is set to an instance of IndirectList. This allows lazy loading of the collection from the database, but won't work on the client. You would need to replace it with something like an ArrayList before sending it to the client. You can set it to an empty list, or copy the contents to a new list.
If the elements of the list contain collections themselves, then you need to replace these collections as well. You'd need to be careful about circular references and pulling too many items from the database.
Simply annotate your List with fetchtype eager.
public class Contact implements IsSerializable {
#ElementCollection(fetch = FetchType.EAGER)
private List<Address> addresses;
}

Class design 'dilemma'

I never did proper class design, so bear with me.
Let's say we have a Project class. Then let's say we have a ProjectGroup class that has the same members as the Project class, plus a list of Projects.
Should ProjectGroup be the superclass of Project or is ProjectGroup a specialization of Project and the former should be a subclass of the latter?
I won't bother you with theory, because you're probably in a hurry to get a quick answer. So here it goes:
If your two classes are actually implying they should be related by inheritance then ProjectGroup should inherit from Project class. This is how it would look like in C#:
public class ProjectGroup: Project ...
If they are not, but they use some common class members (that define their state and some functionality over that state), then I'd write an interface and implement it in both classes. C# code again:
public interface ICommonState ...
public class Project: ICommonState ...
public class ProjectGroup: ICommonState
{
IEnumerable<ICommonState> projects
...
}
Edit
If your classes are actually Project and ProjectGroup and they both have properties like ID and Name in common (for instance), they still shouldn't be inherited. They just happen to have properties with the same name, but they are basically different entities.
They could both either
implement an ICommonEntity interface - use it when they have the same state+functionality but functionality behaves differently in each of them
inherit from CommonEntity class - use it when functionality is completely identical; this way you'll follow the DRY (don't repeat yourself) philosophy
So your component may be an interface or a class (when using composite pattern).
Direct inheritance between two classes is more suitable where entities imply on being in relation to each other. Like User and Person classes. They can be inherited either way. Depending on the business scenario.
class User: Person
This would be the case where you have an application with contacts. Some of them are also users of this very same application.
class Person: User
This would be a web site where you can register as a user. In case you fill up some personal details as well your user data becomes of type Person.
It sounds like you might want the Composite pattern. Both LeafProject and CompositeProject implement the Project interface, and CompositeProject also holds a collection of Project instances.
if the member list of projects is unique to projectgroup and does not apply to all types of projects, then make project your super/base class and derive projectgroup from project.

RIAServices unsupported types on hand-built DomainService

My EF model was generated from my SQL Server database. I then generated a DomainService for RIAServices against the EF model. One of the entities is called "EntryCategories". The DomainService created this method:
public IQueryable<EntryCategories> GetEntryCategoriesSet()
{
return this.Context.EntryCategoriesSet;
}
Since my user interface display model looks quite different from the physical model, I decided to write my own DomainService for that and related entities. Yes, I know we are meant to modify the generated one but it has so much stuff in there and I wanted to focus on a small thing.
I removed the EnableClientAccess attribute from the generated DomainService and added a new class called ClientDomainService, and encapsulated in it the generated DomainService:
[EnableClientAccess()]
public class ClientDomainService : DomainService
{
// the generated domain service encapsulated in my new one.
private DataDomainService _dcds = new DataDomainService();
// reimplement one of the DataDomainService methods
public IQueryable<EntryCategories> GetEntryCategories()
{
return (from t in _dcds.GetEntryCategoriesSet() where t.EntryCategoriesVersions.EntryCategoriesVersionId == datahead.EntryCategoriesVersions.EntryCategoriesVersionId orderby t.DisplayOrder select t);
}
}
The very fist thing I tried is to reimplement the GetCateogoriesSet method but with the underlying data filtered based on another entity in my class (not shown). But when I build this, an error shows up:
Entity 'DataProject.Web.EntryCategories' has a property 'EntryCategoriesVersionsReference' with an unsupported type
If I comment out my CientDomainService, replace the EnableClientAccess attribute on the generated DomainService, and place the analagous linq filtering in the original GetEntryCategoriesSet method, the project compiles with no errors.
What is so special about the generated DomainService that my new one doesn't have? Is it that metadata.cs file?
What's special about the generated domain service is not the .metadata.cs file (you can keep it, and use it, but it doesn't solve your problem).
The problem appears somehow because RIA services (?) needs a 'domain service description provider' for the exposed Linq to EF entities. The LinqToEntitiesDomainService class has the LinqToEntitiesDomainServiceDescriptionProviderAttribute, already applied, so the generated domain services which inherit from it also inherit the provider.
When you build your own custom domain service, derived from DomainService, and expose entities through it, you need to apply this attribute yourself. Furthermore, since the provider cannot infer the object context type from the domain service base class (which it can and does if the base class is LinqToEntitiesDomainService), you need to specify the object context type in the attribute constructor, like this:
[EnableClientAccess()]
[LinqToEntitiesDomainServiceDescriptionProvider(
typeof(YourObjectContextType))]
public class ClientDomainService : DomainService
{
...
}
That should fix it.
Note that this means if you had hoped to abstract your object context away from your domain service, you'll be disappointed. I had opted for the seemingly popular repository model where all code that operates on the object context goes into a provider used by the domain service. This facilitates unit testing, but evidently doesn't remove the domain service's dependency on the object context. The context is required for RIA Services to make sense of your entites, or at least those referenced by the domain entity (such as EntryCategoriesVersions in your case).
If you want to expose a specific entity on a domain service you will have to provde at least one query method for it. This is also required when the entity is only accessed as a child of another entity.
In this case you need to add the EntryCategoriesVersions entityset to the domain service, to get the scenario working correctly.
What type is EntryCategoriesVersionsReference ? Try adding a [DataContract] annotation against the type, and appropriate [Key] and [DataMember]. It should help with marshalling.
For me, the fix for this error was to add a default constructor to the return type.
In OP's example, the property 'EntryCategories.EntryCategoriesVersionsReference' needs to be of a type with a default constructor.