Giter Club home page Giter Club logo

hibernate-generic-dao's People

Contributors

dwolverton avatar

Watchers

 avatar  avatar

hibernate-generic-dao's Issues

Consider adding HQL query helper methods...

It might be nice to have these methods on our DAOImpl:
protected List executeQuery(String query)
protected List executeQuery(String query, Object... params)
protected Object executeQueryUnique(String query)
protected Object executeQueryUnique(String query, Object... params)

Why:
(1) This makes a little bit simpler interface than 
getSession().createQuery("some hql").list()

or

Query query = getSession().createQuery("some hql");
query.setParameter(0, "Holiday");
query.setParameter(1, "Bruce");
return query.list();

(2) These could help abstract developer changes to DAOs from the underlying 
technology. This way we could have an underlying Hibernate or EJB 
implementation with the same code on top of it. (Note: I'm not sure how 
helpful this really is.)

Why not:
(1) The developer may prefer to use criteria.
(2) It is only useful in limited situations because it limits a lot of the 
hibernate query functionality.
(3) It doesn't save that much code or make it that much more readable.
(4) It adds more code to be maintained in this project and ported to 
different implementations.



Original issue reported on code.google.com by dwolvert on 29 Oct 2008 at 2:58

Add tests for filtering collection properties

Hibernate allows filtering on collection properties, but we don't have any 
tests for this functionality.

For example, if I filter on "residents.firstName = 'Bob'", this works in 
HQL, but does it work with this framework?



Original issue reported on code.google.com by dwolvert on 1 Dec 2008 at 10:22

Fetch mode FETCH_LIST and FETCH_ARRAY return unexpected result when only one fetch specified

What steps will reproduce the problem?
1. Create a Search.
2. Add exactly one fetch.
3. Set fetchMode to FETCH_LIST or FETCH_ARRAY.
4. Run the Search in any Generic or General DAO.

EXPECTED RESULT:
List of Lists with one element each or list of Arrays with one element each.

ACTUAL RESULT:
Both fetch modes return just a List of Objects. Each object is what should
be the single element in the List or Array.

This is the default behavior of Hibernate. We need to find a way to
override it. And perhaps we should have a new fetch mode FETCH_SINGLE.

The reason this behavior is undesirable for us is that searches may be
dynamically built by application users in a custom search or something and
we don't want to have to write special code for the exception where they
only select one column to display.


Original issue reported on code.google.com by dwolvert on 6 Aug 2008 at 1:55

process collection fields from queries

HQL like these:
select h.id, h.residents from Home h

select p.id, elements(p.limbs) from LimbedPet p

return a row for each collection element. We could post-process these 
results to return a Collection for the field instead.

For example, if a query returns:
ID, LIMBS
 1, "front"
 1, "back"
 2, "left"
 2, "right"

process the results and return:
ID, LIMBS
 1, ["front", "back]
 2, ["left", "right"]



Original issue reported on code.google.com by dwolvert on 19 May 2009 at 3:02

[REQ] Start Result and End Result

In my application, client side often ask data to the server based on a First 
Result and a Last 
Result. It's different from paging that you have a fixed max results.

Would be nice to have this feature on your Search object.

Nowadays I extend your Search class and add this method:

public Search setLastResult(int lastResult)
{
    if (this.getFirstResult() == -1)
    {
        throw new IllegalArgumentException("First Result must be set!");
    }
    if(lastResult < this.getFirstResult())
    {
        throw new IllegalArgumentException("Last Result must be greater than First Result!");
    }
    this.setMaxResults(lastResult - this.getFirstResult() + 1);
    return this;
}

If it's against your patterns, please ignore.

Thanks.

Original issue reported on code.google.com by [email protected] on 29 Jun 2009 at 11:00

Add get method that allows setting properties to be fetched

For example, if I want to load a cat and join-fetch its list of friends:
catDao.find(catId, "friends");

Or if I want to join-fetch it's friends and children:
catDao.find(catId, "friends", "children");

Original issue reported on code.google.com by dwolvert on 15 Jul 2009 at 9:12

New methods in IGenericDao

It would be nice to allow the load/get with LockMode.

For example, in BaseDaoImpl, to load and lock an entity : 

protected <T> T _load(Class<T> type, Serializable id, LockMode lock) {
   return (T) getSession().load(type, id, lock);
}

Thanks !

Original issue reported on code.google.com by [email protected] on 26 Aug 2009 at 12:36

Order by null or not-null on an entity relationship

There is no way to order the results based on if a relationship exists or
not.  I'd like to create a sorted list of entities, with all of the
entities that do not have a relation with another entity sorted together.

For instance, there is a 1-to-1 relationship between a Game (i.e. a soccer
game) and a FieldSlot (i.e. a time span that a soccer field is available).
 A game and a fieldslot can exist separately without be associated.  There
should be a way to list all games, and order them so that the ones that
haven't been assigned to a fieldslot are listed first. This currently isn't
possible.

Furthermore, I'd like to be able to order the games that do have fieldslots
by properties within the fieldslot, such as Fieldslot.startTime.  That way,
all games would be listed, with those games that don't have fieldslots
listed first, then the rest of the games ordered by their
fieldslot.startTime value.

See this mailing list thread (around the 7th or 8th post) in this topic for
more details:
http://groups.google.com/group/java-generic-dao/browse_thread/thread/8010f6f7176
59c4d


Original issue reported on code.google.com by [email protected] on 6 Aug 2009 at 9:57

Can we use Join in search functionality

Hi,

 I have objects mapped with many-to-one relationship, when i use the search
() method, i see separate SQLs were fired on databse for each objcet, 
Instead I want to use Join, can you please advice.

Eg: I have table Mobile has many-to-one relation with Location and 
Provider tables. when I tried to get location and provider information 
from Mobile using lazy="flase" and fetch="join", still I see three sqls 
firing.
HibernateSQL1: select mobile0_.MSC_ID as MSC1_1_, mobile0_.RANGE_FROM as 
RANGE2_1_, mobile0_.RANGE_TO as RANGE3_1_, mobile0_.LOCATION_ID as 
LOCATION4_1_, mobile0_.PROVIDER_ID as PROVIDER5_1_ from 
hibernatedb.MSC_CODES mobile0_ where mobile0_.RANGE_FROM>=? and 
mobile0_.RANGE_TO<=?

HibernateSQL2: select location0_.LOCATION_ID as LOCATION1_2_0_, 
location0_.LOCATION_CODE as LOCATION2_2_0_, location0_.LOCATION_NAME as 
LOCATION3_2_0_ from hibernatedb.LOCATION location0_ where 
location0_.LOCATION_ID=?

HibernateSQL3: select provider0_.PROVIDER_ID as PROVIDER1_3_0_, 
provider0_.PROVIDER_CODE as PROVIDER2_3_0_, provider0_.PROVIDER_NAME as 
PROVIDER3_3_0_ from hibernatedb.PROVIDER provider0_ where 
provider0_.PROVIDER_ID=?

instead I want to use join between three tables.


Original issue reported on code.google.com by [email protected] on 14 May 2009 at 4:21

deleteById( id ) throws null pointer if the id does not exist

I think the correct behavior would be to do nothing or return false.  (same
as if you pass in a null id)

Here is a patch that makes the change for: HibernateDAOHQLImpl.java

Index: src/main/java/com/trg/dao/hibernate/HibernateDAOHQLImpl.java
===================================================================
--- src/main/java/com/trg/dao/hibernate/HibernateDAOHQLImpl.java       
(revision 110)
+++ src/main/java/com/trg/dao/hibernate/HibernateDAOHQLImpl.java       
(working copy)
@@ -76,10 +76,15 @@
         * Delete the object of the specified class with the specified id
from the
         * database.
         */
-       protected void _deleteById(Serializable id, Class klass) {
-               if (id == null)
-                       return;
-               getSession().delete(getSession().get(klass, id));
+       protected boolean _deleteById(Serializable id, Class klass) {
+               if( id != null ) {
+               Object v = getSession().get(klass, id);
+               if( v != null ) {
+                 getSession().delete( v );
+                 return true;
+               }
+               }
+               return false;
        }

        /**




Original issue reported on code.google.com by [email protected] on 21 Nov 2008 at 11:50

POJO result mode

Add a way to return results as POJOs, similar to the way hibernate 
generally returns entities, except (1) not lazy-loading proxies and (2) 
only load the specified fields.

Maybe something like this:

Search s = new Search();
s.addField("firstName").addField("lastName").addField("age");
s.setResultMode(Search.POJO);


While we're at it how about an varargs addFields method:

s.addFields("firstName", "lastName", "age");

Original issue reported on code.google.com by dwolvert on 13 Jul 2009 at 3:45

Search for Collection-Members fails

Scenario:
DB entity "Person" has a "many-to-many" assoziation "friends" which are
"Person".

How to search for persons which have a special friend X.

First I tried Filter.some("friends", Collection<X>) which results in
"**INVALID VALUE - NOT A FILTER: ..." .

I solved this by by doing something like 
Filter.some("friends", Filter.in("id", Collection<X.id()>))

Original issue reported on code.google.com by [email protected] on 13 May 2009 at 1:46

ClassCastException on filter values

What steps will reproduce the problem?
Run a search with a filter on a property of type Long but use and Integer
for the value instead of a Long.

What is the expected output? What do you see instead?
The framework should automatically convert this, perhaps logging a warning.
If it cannot convert a type, it should throw a meaningful error.

Instead we're just getting an obscure ClassCastException in Hibernate when
it runs the query. This is hard to track down.


Original issue reported on code.google.com by dwolvert on 11 Aug 2008 at 5:15

Lost System.out

Into the class: com.trg.search.hibernate.HibernateSearchProcessor

into function public "List search(Session session, Class<?> searchClass, 
ISearch search)" line 96 
has a lost System.out.println.

It should be changed to:

if (logger.isDebugEnabled())
{
    logger.debug(hql)
}

Or something like that.

Original issue reported on code.google.com by [email protected] on 19 Jun 2009 at 6:50

HibernateDAOImpl with Spring 2.5 annotations and plain Hibernate

Hello again,

as of 2.5 one could think of using the 1.5 Annotations based configuration.
Also it's nowadays rather recommended to use "plain" Hibernate instead of
extending HibernateDaoSupport or injecting HibernateTemplate, see
http://blog.springsource.com/2007/06/26/so-should-you-still-use-springs-hibernat
etemplate-andor-jpatemplate/
- you won't loose the benefits as especially Spring's transaction and
exception handling, see e.g.
http://static.springframework.org/spring/docs/2.5.x/reference/orm.html#orm-hiber
nate-straight

Please find attached a modified version of your HibernateDAOImpl which
takes this under consideration. Hope it's of any use for you.


Best regards from Europe, Germany, Berlin

Karsten Gresch

PS: As one can't modify the severity level of an "issue" as well as not the
type, this post will initially appear as "Defect", which I do not intend,
of course.

Original issue reported on code.google.com by [email protected] on 15 Oct 2008 at 10:36

Attachments:

SearchToQLProcessor doesn't watch for @Embedded

What steps will reproduce the problem?
1. Create an Entity that has an Embedded property
2. Create a search on that Entity with a filter on a property on the
Embedded object.
3. Run the search.

What is the expected output? What do you see instead?
Expected output would be a valid query.  As written, it generates a
NullPointerException in HqlSqlWalker (sorry, don't have the specific stack
trace anymore).  The SearchToQLProcessor is thinking that the Embedded
class needs to be aliased, which it isn't.

What version of the product are you using? On what operating system?
0.3.2 on both Linux and Windows (Java 1.6, Hibernate 3.2.6 and 3.3.1)

Please provide any additional information below.
Not a real easy fix to this.  I'm currently doing some reflection to see if
the property is embedded, however you could also put the onus on the
creator of the filter to specify if this is an embedded property.

Original issue reported on code.google.com by [email protected] on 15 Dec 2008 at 9:41

Add merge method

Consider adding merge method to DAOs. Refactor RemoteDAO to use merge/fetch
instead of update.

Why: Update can cause issues if there is already an instance of the entity
attached to the session.
  Actually I had trouble overriding update in the service layer because of
this conflict. It definitely makes sense for the RemoteDAO to use merge.
However, we still have to implement update in case it is used elsewhere,
especially if we have createOrUpdate.

Why Not: With RemoteDAO there will never be another instance of the entity
in the session. (is this true?) It means more methods that have to be
overridden if the update/merge needs to be overridden.

Keep thinking...

Original issue reported on code.google.com by dwolvert on 26 Aug 2008 at 3:42

Trouble following reverse relationship of OneToOnes

See: http://groups.google.com/group/java-generic-
dao/browse_thread/thread/8010f6f717659c4d

Example mapping:
class Game {
  @Id
  Long id;

  @OneToOne()
  TimeSlot timeSlot;

  ...
}

class TimeSlot {
  @Id
  Long id;

  @OneToOne(mappedBy="timeSlot")
  Game game;

  ...
}

In this case, a search like
new Search(Game.class).addFilterNull("timeSlot");
works to find all games that are not assigned to time slots.

But a search like
new Search(TimeSlot.class).addFilterNull("game");
does NOT work correctly to find time slots without games.

One work-around is to use
new Search(TimeSlot.class).addFilterNull("game.timeSlot");

I also wonder if
new Search(TimeSlot.class).addFilterNull("game.id") would work, but I don't 
know.

Original issue reported on code.google.com by dwolvert on 7 Aug 2009 at 12:11

Using Enums for Filter operator

A good idea would be to use an Enum for the Filter Operator. 

For example : 

public static final int OP_EQUAL = 0, OP_NOT_EQUAL = 1, OP_LESS_THAN = 2,
OP_GREATER_THAN = 3, OP_LESS_OR_EQUAL = 4,...

would be : 

public enum FilterOperator {
    EQUALS(0),
    NOT_EQUAL(1) //... More operators

    private int filterValue;

    private FilterOperator(int filterValue) {
        this.filterValue = filterValue;
    }

    public int getFilterValue() {
        return filterValue;
    }
}

For the first step, you could simply add this enum and provide a method to
construct filter from the enum (which calls
setOperator(enumFilter.getFilterValue())) and continue to use int in the
SearchProcessor, but, IMO the design will be better with an enum :)


Thanks 

Original issue reported on code.google.com by [email protected] on 26 Aug 2009 at 1:07

Util.getExpectedClass needs to conform to Hibernate

The method currently assumes that Hibernate is using the default property 
accessor method of getters and setters. It also assumes that the hibernate 
property names always match these getters and setters.

I recommend using a pluggable implementation of this method that is 
implemented for Hibernate using Hibernate class meta data.

The reason this should be pluggable, is that we are trying to keep open the 
possibility of using another framework underneath the DAO interfaces, like 
some other J2EE persistence implementation.

Original issue reported on code.google.com by dwolvert on 25 Nov 2008 at 7:38

Query Helper Methods?

Look into value of adding query helper methods.

For example:

protected List query(String hql, Object... params);
protected List namedQuery(String queryName, Object... params);
protected Object queryUnique(String hql, Object... params);
protected List sqlQuery(String sql, Object... params);

maybe the params can even include param names...
namedQuery("findByName", "firstName", first, "lastName", last);

Original issue reported on code.google.com by dwolvert on 23 Dec 2008 at 10:21

Create RemoteDAO interfaces for specific remote client platforms

Have a single base RemoteDAO that is called from separate thin classes that 
expose the functionality remotely.

For example the RemoteDAO would provide a method find(Class<?> klass, 
Serializable id). The interface class for Flex would provide a method 
find(String className, Serializable id) that is called directly from Flex.

This way if some of the methods or parameters are not usable for a 
particular technology, a workable interface class could be customized for 
that technology.


Original issue reported on code.google.com by dwolvert on 1 Dec 2008 at 8:29

Released under which License?

I'm looking to use your "library" into my projects, but....

Nowhere I could find the license that this project has been licensed.

If it's still a open issue, I could suggest LGPL, as it's commercial friendly, 
and still is a true Open 
Source.

Nice work!

Original issue reported on code.google.com by [email protected] on 20 May 2009 at 3:39

split search.fetch into search.select and search.eager

We have been using the fetch option on search for two very distinct things:
(1) selecting individual properties to return for each result
(2) eagerly fetching relationships of the main result entity

Which of these operations is performed is determined by the search's fetch 
mode.

It seems to me that it might be better to separate these two ideas to avoid 
confusion. An additional benefit is that it may be possible to do both at 
the same time: For example if the root search entity is a kitten and the 
mother property should be returned and the list of the mother's children 
should be eagerly fetched.

I'm trying to decide what to call these two individual options. Right now 
I'm considering "select" for (1) and "eager" or maybe "fetch" or "fill" for 
(2).

Original issue reported on code.google.com by dwolvert on 17 Dec 2008 at 4:11

Option to ignore case on sorts

Add an option on sort whether or not to ignore case when sorting. Use a 
sensible default.

Original issue reported on code.google.com by dwolvert on 26 Dec 2008 at 4:08

Sub class a dao implementation

First, Great job, we use your generic dao in our project and it's very handy !

What steps will reproduce the problem?
1. create an implementation of GenericDAOImpl<ModelClass, IdClass> named
ParentDao 
2. extend ParentDao in ChildDao
3. new ChildDao();

What is the expected output? What do you see instead?
Constructor threw exception; nested exception is
java.lang.ClassCastException: java.lang.Class cannot be cast to
java.lang.reflect.ParameterizedType

What version of the product are you using? On what operating system?
Java 6 64 bits, ubuntu 8.10, but it's irrelevant.
Present in r590.

Please provide any additional information below.
It's a common issue with Generics. This blog entry shows a solution :
http://www.artima.com/weblogs/viewpost.jsp?thread=208860

Having the choice between an empty constructor (which would infer the
persistent class' type from the generic argument) and a contructor that
takes the persistent class as an argument would be a great solution if you
don't want to implement the whole solution :)

Thanks a lot !

Original issue reported on code.google.com by [email protected] on 30 Jul 2009 at 8:46

jar version 0.2, source version 0.1?

Hi,

first - I really like your flexible approach implementing to levels of
GenericDao support, the completely generic GeneralDao and the extensible
one. Also the Search object reveils an excellent concept. Looking forward
to see more, you folks rock!

As I checked out the sources from SVN I noticed that pom.xml still is on
version 0.1 though you publish a binary with sources as of version 0.2.

Assuming that your featured binary is more up-to-date, I've overwritten the
check out files with the sources included in the jar.

Would be great if you could synchronise this, or even better, offer a Maven
repository for your project.

Also I could not run 'mvn install' as the tests failed because of missing
tests in TestBase. So I excluded this and it worked. Modified pom.xml as
attached.

Best regards from Europe, Germany, Berlin,

Karsten Gresch

Original issue reported on code.google.com by [email protected] on 9 Oct 2008 at 12:19

Attachments:

What about ignoring case in comparison Filters? (=,> ,< ,>= ,<=, IN)

When comparing strings, case can be an important factor. Right now we have 
an ignore case option for the LIKE comparison. Should we have the same 
option for the other string comparison operators?


Original issue reported on code.google.com by dwolvert on 13 Mar 2009 at 4:40

junit dependency missing in pom

I checked out the source project and found that
com.trg.test.TestCaseSpringAutoWire.java couldn't find junit TestCase. 
Added junit to the pom and it all compiled properly:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
        <version>4.5</version>
    <scope>test</scope>
</dependency>


Original issue reported on code.google.com by [email protected] on 23 Feb 2009 at 8:13

save() doesn't get the id of the entity

Caused by: java.lang.NullPointerException
        at
com.trg.dao.hibernate.HibernateBaseDAO._saveOrUpdateIsNew(HibernateBaseDAO.java:
158)
        at com.trg.dao.hibernate.GeneralDAOImpl.save(GeneralDAOImpl.java:87)
        at model.db.dbOperations.changeUserPass(dbOperations.java:67)


the method save was called in this way:

 public static boolean changeUserPass(String username, String newPass) {
           UniversalDAO dao=new UniversalDAO();
           User u=dao.find(User.class, username);
           u.setPassword(utils.CryptoUtils.hexMD5(newPass));
           dao.save(u);
           return true;
    }

and the entity is mapped by annotations:

     @Id 

    @Column(name="username", unique=true, nullable=false, length=20)
    public String getUsername() {
        return this.username;
    }



in Hibernate General DAOs why don't you use the native SaveOrUpdate()
method of Hibernate Session for this purpose?

in my app i resolved in this way (waiting for your bugfix)

/**
 *
 * @author stefano
 */
public class UniversalDAO extends GeneralDAOImpl {


    @Override
    protected Session getSession() {
            return SessionManager.currentSession();
    }


    public boolean save2(Object entity) {
        Session sess=getSession();
        Transaction tx = sess.beginTransaction();
        tx.begin();
        sess.saveOrUpdate(entity);
        tx.commit();
        return true;
    }



}




Original issue reported on code.google.com by rastrano on 25 Aug 2009 at 12:09

Add support for findByExample

I'm seriously considering using the hibernate-generic-dao library in a
project.  I'm doing some major refactoring and wish to really simplify the
service layer.  This project looks very useful, especially the Search features.

However, my project's existing DAO's are using something similar to the
findByExample(T entity) methods shown here:
http://www.hibernate.org/328.html

Would it be possible to add the following methods (or something similar) to
the DAOs?

public List<T> findByFilter(T filterEntity);
public List<T> findByFilter(T filterEntity, String[] excludeProperty);
public int countByFilter(T filterEntity);
public int countByFilter(T filterEntity, String[] excludeProperty);

Or perhaps modify the Search object so that it can be instantiated with an
example entity (a filter entity)?

I like the Search object for doing fine tuned searching.  But there are
many cases when an example instance of the entity would be simpler to use
as a filter.

I think I'll just start implementing this myself.  But it would be nice to
hear opinions about it and if my efforts could be contributed back to the
project.


Original issue reported on code.google.com by [email protected] on 23 Feb 2009 at 8:26

HibernateMetadataUtil not working with proxy objects.

I am getting the following error while trying to save an object (using 
version 0.4.3):

java.lang.IllegalArgumentException: Unable to introspect class
model.user.UserRole$$EnhancerByCGLIB$$85928456. The class is not a
registered Hibernate entity
com/trg/search/hibernate/HibernateMetadataUtil.java:78:in `get'
com/trg/search/hibernate/HibernateMetadataUtil.java:48:in `getId'
com/trg/dao/hibernate/BaseDAOImpl.java:144:in `_saveOrUpdateIsNew'
com/trg/dao/dao/standard/GenericDAOImpl.java:86:in `save'
entity.user.UserRoleManager:-1:in `save'
sun/reflect/DelegatingMethodAccessorImpl.java:25:in `invoke'
java/lang/reflect/Method.java:597:in `invoke'

The problem comes because Hibernate's getClassMetadata(Class<?>) method, 
does not recognize the class model.user.UserRole$$EnhancerByCGLIB$$85928456 
as a registered entity even though it is a proxy for model.user.UserRole, 
which is a registered entity.

We will need to fix our HibernateMetadataUtil class to deal with this 
situation.

Thanks Jas for reporting this.

Original issue reported on code.google.com by dwolvert on 26 May 2009 at 2:20

Fetch mode cannot be used with generic DAO

The search() method on GenericDAO returns List<T> so it cannot return lists
of Object[], List and Map<String, Object> types that are returned when
fetch mode is other than FETCH_ENTITY.

One possible solution is to add another method to GenericDAO for getting a
generic List back. Something like:

List searchWithFetchMode(Search search)"

Hopefully a better name can be found.

Original issue reported on code.google.com by dwolvert on 6 Aug 2008 at 2:57

Check for null values in search params

I struggled for a while to figure why I got the error:

Caused by: java.lang.NullPointerException
    at java.util.regex.Matcher.getTextLength(Matcher.java:1140)
    at java.util.regex.Matcher.reset(Matcher.java:291)
    at java.util.regex.Matcher.<init>(Matcher.java:211)
    at java.util.regex.Pattern.matcher(Pattern.java:888)
    at
com.trg.dao.BaseSearchProcessor.securityCheckProperty(BaseSearchProcessor.java:6
19)
    at com.trg.dao.BaseSearchProcessor.securityCheck(BaseSearchProcessor.java:583)
    at com.trg.dao.BaseSearchProcessor.generateQL(BaseSearchProcessor.java:86)
    at
com.trg.dao.hibernate.HibernateSearchProcessor.search(HibernateSearchProcessor.j
ava:73)
    at
com.trg.dao.hibernate.HibernateSearchProcessor.searchAndCount(HibernateSearchPro
cessor.java:144)
    at com.trg.dao.hibernate.BaseDAOImpl._searchAndCount(BaseDAOImpl.java:544)
    at
com.trg.dao.dao.standard.GenericDAOImpl.searchAndCount(GenericDAOImpl.java:106)


Eventually I figured out this is because I did not register my class with
hibernate.  oops!

(using version 4.1)


Original issue reported on code.google.com by [email protected] on 27 Jan 2009 at 9:17

Saving not working with proxy objects

What steps will reproduce the problem?
1. Try to save an hibernate proxy object not in the Session. Here is a test
case : 


    public void testUpdateProxy() throws HibernateException, SecurityException,
            NoSuchMethodException {
        initDB();
        Address address = papaA.getHome().getAddress();
        try {
            Serializable id = address.getId();

            // When working with 2 differents session, the session.contains(entity)
returns false
            // see in _exists(Object entity) in HibernateBaseDAO 
            SessionImplementor openSession = (SessionImplementor)
target.getSessionFactory().openSession();

            Address proxy = (Address) JavassistLazyInitializer.getProxy(
                    Address.class.getName(),
                    Address.class,
                    new Class[] { HibernateProxy.class },
                    Address.class.getMethod("getId"),
                    Address.class.getMethod("setId", Long.class),
                    new AnyType(Hibernate.LONG, Hibernate.SERIALIZABLE),
                    id,
                    openSession
            );



            target.saveOrUpdateIsNew(proxy);

            Address address2 = target.get(Address.class, id);

            assertEquals("update on the proxy should work ", proxy.getCity(),
                    address2.getCity());

        } catch (Exception e) {
            e.printStackTrace();
            fail(e.getMessage());
        }

    }




What is the expected output? What do you see instead?
The test should pass. 

WARN    2009-10-01 14:42:22.285 org.hibernate.hql.QuerySplitter.concreteQueries() 
        no persistent classes found for query class: select id from
test.trg.model.Address_$$_javassist_5 where id = :id 
org.hibernate.QueryParameterException: could not locate named parameter [id]
    at
org.hibernate.engine.query.ParameterMetadata.getNamedParameterDescriptor(Paramet
erMetadata.java:99)
    at
org.hibernate.engine.query.ParameterMetadata.getNamedParameterExpectedType(Param
eterMetadata.java:105)
    at
org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:437)
    at
org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:407)
    at com.trg.dao.hibernate.HibernateBaseDAO._exists(HibernateBaseDAO.java:634)
    at com.trg.dao.hibernate.HibernateBaseDAO._exists(HibernateBaseDAO.java:623)
    at
com.trg.dao.hibernate.HibernateBaseDAO._saveOrUpdateIsNew(HibernateBaseDAO.java:
163)
    at
test.trg.dao.hibernate.HibernateBaseDAOTester.saveOrUpdateIsNew(HibernateBaseDAO
Tester.java:165)



What version of the product are you using? On what operating system?
trg-dao 0.5.0



I join a patch that corrects the problem.

P.S. : how can we contribute to the code ?


Original issue reported on code.google.com by [email protected] on 1 Oct 2009 at 12:49

Attachments:

Return type of searchGeneric

currently, searchGeneric returns List and searchUniqueGeneric returns 
Object. This means it must be explicitly casted when used, for example:

//Note: this also causes a compiler warning for unsafe cast
List<User> = (List<User>) userDao.searchGeneric(search);

User user = (User) userDao.searchUniqueGeneric(search);

However, there is a language feature that will determine the return type at 
compile time based on context. This may save some trouble...

public <Q> List<Q> searchGeneric(Search search);
public <Q> Q searchUniqueGeneric(Search search);

This could simply be used as follows...

List<User> = userDao.searchGeneric(search);

User user = userDao.searchUniqueGeneric(search);

Original issue reported on code.google.com by dwolvert on 3 Aug 2009 at 12:02

Allow extensibility of HibernateSearchProcessor

Last week, I encountered a problem (I'll submit an issue later), and wanted
to override the HibernateSearchProcessor as a quick fix.

But since HibernateSearchProcessor's constructor is private, it may not be
overriden.


It would be great if the constructor could be made protected for extensibility.


Workaround:
Copy/paste the whole HibernateSearchProcessor class, and then modify the
method you need to override.

Original issue reported on code.google.com by [email protected] on 19 Oct 2009 at 8:30

How about a uniqueResult method and adding some column operators to Search?

Provide a method on the daos for passing in a search and returning a single
result. It would throw an error if the query returns more than one result.
Perhaps it should return null if 0 results are returned.

Then add options to the Search object for column operators. Maybe call it
"summary" and specify a column and an operator. maybe COUNT, SUM, AVG, MAX,
MIN column operators.

The unique result could also be used for searches that have no column
operator but the user expects to return a single result.

Original issue reported on code.google.com by dwolvert on 21 Aug 2008 at 4:21

Improve efficency of deletes

It is probably not necessary to fetch the entity from the DB before 
deleting it.

Session.delete() will work fine with a transient instance.

Session.delete() may throw an unrecoverable error if no matching id is 
found in DB. Not sure.

EntityManager.remove() cannot take transient instance, but it may be able 
to recover if no matching id is found.


Original issue reported on code.google.com by dwolvert on 9 Apr 2009 at 6:35

Replace Criteria with Search (a.k.a. implement search using HQL instead of Criteria)

I originally used Criteria because they are easier to manipulate after we
have used the search to create them initially. But we're getting to the
point where our search covers almost every aspect that Criteria can cover.
Additionally, the Criteria we create end up with so many esoteric aliases
in them anyway, they are not of much use to the user.

In the generic-dao Google Code project implementation, they have their own
criteria object and use it to generate eql/hql. I think hql might be the
more native choice than Criteria. I think it would be simpler to translate
directly from our search object to hql anyway because there are a lot of
difficulties converting to Criteria.

Original issue reported on code.google.com by dwolvert on 26 Aug 2008 at 3:55

Add ILIKE filter operator

This will function the same as LIKE except that it will ignore case.


Original issue reported on code.google.com by dwolvert on 22 Dec 2008 at 2:59

Add fetch mode FETCH_SINGLE

Add a new fetch mode, perhaps called "FETCH_SINGLE", that returns just one
fetch property and does not wrap it in an array, list or map.

For example,
{{{
Search s = new Search(Person.class);
s.setFetchMode(Search.FETCH_SINGLE);
s.addFetch("name"); //exactly one fetch should be added

List<String> results = generalDAO.search(s);
assertEquals("Mike Wilson", results.get(0));
}}}

Other fetch modes all would return each result as a collection of some
sort. For example:
{{{
s.setFetchMode(Search.FETCH_ARRAY);
List<Object[]> results = generalDAO.search(s);
assertEquals("Mike Wilson", results.get(0)[0]); //note the [0] at the end
of the line.
}}}

Original issue reported on code.google.com by dwolvert on 6 Aug 2008 at 2:23

How about a uniqueResult method and adding some column operators to Search?

Provide a method on the daos for passing in a search and returning a single
result. It would throw an error if the query returns more than one result.
Perhaps it should return null if 0 results are returned.

Then add options to the Search object for column operators. Maybe call it
"summary" and specify a column and an operator. maybe COUNT, SUM, AVG, MAX,
MIN column operators.

The unique result could also be used for searches that have no column
operator but the user expects to return a single result.

Original issue reported on code.google.com by dwolvert on 21 Aug 2008 at 4:14

Add "enabled" property to filters.

This would be useful when using the search object to back user interfaces.
Particularly in one Adobe Flex usage, we have a single DataTable that can
take a number of different filters. It would be convenient to to turn some
of those filters on and off.

An alternative approach on the UI end is to switch sets of filters in and
out of the search. Then we wouldn't have to bring this feature all the way
through to the core code. This is more of a UI feature than something that
should be in the embedded in the core here.


Original issue reported on code.google.com by dwolvert on 11 Aug 2008 at 7:13

option to ignore filters with null values

** Use case:

I want to make a simple DAO method:
public List<Person> findByName(String first, String last);

I could implement it simply like this:
public List<Person> findByName(String first, String last) {
    return search(new Search()
                    .addFilterEqual("firstName", first)
                    .addFilterEqual("lastName", last));
}

But what if I want this method to ignore one of the names if it is null? 
Then I would have to write it:
public List<Person> findByName(String first, String last) {
    Search s = new Search();
    if (first != null)
        s.addFilterEqual("firstName", first);
    if (last != null)
        s.addFilterEqual("lastName", last);

    return search(s);
}


** Proposal:

Add an optional "ignoreIfNull" parameter on each addFilter... method, and 
add a default value for the whole Search. If the property is unspecified 
for a given filter it uses the property from the search. The property 
defaults to false for a new search. It can be specified for the search in a 
setter or an optional constructor parameter.

Then the method could be something like this:
public List<Person> findByName(String first, String last) {
    return search(new Search(true) //<-- ignoreIfNull specified for search
                    .addFilterEqual("firstName", first)
                    .addFilterEqual("lastName", last));
}

or this:
public List<Person> findByName(String first, String last) {
    return search(new Search()
                             //ignoreIfNull specified  for filter 
                    .addFilterEqual("firstName", first, true)
                    .addFilterEqual("lastName", last, true));
}

Original issue reported on code.google.com by dwolvert on 23 Dec 2008 at 10:04

cleanup the maven pom.xml

the pom file in /trunk includes a bunch of stuff it does not need to and
could add a few things (like mysql) to scope=provided.

Here is a .pom that seems to work ok

Original issue reported on code.google.com by [email protected] on 18 Nov 2008 at 7:15

Attachments:

Filter toString missing operator

Into the Filter class the method toString is missing operators:

OP_NULL = 10
OP_NOT_NULL = 11,
OP_EMPTY = 12
OP_NOT_EMPTY = 13;


Original issue reported on code.google.com by [email protected] on 17 Jun 2009 at 9:51

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.