Menu
  • HOME
  • TAGS

Grails validation over own domain

Tag: hibernate,grails,grails-domain-class,grails-controller,grails-validation

I'm using Grails 2.4.2 and have a class Contract which has many InvoiceRecipient's. The InvoiceRecipients class has an attribute invoiceType which has 2 possible values, 'O' for the invoice-original and 'C' for an invoice-copy. As you could imagine, only one record with type 'O' is allowed for the InvoiceRecipients for one contract.

If I try to implement it as in the following snipplet, the VM runs into a StackOverflow.

Another approach I tried was a service method which iterates through the recipients array of the contract to count the records with invoiceType 'O' or I tried to do a select count through InvoiceRecipient.countByContractAndInvoiceType() to determine the number of 'O's in the contract->invoiceRecipients relation in the controller.

In both last cases, Hibernate generates an update statement for my current InvoiceRecipient record, which I try to validate. And even if the validation of the current InvoiceRecipient fails and I populate the errors-object of the instance, the record is already updated (without problems, because the constraint is not coded into the class and throws no error in "save".) And I have the logical-wrong records in the database.

class Contract implements Serializable {
    ...
    static hasMany = [recipients: InvoiceRecipient]
    ...
}

class InvoiceRecipient implements Serializable {
    static belongsTo = [contract: Contract]
    ...
    String invoiceType
    ...

    static constraints = {
        invoiceType nullable: false, maxLength: 1, inList: ['O', 'C'], validator: { val, obj ->
        /* => This generates a StackOverflow
        if (InvoiceRecipient.countByContractAndInvoiceType(obj.contract, 'O') > 1)
            return "invoiceRecipient.original.max.exceed"
        */
    }
}

Best How To :

I'd probably use something like this:

validator: { val, obj ->
if (obj.recipients.findAll{invoiceType == 'O'}.size() > 1)
        return "invoiceRecipient.original.max.exceed"

This way you should be able to prevent Hibernate from trying to flush dirty objects and in the process revalidate this object.

Decode base64 image in Grails [duplicate]

grails,groovy

Base64 uses Ascii characters to send binary files, so to retrieve your image, you basically have to decode the Base64 string back to a byte array and save it to a file. String encoded = 'iVBORw0KGgoAAAANSUhEUg' // You complete String encoded.replaceAll("\r", "") encoded.replaceAll("\n", "") byte[] decoded = encoded.decodeBase64() new File("file/path").withOutputStream...

alert grails pagination current offset value

grails,pagination

You can try "${params.offset ?: 0}" and pass this to controller, like <g:link controller="someCtrl" action="someActn" params="[offset: params.offset ?: 0]"></g:link> ...

Grails 3.0 Searchable plugin

maven,grails

The page you took the instructions from contains the following disclaimer: This portal is for Grails 1.x and 2.x plugins. Grails 3 plugins are available in Bintray https://bintray.com/grails/plugins There currenly is no version of this plugin for grails 3.x...

Grails 2.4.4 spring security role doesn't apply to user

java,spring,grails,spring-security,spring-annotations

The spring Security has an default UserDetailsService, which assigned the Roles to an User. You could debug it to see what going wrong. Or You create your own: https://grails-plugins.github.io/grails-spring-security-core/guide/userDetailsService.html HTH...

Log Grails Pre 3.0 startup time

grails

You could try: grails -Dgrails.script.profile=true Although it may require not using forked mode. Otherwise you will need to configure logging with time stamps for the org.codehaus.groovy.grails package....

unexpected token : ( subquery hql

sql,hibernate,hql

Hibernate documentation states that sub-queries are allowed only in the SELECT or WHERE clause. Note that HQL subqueries can occur only in the select or where clauses. But in the example above you have a subquery in the FROM clause of the first subquery. Have you tried consolidating the 2...

very high float value changing to infinity while retrieving from database

java,mysql,sql-server,hibernate,jpa

You should use double instead of float: // Float.MAX_VALUE = 3.4028234663852886E38f float f = Float.parseFloat("1.11111111111111E+49"); System.out.println("f=" + f); // -> f=Infinity // Double.MAX_VALUE = 1.7976931348623157E308 double d = Double.parseDouble("1.11111111111111E+49"); System.out.println("d=" + d); // -> d=1.11111111111111E49 ...

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2

You can simply create an Entity, that's mapping the database view: @Entity public class CustInfo { private String custMobile; private String profession; private String companyName; private Double annualIncome; } Make sure you include an @Id in your view as well, if that's an updatable view. Then you can simply use...

Hibernate : Stale state exception

java,spring,hibernate,spring-mvc,transactions

The reason for the exception is that you were loading a GroupCanvas before and this has a reference to the GroupSection. Then you delete the GroupSection but when the transaction commits GroupCanvas still holds a reference to the deleted GroupSection and you get the StaleStateException. As you saw, deleting the...

grails 3.0.1 scaffolded view does not show domain relationship

grails,scaffolding

What you are seeing is this issue https://github.com/grails3-plugins/fields/issues/1 which when resolved will fix this problem.

Can't Override Equals method on Java when calling contains

java,spring,hibernate

You need to provide an complmentary hashCode() method whenever providing an equals() method and visa-versa. The reason for this is to fulfil the API contracts when interacting with the objects in collections. See the site for tips on creating the code hashcode-equals The Java Docs have more information about the...

org.hibernate.ejb.event.EJB3MergeEventListener missing after upgrading from Hibernate 3 to 4.3.9

java,hibernate,jpa,ejb

So it looks like this class (and a lot of the other EJB stuff) has been renamed and moved around. I was able to replace instances of org.hibernate.ejb.event.EJB3MergeEventListener (which was located in the hibernate-entitymanager jar in version 3.6.10) with org.hibernate.event.internal.DefaultMergeEventListener (which is actually located in the hibernate-core jar in version...

Input data-validation in a restful web service (to use null-object or not to)

java,hibernate,jersey,jax-rs

In this case we generally send a 404. The URL is the identifier for the resource. If part of the URL is used as an identifier for determining the resource, then the appropriate reply for a resource not being found by that identifier, is a 404 Not Found. Generally, personally...

[B cannot be cast to java.sql.Blob

grails,gorm

static mapping = { xmlSubmission sqlType: 'blob' } ...

Hibernate delete child when parent is getting updated in same transaction

hibernate,spring-data

Please share your beans. Given your descriptionI expect you should have: @Entity @Table(name="CUSTOMER") public class Customer implements Serializable { private static final long serialVersionUID = -4505027246487844609L; @Id private String username; @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER) @Fetch(FetchMode.SUBSELECT) @JoinColumn(name="ORDER_USERNAME", nullable = false) private List<SalesOrder> salesOrders; } The important part is: @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true,...

Checking for multiple child constraint violations in Hibernate/JPA

spring,hibernate,jpa

I found a way to accomplish my end result, although it was through means I did not expect. In order to accomplish my goal, I would need to use nested transactions and SavePoints. At the end of the day, that implementation would still produce invalid data in my database, because...

Configure HikariCP + Hibernate + GuicePersist(JPA) at Runtime

java,hibernate,jpa,hikaricp,guice-persist

Try removing the persistence-unit name from the JPA properties, so instead of: Map<String, String> properties = new HashMap<>(); properties.put("myJPAunit.hibernate.hikari.dataSource.url", "jdbc:postgresql://192.168.100.75:5432/mpDb"); properties.put( + "myJPAunit.hibernate.hikari.dataSource.user", "cowboy"); properties.put( + "myJPAunit.hibernate.hikari.dataSource.password", "bebop"); you should have this: Map<String, String> properties = new HashMap<>(); properties.put("hibernate.hikari.dataSource.url",...

unable to resolve class org.apache.commons.net.ftp in grails

grails,apache-commons

In Grails you rarely add jar files to the project, you normally add dependencies. In your case you should add this line to the BuildConfig.groovy (section grails.project.dependency.resolution.plugins) compile 'commons-net:commons-net:3.3' ...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline

grails,grails-plugin

The most simple way is using site mesh. In your layout you need to put <g:pageProperty name="page.script"/> At the end of the body. Then in the page you will do something like this: <content tag="script"> <script type="application/javascript"> ... your code here ... </script> </content> Notice that the content tag (script)...

Updating Database Directly and Bypassing Hibernate - Does hibernate have a “Check and Clean All” feature?

hibernate

No, there is no such feature in Hibernate.

Groovy - timestamp from minutes

oracle,grails,groovy,timestamp

I assume you want to use the current day offset with the number of minutes given for your timestamp. Since a new Date or Timestamp will be initialized to the current time and date, you can use that and override the minute field with the values from your array. Values...

File upload with grails and jquery

jquery,grails

Use below function to send files with ajax on form submit at view end function formSubmit(){ var formData=new FormData($('form#create-form')[0]); $.ajax({url: 'createAttachment', type:'POST', data: formData, processData: false,contentType: false,dataType: 'script',success:function(result){ }}); return false } at controller side use below code to access file objects def createAttachment = { List attachmentsFiles=[] request.fileNames.each {...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa

There are lots of ways you could probably accomplish this. If you really need absolute control try this interface FoobarRepositoryCustom{ List<Foobar> findFoobarsByDate(Date date); } interface FoobarRepository extends CrudRepository<Foobar, Long>, FoobarRepositoryCustom public FoobarRespoitoryImpl implements FoobarRepositoryCustom{ @PersistenceContext private EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar...

HQL order by expression

java,sql,database,hibernate,hql

HQL doesn't support such a syntax, so you'll have to use a native query for this: List<Comment> comments = (List<Comment>) session.createSQLQuery( "select * " + "from Comment " + "where id in ( " + " select comment_id " + " from ( " + " select " + "...

Render a controller into a String

grails,grails-2.0

You can use grails include tag for this def html= g.include(controller: 'myController', action: 'myAction', params: [what:'ever']) ...

Grails: Carry forward params on g:actionSubmit is clicked

grails,gsp

I don't think that you can pass params with actionSubmit in this way. You can use params attribute of g:form tag, like <g:form params="${params}"> ... </g:form> or <g:form params="[offset: params.offset, max: params.max]"> ... </g:form> ...

Grails logging auto inject

grails,logback

add the @Slf4j annotation on your class. This local transform adds a logging ability to your program using LogBack logging. Every method call on a unbound variable named log will be mapped to a call to the logger. For this a log field will be inserted in the class. If...

Spring-MVC, Hibernate : Creating DTO objects from Domain objects

java,spring,hibernate,spring-mvc,dto

What I think that happens is Jackson tries to serialize all fields in the hierarchy based on getter methods. In some situation NullPointerException is thrown in the following method: @JsonIgnore public int getOwnedSectionId(){ return this.ownednotes.getMsectionid(); } replace it with the following method: @JsonIgnore public int getOwnedSectionId(){ if(this.ownednotes != null) return...

Unidirectional one-to-many mapping in Hibernate generates redundant updates

java,hibernate,jpa

Have you tried: @JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false, insertable=false, updatable=false) ...

grails DataSource.groovy refer bean for decoding password

grails

I don't think this will be possible. The reason for this is the lifecycle (startup) of a Spring/Grails application requires that the DataSource be parsed while setting up the Spring application context. As such, making reference to a bean in the application context isn't going to be valid because the...

How to know an object has changed compared to database

java,hibernate,jpa,playframework,playframework-1.x

To force Hibernate to start a new transaction in the playframework and thus give you a new entity manager that will return the object as it is in the database and not a reference to it, you need to specifically ask the play framework to start a new transaction through...

Error when using angular with Grails

angularjs,grails

The error that you get says: Failed to instantiate module myApp due to: {1} Which basically means angular could not create an instance of myApp. You might want at a minimum level to have this code: var myApp = angular.module('myApp',[]); function MyCtrl($scope) { } and in your HTML: <html ng-app="myApp">...

could not resolve property: userId.username

java,hibernate,criteria

Criteria does not work like EL or Java methods or attributes, you cannot refer to inner objects with a dot .. You have to create a restriction in Ticket, right? What does Ticket has? An User. Then... you have to create a new User, set the username to this User...

Blocking Updating or Inserting an Entity when using Cascade in Hibernate

java,hibernate,jpa,orm,hibernate-mapping

If you never want to modify the EntCariHareketler, you could simply annotate it with @Immutable. If you the entity is mutable but you want to disable updates from the other side, you need to set to false the insertable and updatable @JoinColumn attribute: @OneToOne(fetch= FetchType.LAZY) @JoinColumn(name="carihareketid", insertable = false,...

Hibernate Primary Key annotation returns null value

sql,spring,hibernate

Your mapping says that the ID of profile is also a join column (i.e. a foreign key referencing the user ID). That's what @PrimiryKeyJoinColumn means. But your table definition shows that you have a userId column in profile to reference the profile's user ID. So you should in fact use...

Hibernate criteria accepting %% value

java,hibernate,java-ee,orm,hibernate-criteria

Hibernate does not escape special chars in like (e.g. the percentage % sign). But there are descriptions how to solve it (escape it): Escaping special characters in Hibernate queries Using hibernate criteria, is there a way to escape special characters? Escape special characters in hibernate criteria In general we could...

what is gradle missing to map hibernate?

java,hibernate,gradle

I think the problem is not really with gradle. It's with the fact that the JPA spec stupidly requires that the classes of the entities are in the same jar/directory as the persistence.xml file. And since Gradle doesn't store the "compiled" resources in the same output directory as the compiled...

Intercepting login calls with Spring-Security-Rest plugin in Grails

rest,grails,spring-security

Yes, you can provide a custom bean that implements the RestAuthenticationSuccessHandler. Take a look at the API documentation for the class to see what you need to implement. Then it's as simple as overriding the bean in your application context: // Resources.groovy restAuthenticationSuccessHandler(MyCustomRestAuthenticationSuccessHandler) { renderer = ref('accessTokenJsonRenderer') } It might...

JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9

java,hibernate,postgresql,jpa

So the problem was that em.createNativeQuery(...) was not the correct invocation of a NamedNativeQuery in order to do that I should've invoked em.createNamedQuery(...). However, seeing that em.createNativeQuery(...) does not accept @SqlResultSetMapping it is very difficult to map the result to a custom class. The end solution was to use return...

Can't obtain connection with the DB due to very long schema validation and connection reset afterwards

java,oracle,hibernate

Have you tried the solutions in the following question? Oracle 11g connection reset error One particular answer had to do with the following comment: I could get it resolved by adding this parameter to the Hotspot JVM: -Djava.security.egd=file:/dev/./urandom This issue does not affect windows, so it might be similar to...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column

hibernate,sql-server-2008,jpa,spring-data-jpa

I just found I missed setting up hibernate dialect on LocalContainerEntityManagerFactoryBean. After setting up org.hibernate.dialect.SQLServer2008Dialect as hibernate dialect, the GenerationType.IDENTITY works fine as Neil mentioned. Below is my spring data configuration and application.properties. FYI I have multiple datasource, one is H2 embedded datasource for internal use and the other is...

Bean Creation exception, Injection of autowired dependency failed

java,spring,hibernate,spring-mvc

As you can see in the stacktrace: nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool The class GenericObjectPool is missing in your classpath. So you have to add the commons-pool.jar to your project which contains this class....

passing backbone collection to view

grails,backbone.js,handlebars

The reason you don't see any items is that the items aren't actually in the collection until after the view is rendered. Look at these two lines of code: var priceView = new PriceView({collection: prices}); prices.fetch(); The first line renders the view (since you're calling render from within initialize). However,...

How to delete multiple rows in Hibernate

java,hibernate

the user you fetch in getUserByID is queried in its own session which is closed and the user returned is detached. You should have one session per Request but you have nested sessions. Try opening a session and a transaction at the beginning of the Request and commit the transaction...

Grails: Do addTo* and removeFrom* require a call to save?

grails,gorm,grails-2.0,grails-domain-class

Neither needs a call to save() in most contexts. What you're seeing in the "some examples" link is a save to the main domain object Author, which gets persisted first, and then the other properties will make it in the database with a proper id to link back to. For...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types

grails,groovy,jax-rs

either use new ValidateToken.validate(... or make your validate method static. this is actually what the error is stating: No signature of method: static ....ValidateToken.validate() is applicable for argument types: () values: []` ...

Envers Pre/PostCollection Listener

java,hibernate,jpa,hibernate-envers

That's when you have persistent collections, e.g. fields of type List<String>, or Set<EmbeddedComponent>.

Optimistic locking not throwing exception when manually setting version field

hibernate,jpa,spring-data-jpa

Unfortunately, (at least for Hibernate) changing the @Version field manually is not going to make it another "version". i.e. Optimistic concurrency checking is done against the version value retrieved when entity is read, not the version field of entity when it is updated. e.g. This will work Foo foo =...

How can implement long running process in spring hibernate?

java,spring,hibernate

I recommend you to use DeferredResult of Spring. It´s a Future implementation, that use the http long poling technique. http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html So let´s says that you will make a request, and the server it will return you the deferredResult, and then your request will keep it open until the internal process(Hibernate)...

Spring Boot - How to set the default schema for PostgreSQL?

java,spring,hibernate,postgresql

You can try setting the default schema for the jdbc user. 1) ALTER USER user_name SET search_path to 'schema' 2) Did you try this property? spring.datasource.schema http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html...