Reputation: 6678
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">
<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">
<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">
<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 ;)
Upvotes: 0
Views: 8787
Reputation: 11
Firstly, you need to create setter of sessionFactory in both DAOs because you have to inject sessionfactory in both beans (UserDAO and ContectDAO) of contactmanagement.xml.
And Another alternate way is that, you can use HibernateTemplete in your DAOs.
For Example:
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate.Hibernate Template">
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>
then create setter of hibernateTemplate in both (DAOs).
afterthen you can use
hibernateTemplate.save();
hibernateTemplate.saveOrUpdate();
hibernateTemplate.delete();
hibernateTemplate.find();
etc.....
Upvotes: 1
Reputation: 6678
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
Upvotes: 0
Reputation: 49639
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.
Upvotes: 0
Reputation: 20732
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:
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">
<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.
Upvotes: 2
Reputation: 44063
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.
Upvotes: 0
Reputation: 68268
Try using
context.getBeansOfType(UserDaoImpl.class);
or
context.getBeansOfType(UserDao.class);
to make sure there are no typos.
Upvotes: 0
Reputation: 57294
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?
Upvotes: 0
Reputation: 22477
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>
Upvotes: 0