Hibernate vs DAO's

Hi Guys,
I've been using hibernate as the persistence mechanism in an enterprise project for a while now. Originally the datamodel was architected to use a DAO to store (through hibernate) and the BusinessObjects (BO's) would use/update the DO's for persistence.
My question is, given that Hibernate is (almost) database independent, is there any actual need for a DAO layer? It's almost redundant, consistiong of member fields that are to be persisted and no actual persistence logic. AFAIK there will always be a database layer in our system, so needing to abstract the persistence to be anything other than a database is a bit of overkill (although a good Software Engineer always leaves things open for change).
Should the DAO layer exist at all? I can see an argument architectually that you wouldn't want to always rely on hibernate as the persistence mechanism (I don't like to rely exclusively on any 3rd party code, I'd prefer to depend on my own abstraction), and the DAO's provide a relatively easy abstraction for changing the persistence mechanism, but in a hibernate based architecture they really are just "dumb" objects.
Cheers,
Aidos

Hi Guys,
I've been using hibernate as the persistence
mechanism in an enterprise project for a while now.
Originally the datamodel was architected to use a DAO
to store (through hibernate) and the BusinessObjects
(BO's) would use/update the DO's for persistence.
My question is, given that Hibernate is (almost)
database independent, is there any actual need for a
DAO layer? Most emphatically - yes.
It's almost redundant, consistiong of
member fields that are to be persisted and no actual
persistence logic.
AFAIK there will always be a
database layer in our system, so needing to abstract
the persistence to be anything other than a database
is a bit of overkill (although a good Software
Engineer always leaves things open for change).
Should the DAO layer exist at all? I can see an
argument architectually that you wouldn't want to
always rely on hibernate as the persistence mechanism
(I don't like to rely exclusively on any 3rd party
code, I'd prefer to depend on my own abstraction),
and the DAO's provide a relatively easy abstraction
for changing the persistence mechanism, but in a
hibernate based architecture they really are just
"dumb" objects.
Cheers,
AidosHibernate is one way to implement the DAO, but it will remain if you ever switch from Hibernate.
%

Similar Messages

  • Hibernate Query vs PreparedStatement for SQL

    Hi,
    I am using Hibernate for DAO classes, which i am using for the basic CRUD operations. But for complex queries with complex joins i am writing the SQL.
    In such case whether it is better to use the Query.createSQLQuery(String sql) to invoke the SQL or better to use the PreparedStatement since i am invoking only the SQL as supposed to HQL by getting the connection from the Hibernate Session. Since the PreparedStatement is precompiled it may be faster than invoking the SQL through the Query.createSQLQuery(String sql)? or using the Session.getNamedQuery(QUERY_NAME)? Please let me know your opinion on this.
    Thanks

    Whether you use Hibernate, ODBC, BDE, or Funky Foo's SQL client library, Oracle does not give a damn.
    It receives a statement from the client. This can either be SQL or an anonymous PL/SQL block. It parses it as a cursor. It then provides the client with a cursor handle to reference the cursor.
    The cursor is essentially a program. If it has bind variables, it is a program that accepts parameter input. This allows the very same program to be executed multiple times with different input parameters. For example, executing the same INSERT SQL cursor for different values and inserting multiple rows using the very same cursor.
    A cursor can also (like a program), produce output. An example is a SELECT cursor - where the fetch interface of the cursor enables the caller to consume the output of the cursor.
    So what is optimal in this respect? First and foremost cursors that are created using and used with bind variables. Secondly, re-using the very same client cursor handle (and not just the same server side SQL cursor) where possible (e.g. like repeating the same SQL INSERT statement with different values).
    The question to asked is whether the method you select to use on the client side - be that Hibernate or Funky Foo SQL, support this?
    The consideration to make is the following. Why code SQL in the client side? SQL is executed on the server-side - refers to server side data structures and needs to be tuned on the server. Put that code in a client and it significantly increases the complexity and decrease the flexibility of SQL.
    The alternative (and recommended approach) is to use PL/SQL to encapsulate all SQL. Instead of the client (and client programmer) needing to know SQL, a PL/SQL call interface is provided with calls like GetInvoice() to return a single specific invoice, or GetInvoiceByDate() that returns selected invoices for a date range. The PL/SQL code creates the SQL cursor and returns the client cursor handle as a reference cursor to the caller.
    This also allows business and validation logic to be implemented in the PL/SQL call interface to protect data integrity and business transaction sanity. A database structure change requires the SQL inside a PL/SQL procedure to be changed - without having to touch the client code. Likewise, SQL can be tuned and improved without having recompile a single byte of client code. And the same PL/SQL call interface services all clients - unlike multiple Java clients duplicating the same SQL (and not always correctly) to do the same thing, or having to duplicate and repeat the same data validation and business rule logic.

  • Lazy loading differences Toplink vs. Hibernate - plz. explain

    I'm in the process of evaluating both Toplink and hibernate as potential ORM framework to use for a project I'm currently involved in.
    My question is about how Toplink resolves lazily loaded associations. In hibernate I have to perform a query inside a transactional context boundary, like:
    Session s = SessionFactory.getSession();
    s.beginTransaction();
    ... your query logic here
    s.getTransaction().commit();When the query involves associations which are declared as lazily loadable, trying to invoke these associations after the transaction boundary has been closed, results in an exception. This differs from Toplink (my JUnit testcase breaks for Hibernate if I set the DAOFactory to return hibernate enabled DAO's) and I'm wondering why?
    I'm guessing this has something to do with how Toplink manages its clientsession, but would like to get some confirmation about this. It looks like as-long as the thread of execution is running I can resolve associations using Toplink, but not when I use Hibernate.
    This brings me to yet another question - what's considered best practices in Toplink regarding session disposal. Should I do something myself, or let the garbage collector take care of it?

    I'm not too sure here, but I think it's because TopLink has a "long running" ServerSession. When you do lazy initialization outside a clientsession it is for read only purposes and it will use the centrally managed ServerSession (and cache). I'm still trying to figure out the exact relationships here, som I'm not too sure. :) Hibernate does not have a centrally shared cache, and will not be able to instantiate objects if the session is closed (for each session, objects are instantiated from it's data cache).
    As for handling resources and closing/opening, use the Spring/TopLink integration. It will handle it for you and give you heaps of convenience methods that uses some clever tricks to decide if it should fetch objects with Session or UnitOfWork. It will also do some good Exception handling built into Spring.

  • DAO design decission

    Hi All,
    Currently in my j2ee project, we are using hibernate for database access. for this iam using DAO pattern, as follows .
    1) will be calling DAO abstract factory pattern from business service, to give DAO factory object.
    2) with this object, i will try to create a dao factory object(specific for hibernate or jdbc as necessary).
    3) on getting corresponding hibernate/jdbc dao factory object, i will create application specific dao object to interact , ie emplyoeeDAO etc.
    I just want to know whether this is a correct approach to handle jdbc also, if in future if we use.
    Thanks,
    kk
    Edited by: krishna_keriti123 on Dec 17, 2008 7:41 PM

    Why not invert control? Do you use Spring? That provides a neat way of abstracting your DAO strategy and wiring the dependencies up. The problem I see with using the abstract factory pattern for DAOs as you've described, is the sheer number of lookups business services will have to do. They have to get hold of the factory, and then look up the DAO as well. With dependency injection, they just get built with what they need up-front. You needn't actually use Spring for DI, you could roll it yourself. But coupled with the DAO support, and other supporting services, I think you've got a good case for using Spring here

  • Hibernate question.

    Does hibernate eliminate the DAO design pattern? If yes what are the advantages and disadvantages of hibernate over DAO design pattern.
    Thanks in advance.

    Thanks for your responses. Is it possible to create
    custom methods rather than the standard get methods
    in hibernate? For example sometimes i might require
    data from which satisfies criteria from 2 different
    columns or sometimes i might require data wihch is
    greater than a specific value.I'm not sure exactly what you're asking, but if it's something you might do with halfway reasonable code and data model (or even for many things that that only very stupid code and data model would do), the answer to "can you do it with Hibernate" is almost certainly "YES."
    Hibernate is very flexible. It will do most things in a very reasonable default way without you even having to tell it much. You can make custom queries with HQL--a SQL-like query language that Hibernate uses, or even directly in SQL. There are many ways to customize its behavior.

  • Single transaction through multiple service objects [Spring]

    Hello.
    I have multiple service objects, while methods in service objects represent use cases.
    If I call the method from the other method in the same service object, then the second (called) method uses the same transaction as the first (caller), because of default propagation REQUIRED is applied.
    .. as is shown in the following pseudo code:
    @Transactional
    public class PersonService {
         private PersonDAO personDAO;
         public void otherMethod() {
         public void savePerson(Person person) {
              otherMethod();
              personDAO.save(person);
    }But I need to call service methods of different service objects, because some use cases use other use cases. I also need all those called methods to be done as a single transaction.
    @Transactional
    public class OrderService {
         private OrderDAO orderDAO;
         public void saveOrder(Person person, Order order) {
              PersonService personService = CONTEXT.getBean("personService");
              personService.savePerson(person);
              orderDAO.save(order);
    }If I do it like that, the new transaction proxy is created and all personService stuff is executed in the new transaction. How to configure @Transactional annotated objects or Spring beans to do all service stuff in single transaction?
    I have Hibernate sessionfactory, DAOs and services beans simply configured in Spring configuration XML, using autowiring and transaction annotation config. I prefer using @transactional annotated service classes, but if I had to use more complex Spring transaction configuration to achieve the goal I won't have any problem with it.
    Thank you in advance.

    I would like it to be done is single transaction but it isn't. As the bean is retrieved from the spring context in OrderService's method
    PersonService personService = CONTEXT.getBean("personService");a new transaction for PersonService is started. So then I have two transactions in progress - one for OrderService and second for PersonService. I need the PersonService (or any other service object) to detect already pending transaction and use that. Not create new (it's own). I use no arguments in @Transactional annotation so default propagation REQUIRED should be used, but it still creates a new transaction for PersonService stuff.
    I'm posting my applicationContext.xml (simplified slightly)
    <beans default-autowire="byType">
         <bean id="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         </bean>
         <!-- Hibernate SessionFactory -->
         <bean id="sessionFactory"
              class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
              <property name="dataSource">
                   <ref local="dataSource" />
              </property>
         </bean>
         <bean id="hibernateTxManager"
              class="org.springframework.orm.hibernate3.HibernateTransactionManager">
              <property name="sessionFactory">
                   <ref local="sessionFactory" />
              </property>
         </bean>
         <tx:annotation-driven transaction-manager="hibernateTxManager" />
         <!-- DAOs -->
         <bean id="personDAO" class="net.package.dao.PersonDAO" />
         <bean id="orderDAO" class="net.package.dao.OrderDAO" />
         <!-- Services -->
         <bean id="personService" class="net.package.service.PersonService" />
         <bean id="orderService" class="net.package.service.OrderService" />
    </beans>Thank you

  • Unable to view list in drop down menu - JSTL - urgent view requires Pls

    Hello,
    I have the following code in my controller: Spring Framework, Hibernate with DAO is used to persist objects to DB.
    view plaincopy to clipboardprint?
    if((usacs.getRole().equals("salesperson")) && (usacs.getUsername().equals("sp")) && (usacs.getPassword().equals("sp")))
    session.setAttribute("role", role);
    myModel.put("useraccount", usacs);
    session.setAttribute("useraccount", usacs);
    List<UserAccount> cust = uads.getPersonsByRole("customer");
    myModel.put("custList", cust);
    return new ModelAndView("sploginp1", "sploginp1", myModel);
    I am putting the user name and the list of person of role type customer into the model, myModel.
    When I debug, I am able to see the customer names in custList.
    But the names wont appear on screen in the drop down. Could someone please throw some light. I have been breaking my head for the last 16hrs on this.
    This is my JSP code:
    view plaincopy to clipboardprint?
    Choose Customer to serve:
    <select name="customer" >
    <c:forEach items="${splogin1.custList}" var="c">
    <option value="${c.userid}"><c:out value="${c.username}"/></option>
    </c:forEach>
    </select>
    It shows me a empty drop down with no values in it.
    This program, is able to fetch the data from database and populate the model with it. In debug mode , as mentioned earlier, I can see the customers names but i dont see them in my JSP page.
    Can someone please help.
    Thank You.

    Yes, meant to pop that in the original post, Had a look in the per-location element. Nothing there either! It's disappeared from the site, but as I say a legacy Hyperlink stored in favourites
    still brings it out - I can edit the page when I get there etc...
    Apreciate you assistance BTW :-)

  • Why we need XML?

    hi,
    Why we need XML.?(we have ascii file format is a gentral format, to access all plateform,why not we didn't follow.?)
    like XML:
    <contact>
    <name> java</name>
    <age>25</age>
    </contact>
    flat files:
    contact name:java age:25
    i feel flat file is small and easy .....why we didn't use it.........?

    PS - Jos, how's the weather in your garden today?
    (Rainy and cool here.) Well picture this: both of my parrots are trying to
    sleep in their own hollow
    coconut, slightly disturbed by some silly squeaky
    bird at the other side
    of the barn. The fish in the pond are sort of
    sunbathing between the
    floating leafs, my wife seems to be in a catatonic
    state sleeping all the
    time and then there's me in front of my little laptop
    (protected by a silly
    little green umbrella like thingy, the laptop that is
    ;-)A nice image indeed.
    It's been one wet spring here. It's very cool and overcast, threatening more rain. I'm sitting in my office working away on getting my head around Spring. I've been going through Rob Harrop's "Pro Spring" slowly and carefully, making all the code work and taking little side trips to set it into my head. Rod Johnson's team is doing a great job, in my opinion.
    I still feel that the Spring framework, the web part
    of it, is as some sort
    of a corset, a hindrance. I feel like I'm all
    dressed up but nowere to go
    because Spring or something else I don't know about
    forbids me ... I
    know that I have it wrong alltogether but I can't get
    a grip on it. Not sure what the impediment is, but then I don't understand all the nuances of Spring yet. Maybe their newer web flow stuff might help. It models a UI as a state machine, so you can do more complex flows from page to page. The finite automata underneath will appeal to your inner mathematician. 8)
    btw. it's in
    the lower thirties here (celcius); that makes it in
    the lower nineties (fahrenheit).
    btw, YoGee helped me a lot yesterday.No surprise there. YoGee sure is smart. While I was reading the thread I wished that I had seen it first. You've been so helpful to me so often that I would have enjoyed reducing the trade deficit I have with you. I know that particular problem with Tomcat and JSTL well.
    Yep, I'm working on a large ('Dutch-wise' speaking
    that is) optic fibre
    network. Technically this network works great.
    Managerially speaking
    ahem there's nothing yet: no services, no control
    of services, no
    network checking stuff, no customer (crm) stuff, no
    nothing. Those folks
    want me to do it all. Sounds like a great problem. Could be an engagement to carry you through the summer.
    Yes, that particular part gave me blood behind my
    eyes: I did everyhing
    according to the book and that crap simply refused to
    work. It turned out
    that I was trying to develop something against wrong
    versions of several
    components. In a certain way I'm a believer, i.e.
    when I finally do understand
    what it's all about I "walk this way" when the
    documentation tells me to
    "walk this way". When that turns out not to work at
    all I want my pink
    inflatable axe again (or worse ;-)I like Tomcat, but I think the docs are sketchy. This seems to be a common problem.
    No, I feel reluctant to introduce yet another
    technology while I'm still
    struggling with the ones I found necessary to use.Me, too. I'm overwhelmed by all that I don't know. That's why I'm taking the time to get all the way through Spring once. I've been reading and dabbling, but I haven't given it enough concentrated attention to have it under my fingers. I've got three personal projects lined up once I get through "Pro Spring" that should set it into my head nicely.
    <advertisement>
    By the way, I decided to buy a copy of IntelliJ. I've never paid for an IDE, but since I've gotten used to it at work I don't want to be without it. I've never championed an environment as much as I do this one. I used Eclipse for several years and was glad to have it, but I'd still find myself slipping out and using a text editor to do quick things. IntelliJ doesn't get in my way. It's completely eliminated any temptation to use a text editor. A terrific product that's only getting better with time.
    </advertisement>
    <disclaimer>I'm not related to anyone who works for or affiliated with JetBrains in any way. Just a happy customer.
    </disclaimer>
    I'm not a GUI guy myself, far from that and I'd like
    to stay away from it as
    far as possible. As I wrote above I feel "all dressed
    up but nowhere to go".
    I've got my beans all ready, my DataSources are all
    solid and sound; I
    can see that everything works (from the logs), but
    that darn web stuff
    keeps on pestering me ...I think the UI is always the hardest part. Everything from the service layer back can almost be generated from the beans and tables: Hibernate mappings, DAOs, service layer, JUnit tests for the whole thing. A few nice annotations and you've got the whole thing. Just the UI beast left to tame...
    >
    I think I'll take another Grolsch and chase that
    silly squeaky bird away.
    Enjoy your weekend!
    kind regards,
    JosYou too! Go enjoy some World Cup football!
    %

  • JSF calls DAO layer based on  JPA/Hibernate throws NPE

    I'm new in JSF and Hibernate;
    I'm using Hibernate as JPA provider, the dataaccess is tied to DAO layer; when my JSF controller(UserController) calls the getUsers() of my DAO layer
    (Glassfish is the app Server I use)
    NullpointerException is thrown, I assume it's because instance of BasicDAO is initialized, where do I have to instantiate BasicDAO
    here is my code :
    public class BasicDAO {      
    @PersistenceUnit(unitName = "test5PU")
    private EntityManager entityManager;
    public void setEntityManager(EntityManager entityManager)
    {        this.entityManager = entityManager;    }
    public List getUsers() {       
    Query query = entityManager.createNamedQuery("User.findAllUsers");
    return query.getResultList();
    public User findUser(String id) {       
    try{
    Query q = entityManager.createNamedQuery("User.findByIdUser");
    User o = (User)q.getSingleResult();
    return o;
    } finally {
    entityManager.close();
    public class UserController {
    /** Creates a new instance of UserController */
    public UserController() {      
    private DataModel model;
    private BasicDAO basicDAO;
    public DataModel getUsers() {            
    return new ListDataModel(basicDAO.getUsers());
    public void setBasicDAO(BasicDAO basicDAO) {     
    this.basicDAO = basicDAO;
    public BasicDAO getBasicDAO() {           
    return this.basicDAO;
    public User findUser(String id) {
    return basicDAO.findUser(id);
    List.jsp :
    <h:dataTable value='#{user.users}' var='item' border="1" cellpadding="2" cellspacing="0">
    <h:column>
    <f:facet name="header">
    <h:outputText value="IdUser"/>
    </f:facet>
    <h:outputText value="#{item.idUser}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="Password"/>
    </f:facet>
    <h:outputText value="#{item.password}"/>
    </h:column>
    </h:dataTable>

    in fact, i did some tests, and the reason why the NPE happens revealed to be caused by the call to
    this.emf = Persistence.createEntityManagerFactory(persistenceUnitName, emfProperties);
    which returns NULL value, and later when emf is accessed to create entitymanager NullPointerException is thrown.
    I think there is a configuration probem some where, except in persistence.xml file. my persistence.xml content is :
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="test9PU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>JeeCertDB</jta-data-source>
    <class>persistence.user.User</class>
    <properties>
    <property name="hibernate.jdbc.driver"
    value="com.mysql.jdbc.Driver" />
    <property name="hibernate.jdbc.url"
    value="jdbc:mysql://localhost:3306/JeeCertDB" />
    <property name="hibernate.jdbc.user" value="root" />
    <property name="hibernate.jdbc.password" value="belly" />
    <property name="hibernate.logging.level" value="INFO" />
    </properties>
    </persistence-unit>
    </persistence>
    Message was edited by:
    S_screen

  • Hibernate, DAO pattern and tree hierarchy

    Hi all,
    I use Hibernate for a short period of time and now I'm facing a complex problem . I try figure it out what is the best practice for the following scenario:
    I have the following classes: Department, Team, Position, all of them inherited from a Entity class even there is almost no difference between them. But I wanted different classes for different entities.
    I try to create a tree hierachy, each object is with all others in a bidirectional one-to-many relationship. For example a Department can have Teams and Positions as children and a Position can have Departments and Teams as children.
    I created the mapping files and I don't know how to create all necessary methods without duplicating the code.
    Questions:
    1. Do I need a DAO pattern implemented for this design?
    2. Can you recomend some documentation or ideas that will help me find out what is the best approach in this case?
    Thanks

    Write the DAO for the class that is the root of the tree. Sounds like it should be DepartmentDao.
    I don't know of much better documentation than the Hibernate docs. Check their forum, too.
    %

  • DAO classes and Hibernate

    hi all
    need help.
    i have one dought where is used DAO classes and where is
    used Hibernate.i think both r used for data base access ,but why we are
    used both.
    thanks in advence.

    i have one dought where is used DAO classes and where is
    used Hibernate.Awesome, we got doubt misused AND misspelled!
    i think both r used for data base accesscorrect!
    but why we are used both.DAO is a design pattern (concept) and Hibernate is a product (code implementation).
    Hibernate is a DAO implementation. That said, you don't need both, in fact you don't need either.

  • Generic Hibernate dao

    Hi, I have been working with a generic HibernateDao to which I pass the entity type through a constructor parameter, and it works perfectly. I ran into a [SpringSource team blog|http://blog.springsource.com/2006/09/29/exploiting-generics-metadata/] by Rob Harrop that explained how to determine the actual type of the parameter at runtime. I also found a [page on the Hibernate documentation|http://www.hibernate.org/328.html] that explained the same concept. I used Robs version for my own GenericDao:
    public class HibernateDao<E> implements GenericDao<E> {
        private SessionFactory sessionFactory;
        private Class<E> entityClass;
        public HibernateDao() {
            entityClass = extractTypeParameter(getClass());
       // All sorts of DAO  methods
       private Class extractTypeParameter(Class<? extends GenericDao> genericDaoType) {
            Type[] genericInterfaces = genericDaoType.getGenericInterfaces();
            // find the generic interface declaration for GenericDao<E>
            ParameterizedType genericInterface = null;
            for (Type t : genericInterfaces) {
                if (t instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType)t;
                    if (GenericDao.class.equals(pt.getRawType())) {
                        genericInterface = pt;
                        break;
            if(genericInterface == null) {
                throw new IllegalArgumentException("Type '" + genericDaoType
                   + "' does not implement GenericDao<E>.");
            return (Class)genericInterface.getActualTypeArguments()[0];
    }and ran into a ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class for the line with the return statement. It seems they both implement the Type interface, but they are no subclasses of each other. These articles must have been read and tried by numerous people and I found other sites that implement the same thing, what am I doing wrong to get this exception?
    Edited by: Peetzore on 9-feb-2009 14:45

    OK, I've also encountered the same problem, investigated it and finally got into solution.
    The trick with getActualTypeArguments() being of type Class and not TypeVariable works when you instantiate the type argument statically, not dynamically.
    Statically here means:
    class SomeEntityHibernateDAO extends HibernateDAO<SomeEntity> { ... }
    SomeEntityHibernateDAO dao = new SomeEntityHibernateDAO();and dynamically:
    HibernateDAO<SomeEntity> dao = new HibernateDAO<SomeEntity>();In the first case, the "actual type argument" (like in getActualTypeArgument) of E in your code gets bound to Class<SomeEntity>, in the second - to TypeVariable.
    It may be the case, that the desired Class object is further extractable from the TypeVariable (look at its methods), but simply what you may want is to define separate classes for all entities (statically binding the type parameter) and use these instead of generic declarations.
    Hope it helps.
    Cheers,
    Jarek

  • Hibernate - Spring - problem with mapping (many-to-many)

    Hello,
    I want to map the following situation. I have a table called EDUCATION and a table called SCHOOLS. Between those tables I have an associative table called EDUCATION_SCHOOLS. The (usefull) fields:
    EDUCATION:
    id (long) - PK
    name (varchar)
    versionNr (long)
    SCHOOLS:
    id (long) - PK
    name (varchar)
    versionNr (long)
    EDUCATION_SCHOOLS:
    id (long) - PK
    education_id (long) (FK to EDUCATION.id)
    school_id (long) (FK to SCHOOLS.id)
    name (varchar)
    versionNr (long)
    Their is a Unique Constraint between EDUCATION_SCHOOLS.education_id and EDUCATION_SCHOOLS.school_id.
    What I want to be able to do:
    EDUCATION: select, update, insert
    SCHOOLS: select, update, insert
    EDUCATION_SCHOOLS: select, update (only the non-FK fields), insert
    I never want to delete anything in those tables. (and it's never ever going to be an option either)
    Hibernate version:
    Hibernate-Version: 3.0.5
    Mapping documents:
    Education:
    <hibernate-mapping>
         <class name="##.Education" table="EDUCATION">
              <id name="id" column="ID" type="java.lang.Long">
                   <generator class="sequence">
                        <param name="sequence">EDUCATION_SEQ</param>
                   </generator>
              </id>
              <version name="versionNr" column="VERSIONNR" type="long"/>
              <property name="name" column="NAME" type="string" />
            <set name="SCHOOLS" table="EDUCATION_SCHOOLS">
                <key column="EDUCATION_ID" />
                <many-to-many class="##.Schools" column="SCHOOL_ID" lazy="false" />
            </set>
    </hibernate-mapping>
    Schools:
    <hibernate-mapping>
         <class name="##.Schools" table="SCHOOLS">
              <id name="id" column="ID" type="java.lang.Long">
                   <generator class="sequence">
                        <param name="sequence">SCHOOLS_SEQ</param>
                   </generator>
              </id>
              <version name="versionNr" column="VERSIONNR" type="long"/>
              <property name="name" column="NAAM_NAME" type="string" />
            <set name="educations" table="EDUCATION_SCHOOLS" inverse="true" cascade="none">
                <key column="SCHOOL_ID" />
                <many-to-many class="##.Schools" column="SCHOOL_ID" lazy="proxy"/>
            </set>
    </hibernate-mapping>
    Education_schools:
    <hibernate-mapping>
    <class name="##.EducationSchools" table="EDUCATION_SCHOOLS">
               <id name="id" column="ID" type="java.lang.Long" unsaved-value="0">
                   <generator class="sequence">
                        <param name="sequence">SEQ_EDUCATION_SCHOOLS</param>
                   </generator>
              </id>
              <version name="versionNr" column="VERSIONNR" type="long" />
              <many-to-one name="education" class="##.Education" cascade="none" lazy="proxy"
                           column="EDUCATION_ID" not-null="true"/>
            <many-to-one name="schools" class="##.Schools" cascade="none" lazy="proxy"
                        column="SCHOOL_ID" not-null="true"/>  
    </hibernate-mapping>   
    Name and version of the database you are using:
    Oracle XE 10g
    I am able to:
    EDUCATION: select, insert, update
    SCHOOLS: select, insert, update
    EDUCATION_SCHOOLS: select
    Problems:
    EDUCATION_SCHOOLS: when I try to insert, I sometimes get unique constraint violations. (when I should get them, thus I'm trying to insert something that already exists .. but how do I stop Hibernate from Inserting?)
    EDUCATION_SCHOOLS: when I try to update, sometimes it works, but often I get:
    23:03:55,484 [http-8081-1] ERROR be.vlaanderen.lne.vea.epb.ui.struts.EpbExceptionHandler - org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [##.EducationSchools] with identifier [null]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [##.EducationSchools#<null>]
    ex.getMessage() Object of class [##.EducationSchools] with identifier [null]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [##.EducationSchools#<null>]
    org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [##.EducationSchools] with identifier [null]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [##.EducationSchools#<null>]
    Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect):As you can see from the stacktrace I use Spring for the transactionManager: org.springframework.orm.hibernate3.HibernateTransactionManager in which I use e sessionFactory: org.springframework.orm.hibernate3.LocalSessionFactoryBean
    In my DAO, I try to save with the regular this.getHibernateTemplate().saveOrUpdate that has always worked for me.
    Another problem I have:
    when i update "name" in EDUCATION, the records with that ID are delete from EDUCATION_SCHOOLS ...
    As I am experiencing 3 different problems, I'm pretty sure something is wrong in the mapping files .. however I fail to find out what .. Any input would be greatly appreciated.
    (I translated some class/table-names, that's what the ## cause)
    Edited by: Bart_Blommaerts on Jul 29, 2008 11:53 PM

    Thank you for your input.
    When I try what you suggest, I still get the same error:
    16:39:30,406 [http-8081-1] ERROR ###.EpbExceptionHandler - org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [###.EducationSchools] with identifier [2]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [###.EducationSchools#2]
    ex.getMessage() Object of class [###.EducationSchools] with identifier [2]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [###.EducationSchools#2]
    org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [###.EducationSchools] with identifier [2]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [###.EducationSchools#2]
    Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [###.EducationSchools#2]If you had to map the database tables, I'm trying to map, how would you do it?

  • Deployement problem in Oracle App Serv with hibernate + JPA and Spring

    Dear All,
         I am facing a problem in deployment of a web application in oracle application server 10g. but the same is working fine with Tomcat. The following Exception. Is being thrown.
         Failed to deploy web application "OraTest". Failed to deploy web application OraTest". . Nested exception Resolution:
    Base Exception:
    java.rmi.RemoteException
    deploy failed!: ; nested exception is:
    oracle.oc4j.admin.internal.DeployerException: Unknown assembly root-tag attribute: version. deploy failed!: ; nested exception is:
    oracle.oc4j.admin.internal.DeployerException: Unknown assembly root-tag attribute: version     I am using the following technologies
    1.     Spring 2.0.7
    2.     Struts 2.0.9
    3.     Hibernate 3.3
    4.     JPA 1.0
    5.     Oracle App Server 10.1.2.0.2
    Web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
         <display-name>My Application</display-name>
         <filter>
              <filter-name>struts2</filter-name>
              <filter-class>
                   org.apache.struts2.dispatcher.FilterDispatcher
              </filter-class>
         </filter>
         <filter-mapping>
              <filter-name>struts2</filter-name>
              <url-pattern>/*</url-pattern>
         </filter-mapping>
         <welcome-file-list>
              <welcome-file>/index.jsp</welcome-file>
         </welcome-file-list>
         <servlet>
              <servlet-name>dwr-invoker</servlet-name>
              <servlet-class>
                   org.directwebremoting.servlet.DwrServlet
              </servlet-class>
              <init-param>
                   <param-name>debug</param-name>
                   <param-value>true</param-value>
              </init-param>
         </servlet>
         <servlet-mapping>
              <servlet-name>dwr-invoker</servlet-name>
              <url-pattern>/dwr/*</url-pattern>
         </servlet-mapping>
         <listener>
              <listener-class>
                   org.springframework.web.context.ContextLoaderListener
              </listener-class>
         </listener>
         <context-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>
                   /WEB-INF/conf/spring/datasource-context.xml,
                   /WEB-INF/conf/spring/aop-context.xml          
              </param-value>
         </context-param>
    </web-app>
    /Datasource-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
         <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" lazy-init="true"/>
         <!--  following code is for using oracle -->
            <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true">
              <property name="driverClassName">
                   <value>oracle.jdbc.driver.OracleDriver</value>
              </property>
              <property name="url">
                   <value>jdbc:oracle:thin:@//xxx.xxx.xxx.xxx/mydb</value>
              </property>
              <property name="username">
                   <value>admin</value>
              </property>
              <property name="password">
                   <value>admin</value>
              </property>
         </bean>
         <!--  following code is for using mysql -->
         <!--
         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true">
              <property name="driverClassName">
                   <value>org.gjt.mm.mysql.Driver</value>
              </property>
              <property name="url">
                   <value>jdbc:mysql://192.168.10.157:3306/tpsadmin</value>
              </property>
              <property name="username">
                   <value>tpsadmin</value>
              </property>
              <property name="password">
                   <value>tpsadmin</value>+
              </property>
         </bean>
         -->
         <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" lazy-init="true">
              <property name="persistenceUnitName" value="mkclsetsPersistenceUnit"/>
              <property name="dataSource" ref="dataSource"/>
              <property name="jpaVendorAdapter">
                   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" lazy-init="true">
                        <property name="database" value="ORACLE"/>               
                        <property name="showSql" value="true"/>
                   </bean>
              </property>
         </bean>
         <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" lazy-init="true">
              <property name="entityManagerFactory" ref="entityManagerFactory"></property>
         </bean>
         <tx:annotation-driven transaction-manager="transactionManager"/>     
    </beans>Aop-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <!--  Bean Definition of all the required Interceptors -->
         <bean id="methodLoggingAdvice" class="com.mkcl.sets.common.interceptor.MehodLogInterceptor"/>
         <!--
         <bean id="appCacheManager" class="net.sf.ehcache.CacheManager">
              <constructor-arg index="0" type="java.net.URL" value="classpath:country-ehcache.xml"/>
         </bean>     
         -->
          <!--bean id="methodCacheInterceptor" -->
         <bean id="methodCachingAdvice"
              class="com.mkcl.sets.common.interceptor.MethodCacheInterceptor">
              <property name="cache">
                   <ref local="methodCache" />
              </property>
         </bean>
         <bean id="cacheManager"
              class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
              <property name="configLocation">
                   <value>WEB-INF/conf/other/ehcache.xml</value>
              </property>
         </bean>     
         <bean id="methodCache"
              class="org.springframework.cache.ehcache.EhCacheFactoryBean">
              <property name="cacheManager">
                   <ref local="cacheManager" />
              </property>
              <property name="cacheName">
                   <value>mkclSetsCache</value>
              </property>
         </bean>      
         <!--
         <bean id="methodCachingAdvice" class="interceptor.MethodCachingInterceptor"/>
          -->
         <aop:config>
              <aop:pointcut id="getCountriesPointCut" expression="execution(* com.mkcl.sets.dao.master.impl.LocationDAOImpl.getCountries())"/>          
              <!-- <aop:pointcut id="methodLogPointCut" expression="execution(* com.mkcl.sets.service.master.impl.CategoryServiceImpl.getAllCategories(..))"/> -->
              <aop:pointcut id="methodLogPointCutDao" expression="execution(* com.mkcl.sets.dao..*.*(..))"/>
              <aop:pointcut id="methodLogPointCutService" expression="execution(* com.mkcl.sets.service..*.*(..))"/>
              <aop:advisor id="methodCachingAdvisor" advice-ref="methodCachingAdvice" pointcut-ref="getCountriesPointCut"/>          
              <aop:advisor id="methodLoggingAdvisorDao" advice-ref="methodLoggingAdvice" pointcut-ref="methodLogPointCutDao"/>
              <aop:advisor id="methodLoggingAdvisorService" advice-ref="methodLoggingAdvice" pointcut-ref="methodLogPointCutService"/>
         </aop:config>
    </beans>Persistence.xml
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
        version="1.0">
         <persistence-unit name="mkclsetsPersistenceUnit" transaction-type="RESOURCE_LOCAL">
              <!-- jta-data-source>mkclDS</jta-data-source-->
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <!-- properties>
                   <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
                   <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.OC4JTransactionManager"/>
              </properties-->
         </persistence-unit>
    </persistence>Do I need to add some other configuration in the existing files or do I need to add some other configuration files ? Please help to deploy my application.
    Thanks a lot in advance.
    With Best Regards,
    Ishaan
    null

    Did you ever find a solution to this Ishaan?
    I imagine you ended up having to upgrade 10gR2 to 10gR3 at least. Correct?

  • How to integrate hibernate with Stateless Session bean in weblogic10.0

    Hi,
    I need to invoke hibernate(3.x) DAO from EJB Stateless Session bean(EJB2.x). I am using mysql database. Can somebody please post the configuration.
    Thanks in advance,
    Rushi.

    Hi Deepak,
    Thanks for your reply.
    Actually, our stand alone java application already using spring-hibernate feature. Now we are planning divide our application into modules and deploy each module as ejb beans. As it is already integrated with spring-hibernate we are not using entity beans as of now. My understanding is container uses some default transcation management .so, my question is what are all the configurations needs to be done to let weblogic 10.0 server uses org.springframework.orm.hibernate3.HibernateTransactionManager. I mean, is there are any .xml file in weblogic to configure all these? please reply deepak I am struck here..
    Regards,
    Rushi.

Maybe you are looking for

  • IPhoto is a pain in my behind!

    why is ordering a calendar with my own pictures so HARD...I can get it from Walmart or Walgreens but not Apple???

  • White lines

    Product name: HP Photosmart M537 digital camera Pictures that I take outside are totally white obliterating any picture; inside (with or without flash) are white striped horizontally across the picture. The change was immediate. I went from taking a

  • Select query taking more time..

    Hi friends.. The below inner join statement is taking more time ,  can any  body sugget me to improve the performance . I tried FOR ALL ENTRIES also but that also taking more time than inner join statement . SELECT a~vbeln from vbap as a inner join v

  • Malformed HTTP request in access.log

    Hi, we're running a quite standard web application on a weblogic server 9.1, clients are using Internet Explorer 6, and lately, I checked the access.log, and sometimes, logged HTTP requests look malformed, for example: access.log00575:xxx.xxx.xxx.xxx

  • Information Broadcasting(Event data change in Process chains)

    Hi All, Does anyone have experince on the functionality Information Broadcasting ,Can you please help me where we use Trigger event when change in the info provider in the process chains.I want to know when we use the (Trigger event in the Broadcaste