Override getter and setter in grails domain class for relation - grails

How to override getter and setter for field being a relation one-to-many in grails domain class? I know how to override getters and setters for fields being an single Object, but I have problem with Collections. Here is my case:
I have Entity domain class, which has many titles. Now I would like to override getter for titles to get only titles with flag isActive equals true. I've tried something like that but it's not working:
class Entity {
static hasMany = [
titles: Title
]
public Set<Title> getTitles() {
if(titles == null)
return null
return titles.findAll { r -> r.isActive == true }
}
public void setTitles(Set<Title> s) {
titles = s
}
}
class Title {
Boolean isActive
static belongsTo = [entity:Entity]
static mapping = {
isActive column: 'is_active'
isActive type: 'yes_no'
}
}
Thank You for your help.

Need the reference Set<Title> titles.
class Entity {
Set<Title> titles
static hasMany = [
titles: Title
]
public Set<Title> getTitles() {
if(titles == null)
return null;
return titles.findAll { r -> r.isActive == true }
}
public void setTitles(Set<Title> s) {
titles = s
}
}

Related

Grails domain class transient collection attribute setter issue

I am trying to set (or bind) value to a transient List attribute. But I failed with collections.
On the other hand transient String attribute working well on setter.
Grails version 2.4.3
Any advice?
#Resource(uri = "/api/samples", formats = ["json"])
class Sample {
static transients = ["fields","sample"]
String regions
String name
String sample
List<String> fields
List<String> getFields() {
this.regions != null ? Arrays.asList(regions.split("\\s*,\\s*")) : new ArrayList<String>();
}
void setFields(List<String> fields) {
if (fields != null && !fields.isEmpty()) {
this.regions = fields.join(",")
}
}
void setSample(String sample){
this.name = sample
}
static mapping = {
}
}
Untyped fields are transient by default, so this alternative approach should work (and is a lot more concise):
#Resource(uri = "/api/samples", formats = ["json"])
class Sample {
static transients = ["sample"]
String regions
String name
String sample
def getFields() {
this.regions != null ? Arrays.asList(regions.split("\\s*,\\s*")) : []
}
void setFields(def fieldList) {
if (fieldList) {
this.regions = fieldList.join(",")
}
}
void setSample(String sample){
this.name = sample
}
static mapping = {
}
}

Grails, property names in embedded object in domain class causing problems

I'm using grails 2.3.4 and I have a domain class that embeds an object. The embedded object has a property called 'version' and it seems that this is conflicting with the 'version'-field automatically added to the database-table by GORM. The result is that the 'version'-field belonging to my embedded object isn't created in the database and as a consequence my application doesn't work properly.
My code looks like this:
class Thing {
String someText
EmbeddedThing embeddedThing
Date someDate
static embedded = ['embeddedThing']
static constraints = {
embeddedThing(unique: true)
}
}
class EmbeddedThing {
String textOfSomeSort
String version
String textOfSomeOtherSort
}
You might think that a quick fix is to rename the 'version'-property of the embedded object but the class belongs to an included sub-project (i.e. a JAR-file) that I'm not allowed to touch since other projects use it. So the solution needs to be done completely within my domain class, or at least in a manner that doesn't change the class of the embedded object.
version is a special column name, you should rename your version field within your EmbeddedThin class
I actually found a solution to this problem by using a Hibernate UserType to represent the EmbeddedThing-class.
My code now looks like this and works perfectly:
Thing.groovy:
import EmbeddedThingUserType
class Thing {
String someText
EmbeddedThing embeddedThing
Date someDate
static embedded = ['embeddedThing']
static mapping = {
version false
embeddedThing type: EmbeddedThingUserType, {
column name: "embedded_thing_text"
column name: "embedded_thing_version"
column name: "embedded_thing_other_text"
}
}
static constraints = {
embeddedThing(unique: true)
}
}
EmbeddedThing.groovy:
class EmbeddedThing {
String textOfSomeSort
String version
String textOfSomeOtherSort
}
EmbeddedThingUserType.groovy:
class EmbeddedThingUserType implements UserType {
int[] sqlTypes() {
return [StringType.INSTANCE.sqlType(),
StringType.INSTANCE.sqlType(),
StringType.INSTANCE.sqlType()]
}
Class returnedClass() {
return EmbeddedThing
}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)
throws HibernateException, SQLException {
if (resultSet && names) {
return new EmbeddedThing(
textOfSomeSort: resultSet?.getString(names[0] ?: '_missing_textOfSomeSort_'),
version: resultSet?.getString(names[1] ?: '_missing_version_'),
textOfSomeOtherSort: resultSet?.getString(names[2] ?: '_missing_textOfSomeOtherSort_'))
} else {
return null
}
}
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index)
throws HibernateException, SQLException {
if (value != null) {
preparedStatement.setString(index, value?.textOfSomeSort)
preparedStatement.setString(index + 1, value?.version)
preparedStatement.setString(index + 2, value?.textOfSomeOtherSort)
} else {
preparedStatement.setString(index, '_missing_textOfSomeSort_')
preparedStatement.setString(index + 1, '_missing_version_')
preparedStatement.setString(index + 2, '_missing_textOfSomeOtherSort_')
}
}
#Override
public boolean isMutable() {
return false
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
return x.equals(y)
}
#Override
public int hashCode(Object x) throws HibernateException {
assert (x != null)
return x.hashCode()
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value
}
#Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value
}
#Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached
}
}
Config.groovy:
grails.gorm.default.mapping = {
'user-type'( type: EmbeddedThingUserType, class: EmbeddedThing)
}
Please try version false in your 'static mapping', for the 'EmbeddedThing' class.

GORM 'where criteria' with multiple many-to-many associations

Assuming you have three domain objs defined as such:
class Author {
String name
static hasMany = [books: Book]
}
class Book {
String name
static belongsTo = [author: Author]
static hasMany = [words: Word]
}
class Word {
String text
Set<Author> getAuthors() {
// This throws GenericJDBCException:
Author.where {
books.words == this
}
}
}
Why does getAuthors() fail with ERROR spi.SqlExceptionHelper - Parameter "#1" is not set; but works fine if rewritten using a Criteria:
public Set<Author> getAuthors() {
// This works as expected:
Author.withCriteria {
books {
words {
eq('id', this.id)
}
}
}
}
Do I have the syntax of the 'where query' wrong???
It seems like the criteria for your query is sort of misleading. books and words are both associations and you are expecting that words to be equal to single instance of the word object.
You can try this:
def getAuthors() {
Author.where {
books{
words {
id == this.id
}
}
}.list()
}

Get custom attribute for parameter when model binding

I've seen a lot of similar posts on this, but haven't found the answer specific to controller parameters.
I've written a custom attribute called AliasAttribute that allows me to define aliases for parameters during model binding. So for example if I have: public JsonResult EmailCheck(string email) on the server and I want the email parameter to be bound to fields named PrimaryEmail or SomeCrazyEmail I can "map" this using the aliasattribute like this: public JsonResult EmailCheck([Alias(Suffix = "Email")]string email).
The problem: In my custom model binder I can't get a hold of the AliasAttribute class applied to the email parameter. It always returns null.
I've seen what the DefaultModelBinder class is doing to get the BindAttribute in reflector and its the same but doesn't work for me.
Question: How do I get this attribute during binding?
AliasModelBinder:
public class AliasModelBinder : DefaultModelBinder
{
public static ICustomTypeDescriptor GetTypeDescriptor(Type type)
{
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = base.BindModel(controllerContext, bindingContext);
var descriptor = GetTypeDescriptor(bindingContext.ModelType);
/*************************/
// this next statement returns null!
/*************************/
AliasAttribute attr = (AliasAttribute)descriptor.GetAttributes()[typeof(AliasAttribute)];
if (attr == null)
return null;
HttpRequestBase request = controllerContext.HttpContext.Request;
foreach (var key in request.Form.AllKeys)
{
if (string.IsNullOrEmpty(attr.Prefix) == false)
{
if (key.StartsWith(attr.Prefix, StringComparison.InvariantCultureIgnoreCase))
{
if (string.IsNullOrEmpty(attr.Suffix) == false)
{
if (key.EndsWith(attr.Suffix, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(key);
}
}
return request.Form.Get(key);
}
}
else if (string.IsNullOrEmpty(attr.Suffix) == false)
{
if (key.EndsWith(attr.Suffix, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(key);
}
}
if (attr.HasIncludes)
{
foreach (var include in attr.InlcludeSplit)
{
if (key.Equals(include, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(include);
}
}
}
}
return null;
}
}
AliasAttribute:
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class AliasAttribute : Attribute
{
private string _include;
private string[] _inlcludeSplit = new string[0];
public string Prefix { get; set; }
public string Suffix { get; set; }
public string Include
{
get
{
return _include;
}
set
{
_include = value;
_inlcludeSplit = SplitString(_include);
}
}
public string[] InlcludeSplit
{
get
{
return _inlcludeSplit;
}
}
public bool HasIncludes { get { return InlcludeSplit.Length > 0; } }
internal static string[] SplitString(string original)
{
if (string.IsNullOrEmpty(original))
{
return new string[0];
}
return (from piece in original.Split(new char[] { ',' })
let trimmed = piece.Trim()
where !string.IsNullOrEmpty(trimmed)
select trimmed).ToArray<string>();
}
}
Usage:
public JsonResult EmailCheck([ModelBinder(typeof(AliasModelBinder)), Alias(Suffix = "Email")]string email)
{
// email will be assigned to any field suffixed with "Email". e.g. PrimaryEmail, SecondaryEmail and so on
}
Gave up on this and then stumbled across the Action Parameter Alias code base that will probably allow me to do this. It's not as flexible as what I started out to write but probably can be modified to allow wild cards.
what I did was make my attribute subclass System.Web.Mvc.CustomModelBinderAttribute which then allows you to return a version of your custom model binder modified with the aliases.
example:
public class AliasAttribute : System.Web.Mvc.CustomModelBinderAttribute
{
public AliasAttribute()
{
}
public AliasAttribute( string alias )
{
Alias = alias;
}
public string Alias { get; set; }
public override IModelBinder GetBinder()
{
var binder = new AliasModelBinder();
if ( !string.IsNullOrEmpty( Alias ) )
binder.Alias = Alias;
return binder;
}
}
which then allows this usage:
public ActionResult Edit( [Alias( "somethingElse" )] string email )
{
// ...
}

Restrict the rows retrieved from database for the relationship between the domain classes

I have two domain classes:
class Entity {
static hasMany = [
titles: Title
]
}
class Title {
Boolean isActive
static belongsTo = [entity:Entity]
static mapping = {
isActive type: 'yes_no'
}
}
Now when I am calling Entity.get(0) I would like to take from the database the Entity with id=0, but only with active Titles (where isActive = true). Is it possible in grails? I've tried to add where clause in static mapping of Title domain class:
static mapping = {
isActive type: 'yes_no'
where 'isActive = Y'
}
or
static mapping = {
isActive type: 'yes_no'
where 'isActive = true'
}
but it doesn't work. I am using Grails in version 2.2.1
Could You help me? Thank You in advance.
In this case you can use criteria to do that:
Entity.createCriteria().get {
eq('id', 0)
projections {
titles {
eq('isActive', true)
}
}
}
I don't think it's possible to set a default where to be applied in all your database calls to that Domain Class.
You can also wrap your logic in a service:
class EntityService {
def get(Long id) {
return Entity.createCriteria().get {
eq('id', id)
projections {
titles {
eq('isActive', true)
}
}
}
}
}

Resources