hibernate,grails,gorm , Using like to non-string columns in Grails


Using like to non-string columns in Grails

Question:

Tag: hibernate,grails,gorm

I'm currenty working on a Grails query service that involves retrieving row/s from the database with a specific criteria called filterText.

List getAdjustmentCodes(params) {
    def filterText = params.filterText
    .
    .
    .
    adjustmentCodeList = AdjustmentCode.findAll{
        or {
            ilike('description', "%$filterText%")
            // ilike('id', "%$filterText%")
        }                       
    }

    return adjustmentCodeList
}

Notice that I've comment out the line ilike('id', "%$filterText%") because when the program reaches that line, it throws an error:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.lang.Long for value...

This is probably because the id column of that table is of type long:

class AdjustmentCode implements Serializable {
    Long id
    String description
    String type
    String status
    Date statusDate
    String lastUpdateBy
    Date lastUpdateDate

    static mapping = {
        table 'RFADJUSTCDOTB'
        version false
        id column : 'ADJUS_CD'
        description column : 'ADJUS_DESC'
        type column : 'ADJUS_TYPE'
        status column : 'ADJUS_STATCD'
        statusDate column : 'ADJUS_STATDTE'
        lastUpdateBy column : 'ADJUS_LUPDBY'
        lastUpdateDate column : 'ADJUS_LUPDDTE'
    }

    .
    .
    .
}

But I need to use the like operator for this column. For instance, the user wants to search for an adjustment with a code similar to: 00002312123. Is this the right way to use the like operator, or are there any other way. Thank you for answering.

I've seen this post, but it doesn't tell how to use non-strings on a like in an or clause.


Answer:

Well here is an alternative:

class AdjustmentCode implements Serializable {
    Long id
    String description
    .....
    String idAsString
    static mapping = {
        table 'RFADJUSTCDOTB'
        ...
        idAsString formula('to_char(id)') // Or use an equivalent fn to convert it to a String
}

You could then use ilike as follows:

ilike('idAsString', "%${filterText}%")

It's a lazy way out I suppose, but it should work.


Related:


Log Grails Pre 3.0 startup time


grails
In Grails 2.x.x is it somehow possible to log the startup time? We are currently trying to optimize the application startup and having the startup time logged would help tremendously.

Blocking Updating or Inserting an Entity when using Cascade in Hibernate


java,hibernate,jpa,orm,hibernate-mapping
I have an entity , EntHesaplasma , this entity has a relationship with EntCariHareketler entity. I have a foreign key in the EntHesaplasma entity for EntCariHareketler. I want to set a relationship between them , but I dont want to update,insert or remove operations on EntCariHareketler entity. Only I want...

Grails 2.4.4 spring security role doesn't apply to user


java,spring,grails,spring-security,spring-annotations
I have controller: class AdminController { def springSecurityService @Secured(['ROLE_ADMIN', 'ROLE_USER']) def index() { render "test"; } And user with role ROLE_ADMIN in the table: But, when I use: springSecurityService.getPrincipal().getAuthorities() There is only one role: ROLE_NO_ROLES Why? def loggedInUser = springSecurityService.currentUser; returns correct user. Config: ... grails.plugin.springsecurity.userLookup.userDomainClassName = '...' grails.plugin.springsecurity.userLookup.authorityJoinClassName =...

Bean Creation exception, Injection of autowired dependency failed


java,spring,hibernate,spring-mvc
I'm using spring hibernate in my application. I used all the required jar files but still getting bean creation exception saying the following: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'voteController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mindtree.service.VoteService com.mindtree.controller.VoteController.voteService; nested exception is...

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


hibernate
People are executing update/insert/delete sql directly against the database, as opposed to using the APIs, thus bypassing Hibernate (don't ask, it just is). As such, the audit tables are not getting updated. Does hibernate contain some kind of "Check and Clean All" feature that will update the audit tables or...

JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9


java,hibernate,postgresql,jpa
I am having a rather odd problem. I have native query which runs perfectly when executed on sql server: SELECT date_time, GREATEST(sum(count_up - count_down) OVER (PARTITION BY date_trunc('day', result.date_time) ORDER BY date_time),0) AS cum_amt FROM peoplecounting.result order BY date_time; However, using this query as native query in JPA results in...

Configure HikariCP + Hibernate + GuicePersist(JPA) at Runtime


java,hibernate,jpa,hikaricp,guice-persist
I have a java8 desktop app using GuicePersist, Hibernate, and HikariCP to communicate with a Postgres DB. I've had success getting my app to send/receive data to the DB using this META-INF/persistence.xml: <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <!-- A JPA Persistence Unit --> <persistence-unit name="myJPAunit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column


hibernate,sql-server-2008,jpa,spring-data-jpa
I want to know proper JPA annotation setup to handle MS Server 2008 R2 IDENTITY column. MS Server 2008 R2 (RTM) doesn't support SEQUENCE, but the IDENTITY gives auto increment when I tested by raw sql. However, by JPA I can't make it work by any strategy (IDENTITY, AUTO, TABLE)...

alert grails pagination current offset value


grails,pagination
I am using Grails 2.4.2. I have a list which is using pagination. When I mouse hover a number or next page icon it shows current offset number as tool tip. Can I alert this offset number or get my list's current page offset number?

How to know an object has changed compared to database


java,hibernate,jpa,playframework,playframework-1.x
I need to know if some fields of a model object has been changed before save because I need to compare the new values with the old ones. I can't touch the model classes are they are generated. My problem is that whenever I change an object in a controller...

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


grails,apache-commons
I am developing a module in which some file need to be uploaded on a ftp server for that I have added the "commons-net-3.3.jar" in my grails app & while using it import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPClientConfig import org.apache.commons.net.ftp.FTPFile import org.apache.commons.net.ftp.FTPReply It is throwing the error unable to resolve...

Optimistic locking not throwing exception when manually setting version field


hibernate,jpa,spring-data-jpa
I have a Spring Boot 1.3.M1 web application using Spring Data JPA. For optimistic locking, I am doing the following: Annotate the version column in the entity: @Version private long version;. I confirmed, by looking at the database table, that this field is incrementing properly. When a user requests an...

File upload with grails and jquery


jquery,grails
I have a form with multiple inputs plus a doc or pdf file upload. //Multiple input fields are here then upload -> <div class="controls"> <div class="fileupload ${ person?.attachment ? 'fileupload-exists' : 'fileupload-new' }" id="attachment" data-provides="fileupload" data-name="attachment"> <span class="btn btn-file"> <span class="fileupload-new">Add</span> <span class="fileupload-exists">Change</span> <input type="file" /> </span> <span class="fileupload-preview"></span>...

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


java,spring,hibernate,spring-mvc,dto
I am working on a Spring-MVC application in which I am trying to search for List of GroupNotes in database. The mapping in my project is GroupCanvas has one-to-many mapping with GroupSection and GroupSection has one-to-many mapping with GroupNotes. Because of these mappings, I was getting LazyInitializationException. As suggested on...

Hibernate Primary Key annotation returns null value


sql,spring,hibernate
i am following http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/ for learning primary key annotation. I have two classes @Id @Column @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String firstName; private String lastName; private String email; private String password; private String profession; @OneToOne(mappedBy="user" , cascade=CascadeType.ALL) private Profile profile; and my profile class @Id @Column @GeneratedValue(strategy = GenerationType.AUTO) private...

Render a controller into a String


grails,grails-2.0
I can render a template or a view into a String, but how can I render a controller into a String ? I would like to perform this kind of operation: def myAction = { ... def html = renderToString(controller: 'myController', action: 'myAction', params: [what:'ever']) render modify(html) ... } ...

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


java,hibernate,jersey,jax-rs
Below is a web service which gives the latest version among all books with a given Id. //Resource controller @Path("latestVersionBook/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionBook(long id){ bookList=service.getLatestVersionBook(id) return Response.ok(bookList).build(); //backend Service Below is the service method that uses jpa to get the books public getLatestVersionBook(long id){ Query query = entityManager.createQuery("from...

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


java,spring,hibernate,postgresql
What I am currently doing in my application.properties file is: spring.datasource.url=jdbc:postgresql://localhost:5432/myDB?currentSchema=mySchema Isn't there another property for this? Since it looks hacky and according to a post (still finding the link sorry, will update later), it is only applicable to PostgreSQL 9.4....

Spring Boot extending CrudRepository


java,spring,hibernate,spring-boot,spring-data-jpa
I'm using Hibernate in a Spring Boot app. I'm making a new CrudRepository for all my Model objects, to do basic CRUD tasks. They look like this: @Repository public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> { } But then I always need to do some additional things, like custom search queries...

passing backbone collection to view


grails,backbone.js,handlebars
I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...

unexpected token : ( subquery hql


sql,hibernate,hql
Here's my HQL query FROM com.mysite.ActeurInterne act WHERE act.acteurId IN (SELECT DISTINCT COALESCE(acteurInterne.acteurInternePrincipalId, acteurInterne.acteurId) FROM (SELECT DISTINCT acteurInterne FROM com.mysite.ActeurInterne AS acteurInterne JOIN acteurInterne.roleSet.roles AS role WHERE acteurInterne.acteurId = acteurInterne.acteurId AND acteurInterne.nom LIKE :likenom AND (role.dateFermeture IS NULL OR role.dateFermeture >= TRUNC(SYSDATE)) AND (role.dateOuverture IS NULL OR role.dateOuverture <= TRUNC(SYSDATE))...

How can implement long running process in spring hibernate?


java,spring,hibernate
as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

very high float value changing to infinity while retrieving from database


java,mysql,sql-server,hibernate,jpa
I have an entry in my database select item_numeric_value from Item_Allowed_Values where id=761 datatype of item_numeric_value is float in my db. the result I get is 1.11111111111111E+49. when I retrieve this value in java in a string , I get infinity. is there anything I am missing or doing wrong ?...

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


java,hibernate,jpa
I have defined two classes, Parent and Child. The parent can have a list of children. @Entity public class Parent { @Id @GeneratedValue(...) @SequenceGenerator(...) private long id; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false) private List<Child> children; public Parent() { children =...

How to delete multiple rows in Hibernate


java,hibernate
I tried to delete multiple rows from database using Hibernate. Its successfully done. When I refresh the .jsp page, the deleted items will shown again. Here's my code: public int deleteUserById(String id[]) { SessionFactory sf = HibernateUtil.getSessionFactory(); int flag = 0; User user; try { for (int i = 0;...

what is gradle missing to map hibernate?


java,hibernate,gradle
I have unittest to my java project. My code uses hibernate. When i run the test using junit - everything passes. When I run the test using gradle - I get a mapping error: Caused by: org.hibernate.MappingException: Unknown entity: linqmap.users.interfaces.model.UserRecord and the class: @Entity @Table(name = "users") public class UserRecord...

Checking for multiple child constraint violations in Hibernate/JPA


spring,hibernate,jpa
TL;DR: Is it possible to perform nested transactions in Hibernate that use SavePoints to rollback to specific states? So I am attempting to persist a parent entity with a OneToMany mapping to child entities. This is working fine. During this persistence, I would like to catch and log ALL constraint...

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


rest,grails,spring-security
I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts. As I am quite new to Spring Security...

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
While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

Can't Override Equals method on Java when calling contains


java,spring,hibernate
I have the following funtion that checks if a List of codigos contains a single codigos object: if (!concorrente.getJcodigoses().contains(cod)) { return "redirect:" + referrer; } I read that i need to Override the equals method like so: @Override public boolean equals(Object object) { boolean isEqual= false; if (object != null...

Envers Pre/PostCollection Listener


java,hibernate,jpa,hibernate-envers
I use Hibernate Envers with conditional logging. The documentation describes quite well how this can be done (http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch15.html#d5e4449). At 2nd item, it says you have to subclass the appropriate listeners.. The purpose of the three listeners EnversPostDeleteEventListener, EnversPostInsertEventListener and EnversPostUpdateEventListener is clear to me. However, I am not quite clear...

grails 3.0.1 scaffolded view does not show domain relationship


grails,scaffolding
I am following the example in the book "Grails a Quick-Start Guide" using Grails 3.0.1 with following domains package com.tekdays class TekEvent { static constraints = { name() city() description maxSize:5000 organizer() venue() startDate() endDate() } String city String name TekUser organizer String venue Date startDate Date endDate String description...

Grails logging auto inject


grails,logback
I use grails 3.0.2 and logback. How can I use this logger in my code, can I somehow autoinject it, like log.debug() in grails 2.x which was using org.apache.commons.logging.Log?

grails DataSource.groovy refer bean for decoding password


grails
Referring https://jira.grails.org/browse/GRAILS-3620, we need to specify a class with static methods to decode the encrypted password in DataSource config. For passwordEncryptionCodec property, is it possible to refer to a bean defined in resources.xml or any other grails bean definition files? For ex: having a decrypted Properties bean in resoures.xml or...

Error when using angular with Grails


angularjs,grails
Here is my index.gsp <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src="/js/angular.min.js"></script> </html> When I build an app, There is an error like this, Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=myApp&p1=Error%3A%…20at%20d%20(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fangular.min.js%3A17%3A381)...

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


grails,gorm,grails-2.0,grails-domain-class
In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

Hibernate criteria accepting %% value


java,hibernate,java-ee,orm,hibernate-criteria
I am using the below Hibernate code to filter workFlowName. crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE)); // crt is the criteria The problem is when I pass the value to workFlow from web (TextBox).it fetching the value correctly (I am passing sym in text box if fetch 10 records.if i pass the same...

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


grails,grails-plugin
Since there is no deferred option for: <asset:javascript src="custom_view_script.js"/> What else can be used, outside of resource plugin, to place view specific script right before the closing body tag and without declaring it globally in layout? I do know about: <asset:deferredScripts/> but that only handles on page script and not...

HQL order by expression


java,sql,database,hibernate,hql
I have two persistent classes, Comment and Vote. A Comment can be associated with many Votes and there is a @OneToMany - @ManyToOne relationship between them that's working correctly. What I'm trying to do is to sort the comments by most upvotes. A Vote is an upvote if Vote.up column...

[B cannot be cast to java.sql.Blob


grails,gorm
This is my domain class class TimesheetSubmission { Date submissionDate=new Date() String foreman String shift String jobId Date date byte[] xmlSubmission String xmlResponse static constraints = { submissionDate nullable: false foreman nullable: false shift nullable: false jobId nullable: false date nullable: false xmlSubmission nullable: true xmlResponse nullable: false } static...

Hibernate delete child when parent is getting updated in same transaction


hibernate,spring-data
I have defined two entities Customer and SalesOrder in my domain model with oneToMany relationship from customer to salesOrder. Below code deletes the sales order: SalesOrder salesOrder = salesOrderRepository.findByOrderNumber(orderNumber); if(null != salesOrder){ Customer customer = salesOrder.getCustomer(); customer.setCurrentCredit(customer.getCurrentCredit() - salesOrder.getTotalPrice()); Iterator<SalesOrder> iter = customer.getSalesOrders().iterator(); while(iter.hasNext()){ SalesOrder order = iter.next();...

Grails: Carry forward params on g:actionSubmit is clicked


grails,gsp
How to carry forward the parameters when g:actionSubmit button is clicked? Here is my gsp code: <g:checkBox name="msgCheck" checked="" value="${userInstance.emailId}"></g:checkBox> ... <g:actionSubmit class="update" action="delete" value="Delete" params="${params}"></g:actionSubmit> Here is my controller code: def delete() { try { def user_list = params.msgCheck //deleting the user //successful. redirect(action: "list", params: params) } catch...

could not resolve property: userId.username


java,hibernate,criteria
I have following entity classes: @MappedSuperclass public class AbstractEntity implements Serializable, Comparable<AbstractEntity> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") protected Integer id; @Override public int compareTo(AbstractEntity o) { return this.toString().compareTo(o.toString()); } public Integer getId() { return id; } public...

Grails 3.0 Searchable plugin


maven,grails
I've tried to use the searchable plugin in grails 3.0, but I am not sure wheather it is compatible or not. I've added compile "org.grails.plugins:searchable" to the dependencies. The build completes but yields a NotSearializableException: > Configuring > 1/1 projects > Resolving dependencies ':agent' > Resolving dependencies ': BUILD SUCCESSFUL...

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

Decode base64 image in Grails [duplicate]


grails,groovy
This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

How to call MySQL view in Struts2 or Hibernate


java,mysql,hibernate,java-ee,struts2
I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

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


java,hibernate,jpa,ejb
I am trying to upgrade from Hibernate 3.6.10 to 4.3.9 (and JPA 2.0 to 2.1). Some code in my application uses the org.hibernate.ejb.event.EJB3MergeEventListener class, which used to be in the hibernate-entitymanager jar, but is missing from the 4.3.9 version. From what I can tell, it was removed as of 4.3,...

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


java,oracle,hibernate
I have an app where I use Hibernate/Oracle 11g XE/Jboss6.2 and I am having trouble starting up the application on my homolog server at DigitalOcean (Jboss and Oracle xe installed locally). Running everything on my dev machine I have no problem at all and it starts in about 30s, but...

Hibernate : Stale state exception


java,spring,hibernate,spring-mvc,transactions
I am working on a Spring-MVC application in which I am trying to delete an object from the database. Some days back, this error all of a sudden started, and now I am unable to delete. I checked on net, but I cannot find what am I doing wrong and...