Search Results

Search found 18361 results on 735 pages for 'hibernate search'.

Page 170/735 | < Previous Page | 166 167 168 169 170 171 172 173 174 175 176 177  | Next Page >

  • Querying and ordering results of a database in grails using transient fields

    - by Azder
    I'm trying to display paged data out of a grails domain object. For example: I have a domain object Employee with the properties firstName and lastName which are transient, and when invoking their setter/getter methods they encrypt/decrypt the data. The data is saved in the database in encrypted binary format, thus not sortable by those fields. And yet again, not sortable by transient ones either, as noted in: http://www.grails.org/GSP+Tag+-+sortableColumn . So now I'm trying to find a way to use the transients in a way similar to: Employee.withCriteria( max: 10, offset: 30 ){ order 'lastName', 'asc' order 'firstName', 'asc' } The class is: class Employee { byte[] encryptedFirstName byte[] encryptedLastName static transients = [ 'firstName', 'lastName' ] String getFirstName(){ decrypt("encryptedFirstName") } void setFirstName(String item){ encrypt("encryptedFirstName",item) } String getLastName(){ decrypt("encryptedLastName") } void setLastName(String item){ encrypt("encryptedLastName",item) } }

    Read the article

  • Persistence unit is not persistent

    - by etam
    I need persistence unit that creates embedded database which stays persistent after closing EntityManager. This is my PU: <persistence-unit name="hello-jpa" transaction-type="RESOURCE_LOCAL"> <class>hello.jpa.User</class> <properties> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/> <property name="hibernate.connection.username" value="sa"/> <property name="hibernate.connection.password" value=""/> <property name="hibernate.connection.url" value="jdbc:hsqldb:target/hsql.db"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> And it deletes data after closing application.

    Read the article

  • Grails / GORM, Disable First-level Cache

    - by Stephen Swensen
    Suppose I have the following Domain class mapping to a legacy table, utilizing read-only second-level cache, and having a transient field: class DomainObject { static def transients = ['userId'] Long id Long userId static mapping = { cache usage: 'read-only' table 'SOME_TABLE' } } I have a problem, references to DomainObject are being shared due to first-level caching, and thus transient fields are writing over each other. For example, def r1 = DomainObject.get(1) r1.userId = 22 def r2 = DomainObject.get(1) r2.userId = 34 assert r1.userId == 34 That is, r1 and r2 are references to the same instance. This is undesirable, I would like to cache the table data without sharing references. Any ideas? [Edit] Understanding the situation better now, I believe my question boils down to the following: Is there anyway to disable first level cache for a specific domain class while still using second level cache?

    Read the article

  • Entities equals(), hashCode() and toString(). How to correctly implement them?

    - by spike07
    I'm implementing equals(), hashCode() and toString() of my entities using all the available fields in the bean. I'm getting some Lazy init Exception on the frontend when I try to compare the equality or when I print the obj state. That's because some list in the entity can be lazy initialized. I'm wondering what's the correct way to for implementing equals() and toString() on an entity object.

    Read the article

  • Nhibernate fires SQL commands

    - by Chris
    Hi all, when updating an entity A, NHibernate also send an SQL update command for some other entity B. A and B are not related. Just before saving entity A, the parent of entity B is loaded via a SQLQuery. Then, when accessed, B is lazy loaded (part of a collection). If I save entity A an update statement for entity B is generated as well. How can that be, that when saving an entity, another entity loaded before but is not related to the entity saved, is updated as well?! Can I somehow track where the update comes from? Btw. I am using an save event listener. Could it be that this is always triggered for entity loaded, even though they are not saved explicitly? public class EntitySaveEventListener : NHibernate.Event.Default.DefaultSaveEventListener { protected override object PerformSaveOrUpdate(SaveOrUpdateEvent e) { //auditing return base.PerformSaveOrUpdate(e); } } Update (sorry for providing not enough info): I tracked it down a bit. A select stateement on a entity called address is executed (is it lazy loaded by a parent). Then I create a new entity called Request. Right before saving this entity a session flush is called which updates the address, even though I did not call save or update on the address. Address is a collection within Request. <class name="Request" table="Request"> <bag name="addresses" access="field" cascade="all-delete-orphan" where="IsDeleted = 0"> <key column="RequestId"/> <one-to-many class="Address"/> </bag> ... // address is fetched only NHibernate.SQL: 2010-02-17 11:47:21,306 [21] DEBUG NHibernate.SQL [(null)] - SELECT addresses0_.RequestId as ServiceP8_3_, .... // session flushed here // address is updated NHibernate.SQL: 2010-02-17 11:47:34,306 [21] DEBUG NHibernate.SQL [(null)] - Batch commands: command 0:UPDATE Address SET Street = @p0, ..... Would the address be updated automatically when it is manipulated somehow even though it is not explicitly saved via it's parent (cascade)?

    Read the article

  • Customizing detection change

    - by mada
    Hi, I can now if a session contain any changes which must be synchronized with the database with session.isDirty() But i have a simple field (modification date) that i would like to be ignore by it. Example: object Person( name,age,datemodification). if i just modify the datemodification field i would like that session.isDirty() or othermethod like this to return false so at the end no sql update will occur. Thanks in advance. Regards

    Read the article

  • Handle Transaction on differents EARs

    - by rfders
    Hello, what is the best practice to handle multiple EARs and the same transaction, as far as we know we need to apply XA concepts in order transaction works correctly. but apparently in currents project that we've been working on, this is not strictly necessary for creates and updates; however if we try to retrieve any collection from an entity we get an error that say there its not an active transaction or it was closed, but if we update Entity A in Ear A and update Entity B in Ear B it works perfectly when Entity A and Entity B has different datasources, at this point we are so confused about that, because we haven't configure any xa datasource yet. how is the best approach to work with this. transaction are handles by beans and not by the container and datasource are different between EAR A and EAR B

    Read the article

  • HQL Insert Query in Grails

    - by WaZ
    I want to write an insert query in Grails. I have tried all possible combinations but cant get the syntax correct. Can anybody please help? class Person { int age int name } i tried the following: Person.executeUpdate("insert into Person values (20,30)") p.s.:Please do not mention using save()

    Read the article

  • Error: java.lang.ClassCastException

    - by theJava
    Updating the entire post. public Login authenticate(Login login) { String query = "SELECT email, id FROM Login WHERE email=? AND password=?"; Object[] parameters = { login.getEmail(), login.getPassword() }; List resultsList = getHibernateTemplate().find(query,parameters); if ( resultsList.size() == 1 ) { results = (Login)resultsList.get(0); System.out.println(results); } else { System.out.println("Error dude.... "); // error no entity or mutiple entities } return results; } I now return Login Objects. private void checkLogin() { form.commit(); Login newUser = new Login(); newUser = ilogin.authenticate(loginbean); System.out.println("Its Null Value" + newUser); if (newUser == null) { getWindow().showNotification("Login failed", LOGIN_ERROR_MSG, Notification.TYPE_WARNING_MESSAGE); } else { System.out.println(newUser); getApplication().setUser(newUser); } } When there is no matching email, i get there is no such user and also this statement does get printed out. System.out.println("Its Null Value" + newUser); But when there is a email and password matching. I get weird error. Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.intermedix.domain.Login at com.intermedix.services.LoginService.authenticate(LoginService.java:30) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy32.authenticate(Unknown Source) at com.intermedix.ui.LoginDailog.checkLogin(LoginDailog.java:106) at com.intermedix.ui.LoginDailog.access$0(LoginDailog.java:102) at com.intermedix.ui.LoginDailog$1.buttonClick(LoginDailog.java:52) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:487) ... 26 more

    Read the article

  • [N]Hibernate Sessions

    - by Jaimal Chohan
    A silly question, perhaps, but at this time of night, StackOverFlow is my only friend. I'm playing with NHibernate and wanted to factualize these 2 statements regarding Sessions in web applications. 1) You should only ever have 1 ISessionFactory per database for the lifecycle of an application. 2) You should only have 1 ISession per HttpRequest or batch of HttpRequests (i.e. conversation) [I don't want tool or framework recommendation, just want to confirm the above]

    Read the article

  • Second level cache for java web app and its alternatives

    - by EugeneP
    Between the transitions of the web app I use a Session object to save my objects in. I've heard there's a program called memcached but there's no compiled version of it on the site, besides some people think there are real disadvantages of it. Now I wanna ask you. What are alternatives, pros and cons of different approaches? Is memcached painpul for sysadmins to install? Is it difficult to embed it to the existing infrastructure from the perspective of a sysadmin? What about using a database to hold temporary data between web app transitions? Is it a normal practice?

    Read the article

  • Avoid having a huge collection of ids by calling a DAO.getAll()

    - by Michael Bavin
    Instead of returning a List<Long> of ids when calling PersonDao.getAll() we wanted not to have an entire collection of ids in memory. Seems like returning a org.springframework.jdbc.support.rowset.SqlRowSet and iterate over this rowset would not hold every object in memory. The only problem here is i cannot cast this row to my entity. Is there a better way for this?

    Read the article

  • Jpa subclass mapping

    - by Roy Chan
    I am making a POS like system. I wonder how to map subclass using JPA (this is for my DAO). Product class has product details and OrderProduct class has information about the Product and details about the order. @Entity @Table(name="products") public class Product implements Serializable{ @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.AUTO public int getId(){ return id;} /** Other get/set methods */ } @Entity @Table(name="order_products") public class OrderProduct extends Product{ @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.AUTO) public int getId(){ return id;} /** Other get/set methods */ } I got complain about duplicate @Id. But OrderProduct class really need another id than the product one. How should I map this? DB is something like this Table products id int name varchar(32) Table order_product id int quantity int productid int fk referencing product table Would @IdClass or @AttributeOverride help?

    Read the article

  • How do I use Criteria to make a join on a date field (in DB2) based on the year.

    - by HtmlTableGuru
    I have a java.util.Date field in my Object. I would like to use Criteria to select all rows that have a date field with a given year. The SQL would look like the following: SELECT * FROM GAME GM WHERE YEAR(GM.GAME_DATE) = 2010 How can I use Criteria to accomplish this? Thanks in advance. public Collection<Game> getGamesByDate(Date date){ Collection<Game> games = null; try { session.beginTransaction(); Criteria criteria = session.createCriteria(Game.class); criteria .... ... ... games = criteria.list(); } catch (HibernateException e) { e.printStackTrace(); } return games; }

    Read the article

  • PropertyPlaceholderConfigurer vs Filters -- Spring Beans

    - by John
    Hi there. I've got a question regarding the difference between PropertyPlaceholderConfigurer (org.springframework.beans.factory.config.PropertyPlaceholderConfigurer) and normal filters defined in my pom.xml. I've been looking at examples, and it seems that even though filters are defined and marked to be active by default in the pom.xml they still make use of PropertyPlaceholderConfigurer in Spring's applicationContext.xml. This means that the pom.xml has a reference to a filter-LOCAL.properties while applicationContext.xml has a reference to application.properties and they both contain the same settings. Why is that? Is that how it is supposed to be done? I'm able to run the goal mvn jetty:run without the application.properties present, but if I add settings to the application.properties that differ from the filter-LOCAL.properties they don't seem to override. Here's an example of what I mean: pom.xml <profiles <profile <idLOCAL <activation <activeByDefaulttrue </activation <properties <envLOCAL </properties </profile </profiles applicationContext.xml <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" <property name="locations" <list <valueclasspath:application.properties </list </property <property name="ignoreResourceNotFound" value="true"/ </bean <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" <property name="driverClassName" value="${jdbc.driver}"/ <property name="url" value="${jdbc.url}"/ <property name="username" value="${jdbc.username}"/ <property name="password" value="${jdbc.password}"/ </bean an example of the content of application.properties and filters-LOCAL.properties jdbc.driver=org.postgresql.Driver jdbc.url=jdbc:postgresql://localhost/shoutbox_dev jdbc.username=tester jdbc.password=tester Can I remove the propertyConfigurer from the applicationContext, create a PROD filter and disregard the application.properties file, or will that give me issues when deploying to the production server?

    Read the article

  • How can you remove a criterion from criteria?

    - by ChuckM
    Hello, For instance if I do something like: Criteria c = session.createCriteria(Book.class) .add(Expression.ge("release",reDate); .add(Expression.ge("price",price); .addOrder( Order.asc("date") ) .setFirstResult(0) .setMaxResults(10); c.list(); How can I use the same criteria instance, but remove (for example) the second criterion? I'm trying to build a dynamic query in which I'd like to let the user remove a filter, without the backend having to reconstruct the criteria from scratch. Thank you

    Read the article

  • How to invalidate / refresh a domain instance association?

    - by Kimble
    There is a bug in Grails preventing me from using removeFrom* when the node I'm trying to remove is extending the collection type. Removing the node directly from the association won't update the second level cache. A hasMany B Is there any way to manually invalidate or force a reload on an association cache? Invoking refresh() on the many side didn't do the trick.

    Read the article

  • What is the best way to implement multilingual domain objects using NHibernate?

    - by Amitabh
    I have found few links but could not decide which one is the best way. http://fabiomaulo.blogspot.com/2009/06/localized-property-with-nhibernate.html (This stores all localised language data in one field. Can be a problem if we query from Sql) http://ayende.com/Blog/archive/2006/12/26/LocalizingNHibernateContextualParameters.aspx (This one has a warning at the beginning that it is a hack and no longer supported) http://www.webdevbros.net/2009/06/24/create-a-multi-languaged-domain-model-with-nhibernate-and-c/ (This does not describe how multilingual data will be structured in the database.)

    Read the article

  • Cakephp Search Plugin: DateTime Range

    - by Chris
    I am trying to search a model by dates using the CakePHP Search plugin The idea is: The user enters a date of a flight and the engine returns all flights within +- one day of that. My form: <?php echo $form->create('Flight', array( 'url' => array_merge(array('action' => 'find'), $this->params['pass']) )); echo $form->input('departure', array('div' => false, 'dateFormat' => 'DMY','timeFormat' => 'NONE')); echo $form->submit(__('Search', true), array('div' => false)); echo $form->end(); ?> My flight model: public $filterArgs = array( array('name' => 'departure', 'type' => 'expression', 'method' => 'makeRangeCondition', 'field' => 'ABS((TO_Days(Flight.departure))-( TO_Days(?))) < 2') ); The controller: public $presetVars = array( array('field' => 'departure', 'type' => 'expression') ); public function find() { $this->Prg->commonProcess(); $this->paginate['conditions'] = $this->Flight->parseCriteria($this->passedArgs); $this->set('flights', $this->paginate()); } When I try to search, the values for departure are packed in an array; Array ([departure] => Array ) And the filterArgs(...) function doesn't seem to understand this. What is the correct way to do this?

    Read the article

  • Grails: Querying Associations causes groovy.lang.MissingMethodException

    - by Paul
    Hi, I've got an issue with Grails where I have a test app with: class Artist { static constraints = { name() } static hasMany = [albums:Album] String name } class Album { static constraints = { name() } static hasMany = [ tracks : Track ] static belongsTo = [artist: Artist] String name } class Track { static constraints = { name() lyrics(nullable: true) } Lyrics lyrics static belongsTo = [album: Album] String name } The following query (and a more advanced, nested association query) works in the Grails Console but fails with a groovy.lang.MissingMethodException when running the app with 'run-app': def albumCriteria = tunehub.Album.createCriteria() def albumResults = albumCriteria.list { like("name", receivedAlbum) artist { like("name", receivedArtist) } // Fails here maxResults(1) } Stacktrace: groovy.lang.MissingMethodException: No signature of method: java.lang.String.call() is applicable for argument types: (tunehub.LyricsService$_getLyrics_closure1_closure2) values: [tunehub.LyricsService$_getLyrics_closure1_closure2@604106] Possible solutions: wait(), any(), wait(long), each(groovy.lang.Closure), any(groovy.lang.Closure), trim() at tunehub.LyricsService$_getLyrics_closure1.doCall(LyricsService.groovy:61) at tunehub.LyricsService$_getLyrics_closure1.doCall(LyricsService.groovy) (...truncated...) Any pointers?

    Read the article

  • JPA One to Many using JoinTable Error

    - by user553015
    I am trying to model 1:N (Person & Address) relationship using a junction table (Person_Address). 1.Person (personId PK) 2.Address (addressId PK) 3.PersonAddress ( personId, addressId composite PK, personId FK references Person, addressid FK references Address ) @Entity public class Person { @OneToMany @JoinTable( name="PersonAddress", joinColumns = @JoinColumn( name="personId"), inverseJoinColumns = @JoinColumn( name="addressId") ) public Set<Address> getAddresses() {...} ... } I encounter following error. Not able to find any solution. Caused by: org.hibernate.MappingException: Could not determine type for: com.realestate.details.Address, at table: Person, for columns: [org.hibernate.mapping.Column(address)] at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:269) at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253) at org.hibernate.mapping.Property.isValid(Property.java:185) at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:440) at org.hibernate.mapping.RootClass.validate(RootClass.java:192) at org.hibernate.cfg.Configuration.validate(Configuration.java:1108) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1293)

    Read the article

  • TransactionRequiredException on OptimisticLockException

    - by João Madureira Pires
    Hi there. I have the following class that generates sequencial Card Numbers. I'm trying to recover from OptimisticLockException, by calling recursively the same method. however, i'm getting TransactionRequiredException. Dows anyone knows how to recover from OptimisticLockException in my case? Thanks a lot in advance @Name("simpleAutoIncrementGenerator") public class SimpleAutoIncrementGenerator extends CardNumberGenerator{ private static final long serialVersionUID = 2869548248468809665L; private int numberOfRetries = 0; @Override public String generateNextNumber(CardInstance cardInstance, EntityManager entityManager) { try{ EntityCard card = (EntityCard)entityManager.find(EntityCard.class, cardInstance.getId()); if(card != null){ String nextNumber = ""; String currentNumber = card.getCurrentCardNumber(); if(currentNumber != null && !currentNumber.isEmpty()){ Long numberToInc = Long.parseLong(currentNumber); numberToInc ++; nextNumber = String.valueOf(numberToInc); card.setCurrentCardNumber(nextNumber); // this is just to cause a OptimisticLock Exception try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } entityManager.persist(card); entityManager.flush(); return nextNumber; } } }catch (OptimisticLockException oLE) { System.out.println("\n\n\n\n OptimisticLockException \n\n\n\n"); if(numberOfRetries < CentralizedConfig.CARD_NUMBER_GENERATOR_MAX_TRIES){ numberOfRetries ++; return generateNextNumber(cardInstance,entityManager); } }catch (TransactionRequiredException trE) { System.out.println("\n\n\n\n TransactionRequiredException \n\n\n\n"); if(numberOfRetries < CentralizedConfig.CARD_NUMBER_GENERATOR_MAX_TRIES){ numberOfRetries ++; return generateNextNumber(cardInstance,entityManager); } }catch (StaleObjectStateException e) { System.out.println("\n\n\n\n StaleObjectStateException \n\n\n\n"); if(numberOfRetries < CentralizedConfig.CARD_NUMBER_GENERATOR_MAX_TRIES){ numberOfRetries ++; return generateNextNumber(cardInstance,entityManager); } } return null; } }

    Read the article

< Previous Page | 166 167 168 169 170 171 172 173 174 175 176 177  | Next Page >