views:

2255

answers:

7

hi guys this is my first application in with spring and hibernate.So please bear with me with stupid questions :). i created a simple java application in netbeans 6.7. here are my daos interfaces UsersDAO

package Dao;

import Entities.Users;

public interface UsersDAO {
    public Long GetIdByUsernameAndPasswor(String username, String password);
    public Users GetAllByID(Long id);
    public boolean Create(Users user);
    public boolean Delete(Users user);
    public boolean Edit(Users user);
}

and the ContactDAO

package Dao;

import Entities.Contacts;
import java.util.List;

public interface ContactsDAO {
    public List GetAll();
    public Contacts GetAllById(Long Id);
    public boolean Create(Contacts contact);
    public boolean Delete(Contacts contact);
    public boolean Edit(Contacts contact);
}

and their implementations

package Dao.DaoImpl;

import Dao.UsersDAO;
import Entities.Users;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class UserDAOImpl  extends HibernateDaoSupport implements UsersDAO {
    //    private SessionFactory sessionFactory;
    public UserDAOImpl(){}

    public Long GetIdByUsernameAndPasswor(String username, String password)
    {
        try
        {
             return DataAccessUtils.longResult(getHibernateTemplate().find("select u.user_id from Users u where u.username=? and u.password", new Object[] {username, password}) );
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return Long.parseLong("0");
        }
    }

    public Users GetAllByID(Long id) {
       try
       {
           return (Users) getHibernateTemplate().get(Users.class, id);
       }
       catch(Exception ex)
       {
            ex.printStackTrace();
            return new Users();
       }
    }

    public boolean Create(Users user) {
       try
       {
            getHibernateTemplate().save(user);
            return true;
       }
       catch(Exception ex)
       {
           ex.printStackTrace();
           return false;
       }
    }

    public boolean Delete(Users user) {
       try
       {
           getHibernateTemplate().delete(user);
           return true;
       }
       catch(Exception ex)
       {
           ex.printStackTrace();
           return false;
       }
    }

    public boolean Edit(Users user) {
       try
       {
           getHibernateTemplate().saveOrUpdate(user);
           return true;
       }
       catch(Exception ex)
       {
           ex.printStackTrace();
           return false;
       }
      }
    }


package Dao.DaoImpl;

import Dao.ContactsDAO;
import Entities.Contacts;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ContactsDAOImpl extends HibernateDaoSupport implements ContactsDAO{
    public ContactsDAOImpl(){}

    public List GetAll() {
        try
        {
            return getHibernateTemplate().find("from Contacts");
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    public Contacts GetAllById(Long Id) {
      return (Contacts) getHibernateTemplate().get(Contacts.class, Id);
    }

    public boolean Create(Contacts contact) {
        try
        {
            getHibernateTemplate().save(contact);
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean Delete(Contacts contact) {

        try
        {
            getHibernateTemplate().delete(contact);
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
    }

    public boolean Edit(Contacts contact) {

        try
        {
            getHibernateTemplate().saveOrUpdate(contact);
            return true;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return false;
         }
        }
    }

my spring configuration file is under the folder Resources.so normally the path is Resouces/contactmanagement.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"&gt;

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />

    <property name="url" value="jdbc:mysql://localhost:3306/ContactsMan" />
    <property name="username" value="root" />
    <property name="password" value="letmein" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.SessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResouces">
        <list>
            <value>Resources/users.hbm.xml</value>
            <value>Resources/contacts.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
        </props>
    </property>
</bean>
<bean id="usersdao" class="Dao.DaoImpl.UserDAOImpl">
    <property name="sessionFactory" ref="sessionFactory">
</bean>
<bean id="contactsdao" class="Dao.DaoImpl.ContactDAOImpl">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

mapping files are under the same Resources folder users.hbm.xml contacts.hbm.xml

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;
    <hibernate-mapping>
        <class name="Entities.Contacts" table="contacts">
            <id name="contact_id">
                    <generator class="increment"/>
            </id>
            <many-to-one cascade="" class="Users" name="user"/>
            <property name="firstname" />
            <property name="lasstname" />
            <property name="cellphone1" />
            <property name="cellphone2" />
            <property name="telephone" />
            <property name="email" />
        </class>
    </hibernate-mapping>


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;
    <hibernate-mapping>
        <class name="Entities.Users" table="users">
            <id name="users_id">
                <generator class="increment"/>
            </id>
            <bag name="contacts" inverse="true" lazy="true">
                <key column="user_id"/>
                <one-to-many class="Contacts"/>
            </bag>

            <property name="username"/>
            <property name="passsword"/>
            <property name="city"/>
            <property name="country"/>

        </class>
    </hibernate-mapping>

this is finally my main class

package main;
import Dao.UsersDAO;
import Entities.Users;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext
public class contactmanagement {

public static void main(String[] args)
{
    ApplicationContext ctx = new ClassPathXmlApplicationContext("Resources/contactmanagement.xml");
    UsersDAO usersdao = (UsersDAO) ctx.getBean("usersdao");
    Users user = new Users();
    user.setUsername("me");
    user.setPassword("mypass");
    user.setCity("somecity");
    user.setCountry("somecountry");

    usersdao.Create(user);
    System.out.println("created");
 }

when i run this it said to give a summary "No bean named 'usersdao' is defined" Please what did i do wrong? here is another question about the DAOs implementation class. should i set the Property setSessionFactory? or spring handle every thing through the getHibernateTemplate() ? Please let me get Through this.Thanks for reading.I know it's long ;)

A: 

Your formatting is pretty bad, so I haven't really gone through your entire question, but I did notice that you aren't closing your property tag here:

<bean id="usersdao" class="Dao.DaoImpl.UserDAOImpl">
    <property name="sessionFactory" ref="sessionFactory">
</bean>

It should be:

<bean id="usersdao" class="Dao.DaoImpl.UserDAOImpl">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
Jack Leow
sorry for the formating.I've corrected.thanks for the reply
black sensei
Have you tried fixing your Spring configuration file? Is the problem still there?
Jack Leow
A: 

A few notes, although I don't have an answer to your question -

You're not using your interfaces. You have UsersDAO and a UsersDAOImpl, but the Impl doesn't have any relationship to the interface because you've omitted "implements UsersDAO". This shouldn't affect the spring initialization, though. (edit - never mind this, it's above the class, didn't see it - however, you're just creating a bean and using it in spring - you don't really need the interface here).

Usually when I've seen this error it's because either I've a) misspelled the bean name, so there's no such bean (which you have not done) or b) because the bean can't be instantiated for some reason. Can you post a complete stack trace?

Steve B.
Jul 10, 2009 3:39:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefreshINFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7: display name [org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7]; startup date [Fri Jul 10 15:39:53 GMT 2009]; root of context hierarchyJul 10, 2009 3:39:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource [Resources/contactmanagement.xml]
black sensei
Jul 10, 2009 3:39:54 PM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactoryINFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@133f1d7]: org.springframework.beans.factory.support.DefaultListableBeanFactory@11ddcdeJul 10, 2009 3:39:55 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletonsINFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@11ddcde: defining beans []; root of factory hierarchy
black sensei
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'usersdao' is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:391) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:999) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:233)
black sensei
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:883) at main.contactmanagement.main(contactmanagement.java:20)Java Result: 1
black sensei
You're mentioning the session factory exception below, and the "class not found" , which would indicate that you're missing a jar in the run environment. To simplify your life I'd suggest first running this without hibernate, just get spring to load the classes. Then at least you'll verify that you have that piece properly wired.
Steve B.
A: 

Try using

context.getBeansOfType(UserDaoImpl.class);

or

context.getBeansOfType(UserDao.class);

to make sure there are no typos.

Robert Munteanu
thanks for the reply. i did this UsersDAO usersdao = (UsersDAO) ctx.getBeansOfType(UsersDAO.class); and i got this error Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Dao.UsersDAO
black sensei
That method returns a Map, not the bean itself. Just do something like System.out.println(ctx.getBeansOfType(UserDao.class));
Robert Munteanu
A: 

It is also worth cleaning and rebuilding the project after every change to the configuration files to ensure that they are actually moved to the compiled classes and used when you are running the application.

willcodejavaforfood
thanks.the error message has changed. i'm now having this :Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.SessionFactoryBean and i think it has to do with my question about sessionFactory and the property setSessionFactory
black sensei
A: 

Hi there! Might I suggest having a look at using the Spring Annotations instead? I don't mean to throw you head first into yet another thing to figure out, but once you get the hang of it its much easier to get working than making all the configuration and mapping files work together.

There's some highly detailed information regarding this in chapters 3.11 and 3.12 here: Spring Documentation Chapter 3. The IoC container But what it basicly comes down to is this:

  • You annotate the DAO classes you want to define as beans using @Repository (or @Service).
  • Whereever you need to use such a DAO you declare a field in your class using: @Autowired MyExampleDAO myDao; (these classes should themselves also be annotated with @Service for this to work (or is there another way, anyone?))
  • Configure Spring to look for these annotations and it will make it so there is always an implementation for your beans whenever you need it.

As an example, my entire spring configuration looks like this:

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"&gt;

    <context:component-scan base-package="org.path.to.your.base.package" />

    <!-- Transaction Manager -->
    <bean id="transactionManager"
     class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven />

    <!-- Session Factory -->
    <bean id="sessionFactory"
     class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
     <property name="configLocation" value="hibernate.cfg.xml" />
    </bean>
</beans>

And a sample DAO looks like this:

@Repository
public class UserHibDAO extends GenericHibernateDAO<HopeUser> implements UserDAO {
    public IUser findByName(String name) {
     return (User) createCriteria(Restrictions.naturalId().set("name", name)).uniqueResult();
    }
}

And using this DAO looks like this:

@Service
public class Installer {
    private static final Logger log = Logger.getLogger(Installer.class);

    public static void main(String[] args) throws Exception {
     Installer inst = (Installer) SpringUtil.getContext().getBean("installer");
     inst. storeUsers();
     log.info("Done");
    }

@Autowired
private UserDAO userdao;

@Transactional
public void storeUsers() {
 userdao.makePersistent(new User("Tim"));

 log.info("Users stored");
}
}

Take special care looking at the main method in the last code sample: This is what you have to use instead of new Installer() to make the autowiring work.

Hope this example helps you in anyway, I realize its not a direct answer to your question, but an alternative solution to the problem at hand.

Tim
thanks for your effort to help me.i think with little reading i got to some point.there is another thing that boders me.should i create the sessionFactory Property or not.the book i'm using doesn't use it but online i can see it.Beside in my try to create one i only have access to org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean but in the book it's uses org.springframework.orm.hibernate3.annotation.SessionFactoryBean.So i' a bit confused.thanks
black sensei
The difference between ASFB and SFB is that the first is for use with Hibernate Annotations and the second is for use with Hibernate Mapping files. I see you're still using mapping files, so you could go with the SessionFactoryBean, but I believe AnnotationSessionFactoryBean should also be able to handle mapping files.. In that case using ASFB should also be fine.
Tim
As for your second question: If you include the line <context:component-scan base-package="org.path.to.your.base.package" /> in your spring configuration file, then you can declare a field "@Autowired private SessionFactory sessionFactory;" in your UserDAOImpl. If you then add the annotation "@Repository" on the line above "public class UserDAOImpl" Spring should magically make the SessionFactory available to you..
Tim
A: 

This is a shot in the dark, but try doing a clean and build on Netbeans. The automatic behind the scenes compilation doesn't update XML in the .War file.

James McMahon
A: 

hello everybody and thanks for all your time helping me solving the problem.I've actually solved the problem by looking at the stack message and correct most of the time typos error and bad reference in the hbm files and corrected case sensitivity in the pojo for the properties.And also i didn't have to create a sessionFactory property in any of the daos. it's fine now what i stated in my first question.While most of crud functions are working i'm still having problem in returning Users object instead of list.of course based on id i used thgetHibernateTemplate.get(Users.class, id)

but i wanted to return Users object by Username after realizing a simple cast from arraylist to Users class is not possible here is what i did

public Users GetUserByUsername(String username) {
  try
  {
      List userdetails = getHibernateTemplate().find("select u.user_id, u.username, u.password, u.city, u.country from Users u where u.username=?",username);
      Users u = new Users();
      u.setUser_id(Integer.parseInt(userdetails.get(0).toString()));
      u.setUsername(userdetails.get(1).toString());
      u.setPassword(userdetails.get(2).toString());
      u.setCity(userdetails.get(3).toString());
      u.setCountry(userdetails.get(4).toString());
     return u;
  }
  catch(Exception ex)
  {
      ex.printStackTrace();
      return new Users();
  }

it's not working.i guessed that maybe it's not returning columns in order that's why i i changed the query from "from Users u where u.username=?" to the one above.

1 how do i return an Users object from that query? 2 what about returning List of Users objects ?

Another thing that worries me is how to save contacts for a particular user.You can notice from my mapping files that i the table contacts is holding the relationship by having a reference to user_id which is a primary key in Users table. i faced a couple a problem when writing the unit testing for contactdaoimpl. as you all know there is a property of the class Users in the contact pojo. then to save a contact of the id 2 for example should i do this ?

Users u = new Users();
u.setUser_id(2); //supposing i have a way to get the id of the user
Contacts c = new Contacts();
c.setUser(u);
c.setFirtname("young");// an so on for the rest of the properties
contactdao.save(c);

if that is correct so in the test class i will have to intanctiate both userdao and contactdao. 3 is that fine? i have the feeling that the test is not on contact only that it has a dependency with users but still i don't have any idea about decoupling them and i don't even know that i should. so that it.Once those three worries are cleared then i'll successfully completed a basic but functional app with spring hibernate.I think after that i'll use this to post a tutorial somewhere.thanks for reading and for helping

black sensei