I have these 2 domains
class Country {
String name
static hasMany = [cities:City]
}
class City {
String name;
static belongsTo = [country: Country]
}
The data contained in these 2 tables is relatively big, and they're used in all the screens,
every time i choose a country i have to reload all its cities.
How can I load the data only once in memory so i can access it faster in all the screens.
I tried putting cities for eager fetching, and tried using cache plugin.
Thank you
You can configure both domain classes to be cached automatically and also cache the cities relation in Country:
class Country {
String name
static hasMany = [cities:City]
static mapping = {
cache true
cities cache:true
}
}
class City {
String name
static belongsTo = [country: Country]
static mapping = {
cache true
}
}
Caching is often a good strategy, but remember that caches have expiry parameters so if left idle your app may reload from the DB again. Depending on your cache provider you'll have to tune this, eg For ehcache edit your ehcache.xml in the grails config folder and set (cache name is the same as your Domain class including package name):
<cache name="Country" maxElementsInMemory="1000" timeToIdleSeconds="0" timeToLiveSeconds="0"/>
You should also move the query into a service, the service is by default singleton scoped and the service method also cachable.
An alternative is to store them in application scope such as in your Bootstrap.groovy run the query and assign the results:
servletContext.countries = Country.list()
Retrieve them in the same way, eg
in a controller:
List<Country> countries = servletContext.countries
or gsp:
<g:each var="country" in="${application.countries}">
${country}
</g:each>
If you have eager fetching on then you should see no DB hits.
Related
I am new to Elasticsearch and am using the revived grails plugin "elasticsearch:0.0.4.6".
I wanted to implement a search for a User by their firstName, surname or username, which returns the full domain instance.
I have a 2 domain classes:
User:
class User {
String firstName
String surname
static hasOne = [profile:Profile]
static hasMany = [friends:User]
static mappedBy = [ friends: 'friends' ]
static searchable = {
profile component:true
only = ['firstName', 'surname', 'profile']
}
...
Profile:
class Profile {
String username
String status
byte[] photo
static belongsTo = [user:User]
static searchable = true
...
}
I made the classes "searchable = true" and then created the following search:
def res = User.search("${params.friendSearch}").searchResults
This found the correct instances, but now when a user adds a photo to their profile, it suceeds but I recieve a never ending loop of the following error:
ERROR index.IndexRequestQueue - Failed bulk item: MapperParsingException[failed to parse [photo]]; nested: NumberFor
matException[For input string: the photos base64inputstring
I dont really get what is happening, but i figure it must be something to do with elasticsearch being unable to index the photo data. Can somebody provide an explanation?
I then experimented with searchables custom mapping options -
profile index:'no'
all=false
excludeFromAll = true
etc
Nothing worked. Eventually I added
only = ['username']
and it stopped the error from occuring and allowed me to find users based on the criteria i mentioned above. However, because of the "only" limit, it means that the User instances returned by the seach have a photo property equal to null, but i need this value!
What am i doing wrong? Can anyone advise me on the best course of action to take or any misunderstandings i have about Elasticsearch? Thanks
I think you might have to exclude the byte property photo from the searchable fields like so:
class Profile {
String username
String status
byte[] photo
static belongsTo = [user:User]
static searchable = {
except = ['photo']
}
This will exclude the property photo from being indexed and search. Hence the output of converting the byte format to string format will not fail.
Also maybe you might need a custom convertor to change the byte(string) to something more usable in the results?
Okay, I am trying to find all of my Employee that have a given role... However no matter what I try I end up getting the same exception thrown...
enum Role {
SFC("State Fitness Coordinator"),
TRAINING("Training"),
DFC("District Fitness Coordinator"),
final String longName
private Role(String longName) {
this.longName = longName
}
}
class Employee {
static hasMany = [roles: Role]
static constraints = {
}
}
The first Thing I tried was Employee.findAllByRoles(Role.DFC)
Then I tried:
Employee.findAll("FROM Employee e WHERE e.roles IN (:role)", [role: [Role.DFC]])
as well as
Employee.withCriteria {
'in'('roles', [Role.DFC])
}
all resulting in
Class
java.sql.SQLException
Message
Missing IN or OUT parameter at index:: 1
Any direction would be much appreciated.
with grails 2.3.8 and H2
Employee.findAll("FROM Employee e WHERE :role in elements(e.roles) ", [role: Role.DFC.toString()])
this works… even if I think that Role could be a real Domain simplifying all operations
I think the problem is that Role is an enum. Are you sure you want to make it an enum?
I recommend making it a class since new roles might be added. If so, you can easily add a record using bootstrap or SQL query without making a new build to production.
class Role {
String roleName
String description
}
In Bootstrap:
Role sfc = new Role("SFC","State Fitness Coordinator")
Role sfc = new Role("TRAINING," "Training")
Role sfc = new Role("DFC", "District Fitness Coordinator")
N.B. Please make sure you are not using spring security plugin which has its own 'Role' class. If so, please change the name of your 'Role' class to something like 'EmployeeRole'
I have 3 domain classes User, Server, Quota and I want to map them with the following relations
A User can access many Servers with different Quotas
But it should not allow a User to access the same Server with different Quotas (or +Each User may have exactly one entry for each Server)
You can create a NxN relation between User and Server. However, will be necessary create a class for that relation. This is necessary because you need the attribute quota. In the standard way of a NxN relation Grails (Hibernate) doesn't create a class for it.
You'll need three classes:
User,Server,UserServer
Class UserServer {
int quota
static belongsTo = [user:User, server:Server]
static constraints = {user unique: 'server'}
}
The unique constraint it's very important, because as you said, a User may have exactly one entry for each Server.
To link and unlink a User and Server you can use the following methods:
Class UserServer {
int quota
static belongsTo = [user:User, server:Server]
static constraints = {user unique: 'server'}
static PackScheme link(User user, Server server) {
UserServer userServer = UserServer.findByUserAndServer(user, server)
if (!userServer) {
userServer = new UserServer()
user.addToUserServers(userServer)
server.addToUserServers(userServer)
userServer.save()
}
return userServer
}
static void unlink(User user, Server server) {
UserServer userServer = UserServer.findByUserAndServer(user, server)
if (userServer) {
user.removeFromUserServers(userServer)
server.removeFromUserServers(userServer)
userServer.delete()
}
}
}
Note that you need to create a hasMany relation in User and Server called userServers:UserServer.
This solution is based on this link: http://grails.org/Many-to-Many+Mapping+without+Hibernate+XML
I am using Castle ActiveRecord in my Asp.net / MVC 2 / Multi-tenancy application with SQL Server as my backend.
For every user logging in, the app loads the corresponding DB, dynamically at run time like below:
IDictionary<string, string> properties = new Dictionary<string, string>();
properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
properties.Add("connection.connection_string", strDBConnection);
InPlaceConfigurationSource source = new InPlaceConfigurationSource();
source.Add(typeof(ActiveRecordBase), properties);
ActiveRecordStarter.Initialize(new System.Reflection.Assembly[] { asm1 }, source);
The strDBConnection string comes from another small database that holds the user info, corresponding DB, etc.
Scenario:
When a user logs in, his DB gets loaded, he can do his CRUD jobs -- No Probs !
Another user logs in (from another remote machine) his DB gets loaded -- No Probs !
Now, when the first user reads from DB, he sees new data from the second user's DB
My little understanding for this behavious is : ActiveRecordStarter is a Static object.
Could someone help me with a solution for this situation ?
The expected behaviour:
each user should access his own DB only, securely, in parallel / at the same time.
Thanks a lot !
ActiveRecordStarter.Initialize should only be called once in your app (in Application_Start in Global.asax).
To achieve what you want, create a class that inherits from NHibernate.Connection.DriverConnectionProvider:
public class MyCustomConnectionProvider : DriverConnectionProvider
{
protected override string GetNamedConnectionString(IDictionary<string, string> settings)
{
return string.Empty;
}
public override IDbConnection GetConnection()
{
// Get your connection here, based on the request
// You can use HttpContext.Current to get information about the current request
var conn = Driver.CreateConnection();
conn.ConnectionString = ... // Retrieve the connection string here;
conn.Open();
return conn;
}
}
Then set the connection.provider property to the name of your class:
properties.Add("connection.provider", "MyCompany.Domain.MyCustomConnectionProvider, MyCompany.AssemblyName");
I have the following seemingly simple scenario, however I'm still pretty new to NHibernate.
When trying to load the following model for an Edit action on my Controller:
Controller's Edit Action:
public ActionResult Edit(Guid id)
{
return View(_repository.GetById(id));
}
Repository:
public SomeModel GetById(Guid id)
{
using (ISession session = NHibernateSessionManager.Instance.GetSession())
return session.Get<SomeModel >(id);
}
Model:
public class SomeModel
{
public virtual string Content { get; set; }
public virtual IList<SomeOtherModel> SomeOtherModel { get; set; }
}
I get the following error:
-failed to lazily initialize a collection of role: SomeOtherModel, no session or session was closed
What am I missing here?
The problem is that you create and also close the session in you models GetById method. (the using statement closes the session) The session must be available during the whole business transaction.
There are several ways to achieve this. You can configure NHibernate to use the session factories GetCurrentSession method. See this on nhibernate.info or this post on Code Project.
public SomeModel GetById(Guid id)
{
// no using keyword here, take the session from the manager which
// manages it as configured
ISession session = NHibernateSessionManager.Instance.GetSession();
return session.Get<SomeModel >(id);
}
I don't use this. I wrote my own transaction service which allows the following:
using (TransactionService.CreateTransactionScope())
{
// same session is used by any repository
var entity = xyRepository.Get(id);
// session still there and allows lazy loading
entity.Roles.Add(new Role());
// all changes made in memory a flushed to the db
TransactionService.Commit();
}
However you implement it, sessions and transactions should live as long as a business transaction (or system function). Unless you can't rely on transaction isolation nor rollback the whole thing.
You need to eagerly load the SomeOtherModel collection if you intend to use it before closing the session:
using (ISession session = NHibernateSessionManager.Instance.GetSession())
{
return session
.CreateCriteria<SomeModel>()
.CreateCriteria("SomeOtherModel", JoinType.LeftOuterJoin)
.Add(Restrictions.Eq(Projections.Id(), id))
.UniqueResult<SomeModel>();
}
By default FluentNHibernate uses lazy loading for collection mappings. Another option is to modify this default behavior in your mapping:
HasMany(x => x.SomeOtherModel)
.KeyColumns.Add("key_id").AsBag().Not.LazyLoad();
Note that if you do this SomeOtherModel will be eagerly loaded (using an outer join) every time you load the parent entity which might not be want you want. In general I prefer to always leave the default lazy loading at the mapping level and tune my queries depending on the situation.
"If we want to access the order line items (after the session has been closed) we get an exception. Since the session is closed NHibernate cannot lazily load the order line items for us. We can show this behavior with the following test method"
[Test]
[ExpectedException(typeof(LazyInitializationException))]
public void Accessing_customer_of_order_after_session_is_closed_throws()
{
Order fromDb;
using (ISession session = SessionFactory.OpenSession())
fromDb = session.Get<Order>(_order.Id);
// trying to access the Customer of the order, will throw exception
// Note: at this point the session is already closed
string name = fromDb.Customer.CompanyName;
}
"Eagerly loading with the NHibernateUtil class If you know you need have access to related objects of the order entity you can use the NHibernateUtil class to initialize the related objects (that is: to fetch them from the database)."
[Test]
public void Can_initialize_customer_of_order_with_nhibernate_util()
{
Order fromDb;
using (ISession session = SessionFactory.OpenSession())
{
fromDb = session.Get<Order>(_order.Id);
NHibernateUtil.Initialize(fromDb.Customer);
}
Assert.IsTrue(NHibernateUtil.IsInitialized(fromDb.Customer));
Assert.IsFalse(NHibernateUtil.IsInitialized(fromDb.OrderLines));
}
Reference: http://nhibernate.info/doc/howto/various/lazy-loading-eager-loading.html