I have two domain classes
class Country {
... // some fields, including other domains
}
class City {
... // some fields, including other domains
Country itsCountry
}
One of my service method is here:
City createCity(String name, Country country) {
// country is existing and loaded in the controller's layer and passed here
City city = new City()
city.itsCountry = country // it is not persisted
city.save('flush':true)
}
The problem is that in the database the city has null country.
Of course, I simplified the example, really is it more complicated. (Unfortunately, some important details can be lose, I hope if you faced this problem, you share the reason)
What I did without success:
playing with Country, getting it by id inside the service method, save and flush it before saving the City object
make the itsCountry field not nullable. So I got an exception from database, that this field can't be null.
I feel that it must be some trivial thing. What can be a reason of it?
in Grails we can already get the country id in params .Right.
like for example, params?.countryId.
If it is new record for country table, then first create new object for country and assign in city object.
For example,
Country country = new Country()//for new record
country.name=params?.countryName
City city=new City()
city.itsCountry = country
city.save('flush':true)
If you have already country record in table then use get method to get object and assign it to city.
For example,
Country country=Country.get(Long.valueOf(params?.countryId))
city.itsCountry = country
city.save('flush':true)
I hope it will help you. If any doubt please ping me.
Related
I have 2 domain classes
Expenditure
class Expenditure {
Date date
Supplier supplier
String particular
BigDecimal amount
}
Supplier
class Supplier {
String name
String address
static hasMany = [expenditures: Expenditure]
}
What happening is that when I create a new expenditure, I will enter the supplier from the list of suppliers in the Supplier class. When the supplier is not exist, I will have to create it first and then select it when creating the expenditure.
What I want is that, when I enter the supplier it will be looked up, and when not found, it will be created on the go (when saving the expenditure instance) without me having to create it first in the Supplier table and then come back to Expenditure to complete the form.
How can I achieve this?
What I want is that, when I enter the supplier it will be looked up,
and when not found, it will be created on the go
One option you have is to do something like one of these...
Supplier.findOrCreateByName('some name goes here')
Supplier.findOrCreateByNameAndAddress('some name goes here', 'some address goes here')
There are also findOrSaveBy... counterparts but those only work if you are supplying enough search criteria to create a fully save-able instance.
I hope that helps.
Suppose I have two domains:
class Country {
String name
String Desc
static hasMany = [organizations: Organization]
}
class Organization {
String name
Country country
static belongsTo = [country:Country]
}
Note: In case of create Organization, countries will be listed in a combobox.
Suppose I have 4 row in my database which I have fetched from bootstrap.
**Name** **Desc**
US USA
CA CAN
NP NEP
IN IND
I want to assign USA as a default value while create a Organization. Is there a way to do it from domain level not gsp?
I think the load method is your best bet, although it requires that you know the id of the instance that you want to be the default. It's not a good idea to hard-code this because it could change in the future. But you can look it up when the app starts and save the id, e.g.
class BootStrap {
def grailsApplication
def init = {
def usa = Country.findByName('US')
grailsApplication.config.COUNTRY_US_ID = usa.id
}
}
Use whatever Config key you want of course.
Then change the Organization class to call load in its constructor:
import grails.util.Holders
class Organization {
Organization() {
if (Holders.config.COUNTRY_US_ID) {
country = Country.load(Holders.config.COUNTRY_US_ID)
}
}
String name
static belongsTo = [country:Country]
}
Note that I removed the Country country property because it's redundant; adding that belongsTo creates a property with the same name as the map key ("country") and with the same type as the map value (Country). It doesn't hurt to have it, but it's not needed.
The reason load is appropriate here is that it doesn't hit the database until you access a persistent property other than id. So you're configuring it to lazily retrieve the real instance if necessary, but if you overwrite the value with a different instance, you won't have wasted a database lookup for the initial population. Turn on SQL logging to verify this.
Im designing an application from the ground up. I do this as a study object to get my coding skills better and better. In this application I have two entities:
Countries
Cities
Adding a country is not hard. I pass the viewmodel in the business layer, the CountryService, convert it in an entity and persist it.
Secondly I need to add a city. To do this, I have a viewmodel that has a CountryId and the fields for city. I pass the viewmodel to the CityService. There I need to do a couple of things. I need to retrieve the correct country entity, convert the city data to a city object, add either the city object to the country or add the country to the city (via the AddXXX method Nhibernate propose). Then I need to save the City with country via the city repository or save the country with city via the country service and then in the country repository.
With the mindset of having 1 function per method I'm kind of lost how to structure this kind of functionality.
Instead of retrieving the country in the city service why not just pass in the CountryId into the city service method and use:-
var city = new City
{
Name = "London",
country = session.Load<Country>(countryId)
};
session.save(city);
This does not hit the database and physically return the record, it simply allows you to set the foreign key.
That said another way is to embrace Nhibernate in your MVC project and expose the session, rather than abstracting it completely away. This train of thought is gaining momentum.
Here is the situation: a user table contains data that overlap with other users' data such as country, age group, gender, etc.
In MySQL, I would use three tables or two. In the case storing country, I would use three tables: one would the be user table, the other country table, and the last one that joins the two. (Of course I could use two tables if one user has one country.)
ex) user(id, otherUserInfo),
userCountry(id_user, id_country),
country(id, countryName)
Being new to Grails, I was wondering what's the best way to represent this schema. Is it necessary to create 2-3 domain classes? Or is there some magical feature (like so many other Grails features (: ) to do this in a single domain class.
More than likely you could do it with two.
class User {
//other user info
//if user only has one country
Country country
//if user has many countries
static hasMany = [countries: Country]
}
class Country {
//country info
}
Since you probably don't want a Country to belong to the User, you don't need anything in the Country class to indicate ties back to the User. Grails/Gorm will handle creating the linking entities in either of these cases.
If the user has many countries and you needed to store other information regarding the relationship you would need to create your own join table. For example if you needed to keep the number of visits the user has made to the country:
class User {
//other user info
static hasMany = [userCountries: UserCountry]
}
class UserCountry {
static belongsTo = [user: User]
Country country
int numberOfVisits
}
class Country {
//country info
}
Just using this as an example...
Here are the columns in my UserProfile table:
ProfileID (Primary key)
UserID (Foreign key)
Address
PhoneNumber
now, when I want to add a new user to the database using LINQ to Entities, here is what I'm doing:
UserProfile profileToAdd;
profileToAdd.ProfileID = 0;
profileToAdd.Address = "123 MyStreet";
profileToAdd.PhoneNumber = "123-4567";
/* How do I add in the UserID here? */
_myDB.AddToUserProfiles(profileToAdd);
A few questions...
Is there anything special about dealing with Foreign keys that I need to know, or can I assign it just as I did with Address or PhoneNumber?
The UserId is a Guid, and I need to retrieve it from the current user's UserId. I can't seem to get access to Membership class or User class (This is a C# Library so I'm guessing it needs a reference somehow, but my project is already referencing my Library so I can't reference back or I'll have a circular dependancy)
I don't quite understand how to deal with Guids. When implementing getProfileByUserName(string userName), here's my problem...
first off I can't retrieve the UserID, here's what I tried:
Guid currUser = (Guid)from user in _ myDB.aspnet_Users
where user.UserName == userName
select new { user.UserId };
But it says I can't cast it to a Guid for some reason.
If you can provide any insight to any of these questions I would greatly appreciate it!
Thanks,
Matt
If the database contains the proper constraints for the foreign key relationship, there should be a member in your UserProfile class, that points to a User object. The name might be a little weird, such as UserProfileUser or something like that.
However, you can change this name in the diagram. Just set a pointer to the user entity object and the framework will assign the correct id for you.