I came across a problem mapping multiple beans with Super CSV. I got a csv file, containing information for multiple beans (per line). But as I can see from examples on the website it is only possible to map each line into one bean (not into two or more beans).
Is there a way of doing this? The only way I can think of is creating a new bean, containing the all beans I need and do a deep mapping, i.e.:
class MultiBeanWrapper {
Address addreass;
BankAccount bankAccount;
}
...
String[] FIELD_MAPPING = new String[]
{address.street, bankAccount.bankNumber};
...
beanReader.read(MultiBeanWrapper.class, processors));
I didn't try this, because I want to be sure that there is no other / better way.
Thanks for your help
Daniel
No, you can't read a line into multiple beans - sorry! (I'm not sure what this would even look like - would you get a List<Object> back?)
You have a few options:
Add a relationship between the objects
Then can use a mapping like parent.fieldA, parent.child.fieldB. In your scenario Address and BankAccount aren't related semantically, so I'd recommend creating a common parent (see next option)
Add a common parent object
Then you can use a mapping like parent.child1.fieldA, parent.child2.fieldB. This is what you've suggested, but I'd recommend giving it a better name than Wrapper - it looks like a customer to me!
Oh, and I'd recommend trying stuff out before posting a question - often you'll answer your own question, or be able to give more details which will get you better answers!
Related
I've been looking at the different approaches to solving the mass assignment issues with MVC as well as doing things the right way.
So far, the 2 approaches which I think are the best are below: (I have also looked at AutoMapper)
1: Value Injecter - This seems to do the job pretty well, but also relies on a third party library
2: Using the UpdateModel method and bind to a View Model interface which exposes a subset of the required properties in your domain model. http://www.codethinked.com/easy-and-safe-model-binding-in-aspnet-mvc
Before I jump in and code my whole application (without spending a week on each to find out which one I actually like) using one of the above practices, does anybody have real world experience of using these 2 methods and which one you would recommend?
in simple scenarios where you have only text fields matching strings/int properties anything will do just as well.
but when you have properties on the viewmodel that match objects in the model (FK in the DB) it gets a bit more complex, you might need to pull data from the DB for some individual props and map some property of that object to the ViewModel, stuff like that.
prodinner asp.net mvc demo application uses valueinjecter in Mapper classes, there's a pdf where this approach is explained, you can download it here: http://prodinner.codeplex.com/
General consensus from all the reading I've done on this topic is that if you're going from a Entity or Domain Model (from your database) to a View Model to show on the form feel free to use automation tools like AutoMapper or whatever your preferred tool is to automate it.
If you are however going from a Input or Form Model (the object populated via the automatic model binding) back into to your Entity or Domain Model, do not automate this. It's a slippery slope to navigate correctly and can result in your automation tool mapping over fields that were not intended/permitted. Everything I've read about this (and various implementations myself) suggest the best practice is to do this manually/explicitly. It's pretty straight forward and object initializers can make it very easy to read.
var person = new Person()
{
PersonId = model.PersonId,
FirstName = model.FirstName,
LastName= model.LastName
}
personService.UpdatePerson(person);
Something along that line.
I use MVC4 and entity framework 5 in my project and I've lots of tables. As a rule of our project, we don't delete any records from database, each record has a isActive field and if that field is false, then we consider it deleted. I wanted to write an extension method to get active records and after some googling I wrote this:
public static IQueryable<Company> GetAll(this IQueryable<Company> source)
{
return source.Where(p => p.isActive);
}
Now I can use my extension method to get only active records like
Context db = new Context();
db.Company.GetAll();
But let's say I've 50+ tables in my database, is it a good approach to write the same extension method for each of my tables. Is there a better way to write a only one GetAll() extension method for all of our tables? Actually I'm not even sure if is it right way to use extension methods for this instance?
Could somebody please help me and show me the right way? I appreciate if you help with code examples.
It depends on how you are using Entity Framework, if you are depending on the normal generator (and I think you do), your case gets harder and I never had a similar case study. But, if you use normal POCO classes generator, you can use a base class let's call it CEntity which is a base class for each of your other classes (tables).
Are we there yet? No, to continue with this, I prefer to use the Repository Pattern, and you can make that repository generic (CEntity), for example:
public class Repository<CEntity> where CEntity : class
{
public IQueryable<CEntity> GetAll()
{
return source.Where(p => p.isActive);
}
}
And this is how to use it:
Repository<Company> com = new Repository<Company>();
Repository<Employee> emp = new Repository<Employee>();
var coms = com.GetAll(); // will get all ACTIVE companies
var emps = emp.GetAll(); // will get all ACTIVE employees
This is off the top of my head, if you had any other problems, put them as comments, glad to help.
Just as a point of interest, this is exactly how I implement my data layers, and i think its awesome :)
I also jam a repository in the middle as well but the general concept should work with or without.
Here's some working code examples of how I use this method in my blog for some similar use cases.
https://github.com/lukemcgregor/StaticVoid.Blog/blob/master/Blog/Data/Entities/Post/PostRepositoryExtensions.cs
I've found that it makes some pretty elegant code while still not restricting what you can do too much. Like i said, i think this method is awesome and really recommend its usage.
I tried to serialize grails domains classes to Maps or similar in order to be able to store it in memcached.
I want to be able to read the objects only, I don't need gorm crud. Only to read them without breaking the kind of interfaces they have.
For instance: I could convert domains to maps, becouse it wouldn't break the interface for access like .<property> or .findall or similar
First I tried to do a manual serialization but it was very error prone. So I needed something more general.
Then I tried to serialize as a map with a grails codec.
Here is the testing repo.
Here is the snippet.
But I get StackOverFlowException.
I also tried to mark all the domains as Serializable but I need to reattach every domain when I bring them back from memcached to avoid hibernate errors like org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Do you know a way to achieve this?
Is very frustrating to google search for something like this "storing domain classes in memcached" and find out is not a common problem.
I haven't see an out-of-the-box solution for doing this, but if you wanted to keep it generic you could do it manually (and consistently) like this:
def yourDomainInst = DefaultGrailsDomainClass(YourDomainClazz)
List listOfOnlyPersistantProperties = yourDomainInst.persistantProperties
def yourNewMap
yourObjects.each { obj ->
listOfOnlyPersistantProperties.each { prop ->
def propName = prop.name
yourNewMap.put(propName, obj."$propName")
}
}
Something like that should work. Note there's probably a hundred errors because I can't try it out right now, but that is the general idea.
Have a look at: Retrieving a list of GORM persistent properties for a domain
Just a few high-level, hopefully very quick questions:
1) If I have a class A with a single field x, is constructing it
def A = new A(x:someVal, y:someVal)
totally fine?
2) Related, is the following a good way to copy relevant parts of a command object into a domain object?
def domainObject = new DomainObject(commandObject.properties).
Where command object has extra properties. Or should it be done instead:
def domainObject = new DomainObject()
domainObject.properties['prop1', 'prop2', ...] = commandObject.properties
or ?
Thanks
For the first question, it's important to distinguish between a vanilla groovy object, and a grails domain object. Groovy objects with throw a MissingPropertyException. Grails domain objects will silently ignore extra properties.
Regarding the second question, initializing grails domain objects with a command object is a common pattern, and generally ok. Params can be a little bit more dangerous. A malicious user can put anything into params so it's best to explicitly spell out what properties you want to assign. Otherwise, things like timestamps and users, or even non-mapped columns like injected spring beans could be affected.
I have about the following:
class Object_1 {
static hasMany = [tags:Tag]
Set tags;
...
}
Now I have a set of tags and want to find all Object_1-instances with intersecting (!= matching) tags. I was thinking of something like
Object_1.findAllByTagsInList(tags);
But that does not work at all - I get a "nested exception is org.hibernate.exception.SQLGrammarException: could not execute query". I have the feeling I am missing something important. Help highly appreciated.
I actually found an elegant way to solve the problem. I redesigned the relationship to be many-to-many which allows for simply iterating over the tags list finding all the relevant objects.
... of course now I have to take care of that relationship a couple of times - but I am happy to have this working with few locs.
"in list" is not one of the operators recognized in dynamic finder methods - that won't work.
Instead, you'll have to use HQL or the criteria builder to formulate your query (and perhaps put it in a static finder method).