Grails Constraints with Java Classes and Hibernate Mappings - grails

I have the following Java class defined in src/java
package org.davisworld.trip;
public class AirportHbm {
private long id;
private String name;
private String iata;
private String state;
private String lat;
private String lng;
// getters/setters defined
}
I have the hbm.cfg.xml file defined as follows in conf/hibernate:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="AirportHbm.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I have the AirportHbm.hbm.xml file configured as follows in conf/hibernate:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.davisworld.trip.AirportHbm" table="usgs_airports">
<id name="id" column="airport_id">
<generator class="native"/>
</id>
<property name="name" type="java.lang.String">
<column name="airport_name" not-null="true" />
</property>
<property name="iata" type="java.lang.String">
<column name="locid" not-null="true" />
</property>
<property name="state" />
<property name="lat" column="latitude" />
<property name="lng" column="longitude" />
</class>
</hibernate-mapping>
And lastly, I have an AirportHbmConstraints.groovy file in the src/java folder:
package org.davisworld.trip
class AirportHbmConstraints {
static constraints = {
name()
iata(maxSize:3)
state(maxSize:2)
lat()
lng()
}
}
When I try to run the app, I get this error when Spring is initializing the web app context:
Caused by: java.lang.ClassCastException: org.davisworld.trip.AirportHbmConstraints cannot be cast to groovy.lang.Script
The tutorial I was following originally said that the AirportHbmConstraints.groovy file shouldn't have a class; it should just be a script:
package org.davisworld.trip
static constraints = {
name()
iata(maxSize:3)
state(maxSize:2)
lat()
lng()
}
But when I do that, STS gives me a compiler error:
Groovy:Modifier 'static' not allowed here.
Anyone know what I'm doing wrong? What is the correct way to apply constraints in Groovy to a Java domain class?
Many thanks,
Vito

When using constraints scripts with a Hibernate domain you do not use a class declaration or the static modifier as explained in section 15.3 Adding Constraints of the Grails documentation.
The correct constraint script would be:
constraints = {
iata maxSize: 3
state maxSize: 2
}
Note that fields without a constraint and the parentheses on the field declaration are optional.

Related

custom exception mapping in spring security xml

I am giving below snippet in spring security.xml
<!-- Exception Mapping configuration -->
<bean id="securityExceptionTranslationHandler"
class="com.abc.xyz.ExceptionMappingFailureHandler" >
<property name="exceptionMappings">
<props>
<prop key="org.springframework.security.authentication.CredentialsExpiredException">/408</prop>
</props>
</property>
</bean>
I am getting error while starting tomcat itself saying :
Invalid property exceptionMappings of com.abc.xyz.ExceptionMappingFailureHandler class :Bean Property exceptionMappings is not writtable or has an invalid setter method .
What should be content of com.abc.xyz.ExceptionMappingFailureHandler class ?
Any Help would be appreciated !
Your class should look something like this to work:
package com.abc.xyz;
public class ExceptionMappingFailureHandler {
public void setExceptionMappings(Map mappings) {
...
}
}
The important thing is that there is a setter with that name, it returns void, and accepts a single argument of type Map.

Connection pool. call a procedure each time an operation is made

Hei there, I'm working on a Primefaces 5/JSF 2/Mybatis webapp. My question is. To know each time who did what (on the app) we have to execute a method setUser(...). The company I'm working in right now, had a C# version of the app we are building now but there were no connection pools there so they only had to execute that procedure when the user logged in.
(right now we just call that method in the getSQLFactory method, which I know is not best practice... but that looked like the only viable solution to not add it manually in all our 200+ Mappers)
public static SqlSessionFactory getSqlSessionFactory() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
ManagedNavUtils navyUtils = (ManagedNavUtils) session.getAttribute("navy");
if (navyUtils != null && navyUtils.getLoggedInUser() != null)
setLoggedInUser(navyUtils.getLoggedInUser());
return factory;
}
IS there a way to call the procedure each time something gets executed on the DB?
my mybatis-config.xml file with the relevant configuration:
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
<!-- CONNECTION POOLING PROPERTIES -->
<property name="poolMaximumActiveConnections" value="20" />
<property name="poolMaximumIdleConnections" value="5" />
<property name="poolPingEnabled" value="false" />
</dataSource>
</environment>
</environments>
You can create mybatis plugin to intercept all queries.
But for your case better option is to set user only once that is during connection retrieval. Some connection pools allows custom initialization when connection is borrowed from the pool. Another possible option is to wrap DataSource which is used by mybatis.
For your case that is using datasource shipped with mybatis the easiest way it to wrap DataSource using custom DataSourceFactory.
First extend PooledDataSource like this:
class MyPooledDataSource extends PooledDataSource {
// all constructors should be defined but omitted for brevity
public Connection getConnection() throws SQLException {
Connection connection = super.getConnection();
setLoggedInUser(connection);
return connection;
}
public Connection getConnection(String username, String password) throws SQLException {
Connection connection = super.getConnection(username, password);
setLoggedInUser(connection);
return connection;
}
private void setLoggedInUser(Connection connection) {
// actual setting of logged in user
}
}
Then you need to define factory:
public class MyDataSourceFactory extends PooledDataSourceFactory {
public MyDataSourceFactory() {
this.dataSource = new MyPooledDataSource();
}
}
And modify mybatis-config.xml to make mybatis use your datasource factory:
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="org.myproject.MyDataSourceFactory">
<property name="driver" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
<!-- CONNECTION POOLING PROPERTIES -->
<property name="poolMaximumActiveConnections" value="20" />
<property name="poolMaximumIdleConnections" value="5" />
<property name="poolPingEnabled" value="false" />
</dataSource>
</environment>
</environments>

Spring Framework basics

I'm quite new to Spring Framework. Could someone please help me understand the spring configuration below?
<?xml version="1.0"?>
<configuration>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<object type="Test.aspx">
<property name="AService" ref="AService" />
<property name="BService" ref="BService" />
</object>
</objects>
</spring>
</configuration>
Basically questions in my mind are:
What does this line means:
<resource uri="config://spring/objects" />
and this:
<object type="Test.aspx">
<property name="AService" ref="AService" />
<property name="BService" ref="BService" />
</object>
Does config: means configuration file?
Does ref means Classes in C#?
<resource uri="config://spring/objects" /> means that the spring container should read a configuration section from an application configuration file (app.config or web.config).
<object ... is an object definition; this defines an object in your container. An object can have dependencies. In your case, the Test.aspx page has properties named AService and BService. The container will set these properties to the objects defined elsewhere in your container.
What might be a bit confusing here is the double usage of ="AService" in <property name="AService" ref="AService" />:
name=: refers to the name of the property on your class Test, there is a property defined as public IMyService AService { get; set; }
ref= : refers to another object defined in your container, there is an object definition like <object id="AService" type="MyNamespace.MyClass, MyAssembly" /> somewhere in your configuration.
The "Instantiating the container" section of the spring docs does a good job of explaining this further.

Actionscript 3 aaa namespace gets added

The following code results in nodes with "aaa" injected as the namespace. What is the correct way to convert from a ICollectionView to an XMLList without injecting a namespace?
The conversion to XMLList seems to create a default namespace called "aaa". This code is inside of a class that extends DefaultDataDescriptor.
I have this declaration at the top of this class, to be honest, I'm not sure why or when I added it, I still find namepsaces to be confusing:
var xns:Namespace = new Namespace("http://www.spicefactory.org/parsley");
I've already tried removeNamespace() on the XMLList, which didn't seem to have any effect. Thanks!
var x:XML =
<property xmlns="http://www.spicefactory.org/parsley" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="steps">
<array>
<object type="com.tn.assistant.models.Step">
<property name="id" value="2"/>
<property name="name" value="outro"/>
</object>
</array>
</property>
var chICollView:ICollectionView = getChildren(x);
var chXMList:XMLList = XMLList (chICollView);
Resulting XMLList, chXMLList =
<aaa:object type="com.tn.assistant.models.Step" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aaa="http://www.spicefactory.org/parsley">
<aaa:property name="id" value="2"/>
<aaa:property name="name" value="outro"/>
</aaa:object>
Added this in my constructor, and it fixed it:
default xml namespace = xns;

NHibernate: No persister error

In my quest to further my knowledge, I'm trying to get get NHibernate running.
I have the following structure to my solution
Core Class Library Project
Infrastructure Class Library Project
MVC Application Project
Test Project
In my Core project I have created the following entity:
using System;
namespace Core.Domain.Model
{
public class Category
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
}
In my Infrastructure Project I have the following mapping:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="Core.Domain.Model"
assembly="Core">
<class name="Category" table="Categories" dynamic-update="true">
<cache usage="read-write"/>
<id name="Id" column="Id" type="Guid">
<generator class="guid"/>
</id>
<property name="Name" length="100"/>
</class>
</hibernate-mapping>
With the following config file:
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">server=xxxx;database=xxxx;Integrated Security=true;</property>
<property name="show_sql">true</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="cache.use_query_cache">false</property>
<property name="adonet.batch_size">100</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="Infrastructure" />
</session-factory>
</hibernate-configuration>
In my test project, I have the following Test
[TestMethod]
[DeploymentItem("hibernate.cfg.xml")]
public void CanCreateCategory()
{
IRepository<Category> repo = new CategoryRepository();
Category category = new Category();
category.Name = "ASP.NET";
repo.Save(category);
}
I get the following error when I try to run the test:
Test method Volunteer.Tests.CategoryTests.CanCreateCategory threw exception: NHibernate.MappingException: No persister for: Core.Domain.Model.Category.
Any help would be greatly appreciated. I do have the cfg build action set to embedded resource.
Thanks!
The Build Action of the XML mapping file must be set to Embedded Resource in the Infrastructure assembly. When you use the following instruction in your config file: <mapping assembly="Infrastructure" /> it will look for mappings as embedded resources in this assembly.
I am guessing the problem is that your configuring your SessionFactory in your Test assembly without telling it that your mappings are in your Core assembly, something like
ISessionFactory factory = new Configuration().Configure()
.AddAssembly(typeof(Category).Assembly) <========***
.BuildSessionFactory();
If that doesn't help, post your configuration code.
Cheers,
Berryl

Resources