I am trying to make a simple Spring MVC application using Spring Data, hibernate and H2 database. But spring cannot find the repository as a bean.
The error when application start:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskService': Unsatisfied dependency expressed through method 'setTaskRepository' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.intership.repositories.TaskRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.intership.repositories.TaskRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
TaskRepository.java
#Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}
TaskSerice.java
public interface TaskService {
public List<Task> getAll();
public void save(Task t);
}
TaskServiceImpl.java
public class TaskServiceImpl implements TaskService {
private TaskRepository taskRepository;
#Override
public void add(Task task) {
taskRepository.save(task);
}
#Override
public List<Task> getAll() {
LinkedList<Task> tasks = new LinkedList<>();
taskRepository.findAll().forEach(tasks::add);
return tasks;
}
#Autowired
public void setTaskRepository(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
}
BeanConfiguration.java
#Configuration
public class BeanConfiguration {
#Bean
MemoryService memoryService() {
return new MemoryServiceImpl();
}
#Bean
TimeService timeService() {
return new TimeServiceImpl();
}
#Bean
NameService nameService() {
return new NameServiceImpl();
}
#Bean
TaskService taskService() {return new TaskServiceImpl(); }
}
application-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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource" id="dataSource">
<property name="driverClass" value="${db.driverClass}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.spring.intership.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.driver_class">org.h2.Drive</prop>
</props>
</property>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer"
init-method="start" destroy-method="stop">
<constructor-arg value="-web,-webAllowOthers,-webDaemon,-webPort,8082" />
</bean>
<jpa:repositories base-package="com.spring.intership.repositories"/>
</beans>
And i have this in my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/config/application-context.xml
WEB-INF/config/application.properties
</param-value>
</context-param>
I have very little experience in MVC spring (a little more in boot) so please consider the most obvious mistakes too;
P.S. My Task.java
#Entity
#Transactional
public class Task {
private long number;
private String description;
private Date date;
#Id
#Column(name = "ID")
public long getNumber()
{
return number;
}
#Basic
#Column(name = "DESCRIPTION")
public String getDescription()
{
return description;
}
#Basic
#Column(name = "DATE")
public Date getDate()
{
return date;
}
public void setNumber(long number)
{
this.number = number;
}
public void setDate(Date date) {
this.date = date;
}
public void setDescription(String description) {
this.description = description;
}
}
try this tips:
Use "#ComponentScan" annotation in "BeanConfiguration" class. Note that you can use "#ComponentScan(basePackages = "com.example.package")" to force scan of the package when your repositories are.
You can use "#EnableJpaRepository(basePackages = "package.of.repositories")" to scan specific package to find ONLY repositories.
Let's check if "Task" class is annoted with "#Entity"
Consider to convert you context to class and try to use annotation instead of xml bean definition.
If you choose to use #ComponentScan annotation consider to scan all packages' tree. If your packages are "com.example.repository", "com.example.controller", "com.example.service" let's scan "com.example" in order to scan also future packages' you will add
I agree with #Luke.
Also you should autowire TaskRepository in TaskService.
public class TaskServiceImpl implements TaskService {
#Autowired
private TaskRepository taskRepository;
....
Related
I am using Spring-ORM to add a Employee* object in Table called emp using HibernateTemplate.
But when I'm trying to execute the program I'm getting this error:
Error creating bean with name 'testBean': Unsatisfied dependency expressed through field 'dao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:E rror creating bean with name 'empDaoImpl': Unsatisfied dependency expressed through field 'ht'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ht' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is
org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table emp add empno number(10,0) not null]
This is My java bean
#Service
public class TestBean
{
#Autowired
private EmpDao dao;
public void persistEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.save(e);
}
public void updateEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.update(e);
}
public void deleteEmp(int empid)
{
dao.deleteEmployee(empid);
}
public void selectEmps()
{
List lt=dao.selectEmployees();
Iterator it=lt.iterator();
while(it.hasNext())
{
Employee e1=(Employee)it.next();
System.out.println(e1);
}
}
}
*This is my Entity class
#Entity
#Table(name="emp")
public class Employee
{
#Id
#Column(name="empno")
private int empid;
#Column(name="ename")
private String empName;
#Column(name="sal")
private int empSalary;
#Column(name="deptno")
private int deptNum;
//Setters and Getters
public String toString()
{
return "Employee["+empid+" "+empName+" "+empSalary+" "+deptNum+"]";
}
}
This is my EmpDaoImpl class
#Repository
#Transactional
public class EmpDaoImpl implements EmpDao
{
#Autowired
private HibernateTemplate ht;
public void deleteEmployee(int empid)
{
Employee e=(Employee)ht.get(Employee.class, empid);
ht.delete(e);
System.out.println("one Employee object is deleted");
}
public List selectEmployees()
{
List empList=ht.find("from Employee e");
return empList;
}
public void save(Employee e)
{
ht.save(e);
System.out.println("Object is saved ");
}
public void update(Employee e)
{
ht.update(e);
System.out.println("Object is Updated");
}
}
This is my Main class
public class Main
{
public static void main(String[] args)
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
TestBean testB=(TestBean)ctx.getBean("testBean");
testB.persistEmp(7999, "naveen", 55555, 40);
System.out.println("===============================");
}
}
This is my applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.pack1"></context:component-scan>
<bean id="ht" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="ds"></property>
<property name="annotatedClasses">
<list>
<value>com.pack1.entity.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
<bean id="txm" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="tiger"/>
</bean>
<tx:annotation-driven transaction-manager="txm"/>
</beans>
When hibernate.hbm2ddl.auto is set to update Hibernate won't modify existing table column definitions. So, you can manually alter the column definition or drop the table/column and run your code. In the latter case, hibernate will create the column if it is not present.
Please refer here, here and here for more info on hibernate.hbm2ddl.auto options and how they work.
I am creating a ShoppingCart App using Spring-mvc.In dao layer I am using Spring-Hibernate ORM feature.
#Repository("baseDao")
public class BaseDaoImpl<T extends ShoppingCartEntity> implements BaseDao<T>
{
#Autowired
protected SessionFactory sessionFactory;
private Class<T> entityClass;
public BaseDaoImpl(Class<T> entityClass) {
super();
this.entityClass = entityClass;
}
public Serializable save(T entity) {
return sessionFactory.getCurrentSession().save(entity);
}
public void update(T entity) {
sessionFactory.getCurrentSession().update(entity);
}
public void saveOrUpdate(T entity) {
sessionFactory.getCurrentSession().saveOrUpdate(entity);
}
}
CartDaoImpl.java
#Repository("cartDao")
public class CartDaoImpl extends BaseDaoImpl<CartMaster> implements CartDao {
private Class<CartMaster> entityClass;
public CartDaoImpl(#Value("com.orgn.shc.entity.CartMaster")Class<CartMaster> entityClass) {
super(entityClass);
this.entityClass = entityClass;
}
//other getter & setter
}
I have a base entity class named ShoppingCartEntity.java.
#MappedSuperclass
public class ShoppingCartEntity implements Serializable {
private static final long serialVersionUID = 1L;
//other fields
}
CartMaster.java:
#Entity
#Table(name = "SHOP_CART_MASTER")
public class CartMaster extends ShoppingCartEntity {
//other fields
}
Now,during deployment of application in weblogic I am getting following exception:
<28 Dec, 2017, 11:48:08,916 PM IST> <Error>
<org.springframework.web.servlet.DispatcherServlet> <BEA-000000> <Context
initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'baseDao' defined in URL [zip:C:/Oracle
/Middleware/ORACLE_HOME/user_projects/domains/wl_server/servers
/AdminServer/tmp/_WL_user/shoppingcart/8i2b70/war/WEB-INF/lib
/wl_cls_gen.jar!/com/orgn/shc/dao/impl/BaseDaoImpl.class]: Unsatisfied
dependency expressed through constructor parameter 0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'java.lang.Class<?>' available: expected at least
1 bean which qualifies as autowire candidate. Dependency annotations: {}
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
Its spring-bean configuraation part as below
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/SHPDS"
expected-type="javax.sql.DataSource" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.orgn.shc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
</bean>
<mvc:annotation-driven />
<context:component-scan base-package="com.orgn.shc" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/assets/**" location="/assets/" />
My perception is that #Value annotation at constructor level is sufficient to inject the dependencies accordingly in sub classes.
Can anyone has any suitable solution to this?
Remove #Repository("baseDao") from your BaseDaoImpl as it should not be created as a separate bean; instead, it should be only used as a parent for other DAO classes. I would also make it abstract and its constructor protected to avoid accidental instantiation.
Also, it looks like you need to change the constructor of your CartDaoImpl to the following:
public CartDaoImpl() {
super(CartMaster.class);
}
And I don't believe you actually need entityClass field in CartDaoImpl as you know the class of your entity in this DAO: it's CartMaster.class. At the same time, in BaseDaoImpl that entityClass field may be useful to read entities from database (even though you don't have such methods).
[enter image description here][1]
Account.java
package com.hibernateWithSpring;
public class Account {
private int accountNumber;
private String owner;
private double balance;
public Account(){
}
public Account(int accountNumber, String owner, double balance) {
this.accountNumber=accountNumber;
this.owner= owner;
this.balance=balance;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
AccountClient.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountClient {
public static void main(String[] args){
ApplicationContext context=new FileSystemXmlApplicationContext("bin/beans.xml");
AccountDao accountdao = context.getBean("accountDaoBean",AccountDao.class);
accountdao.createAccount(110, "varun",1000);
accountdao.createAccount(111, "vicky",1200);
System.out.println("account created");
accountdao.updateBalance(111,2222);
System.out.println("account updated");
accountdao.deleteAccount(111);
System.out.println("account deleted");
List<Account> account= accountdao.getAllAccount();
for(int i=0;i<account.size();i++){
Account acc=account.get(i);
System.out.println(acc.getAccountNumber()+":"+acc.getOwner()+":"+acc.getBalance());
}
}
}
AccountDao.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class AccountDao extends HibernateDaoSupport
{
public void createAccount(int accountNumbeer, String owner, double balane){
Account account= new Account(accountNumbeer,owner,balane);
getHibernateTemplate().save(account);
}
public void updateBalance(int accountNumber, double newBalance){
Account account= getHibernateTemplate().get(Account.class, accountNumber);
if(account !=null){
account.setBalance(newBalance);
}
getHibernateTemplate().update(account);
}
public void deleteAccount(int accountNumber){
Account account=getHibernateTemplate().get(Account.class, accountNumber);
if(account!=null){
getHibernateTemplate().delete(account);
}
}
#SuppressWarnings("unchecked")
public List<Account> getAllAccount()
{
return getHibernateTemplate().find("from Account");
}
}
Account.hbm.xml
<?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="com.hibernateWithSpring.Account" table="account">
<id name="accountNumber" column="account_number" type="int"></id>
<property name="owner" column="owner" type="string"></property>
<property name="balance" column="balance" type="double"></property>
</class>
</hibernate-mapping>
beans.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-3.0.xsd">
<bean id="accountDaoBean" class="com.hibernateWithSpring.AccountDao">
<property name="hibernateTemplate" ref="hibernateTemplateBean"></property>
</bean>
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sfBean"></property>
</bean>
<bean id="sfBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="mappingResources">
<value>com/hibernateWithSpring/Account.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/accountdb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
My db Details are correct But I have no idea why i am getting this error:-
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDaoBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'hibernateTemplateBean' while setting bean property 'hibernateTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplateBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'sfBean' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sfBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Things you need to fix:
1 - put the JAR (javaee-api) in your LIB folder
http://mvnrepository.com/artifact/javax/javaee-api/7.0
2 - if you are using Maven, add the following dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
3 - Configure your artifact and include this jar, allowing to be deployed
4 - Put the javaee-api jar in your tomcat/jboss lib folder
I am trying to use annotated TX Spring support.
Application context XML:
<?xml ...>
<tx:annotation-driven/>
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource">
...
</bean>
<bean id="repository" class="Repository">
<constructor-arg ref="dataSource"/>
</bean>
</beans>
Actual code:
public class Repository {
#Transactional
public void save(Op op) {
System.out.println("Transaction active:::: " + TransactionSynchronizationManager.isActualTransactionActive());
...
}
}
Calling code:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"/integration-context.xml"})
public class RepositoryTest {
#Autowired
private Repository repository;
#Test
public void testRepositoryPersistence() {
Op op = mock(Op.class);
repository.save(op);
}
}
And it gives FALSE.
What am I doing wrong?
You should add this in your configuration
<context:annotation-config/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
add an interface on your RepositoryClass
public class Repository implements IRepository{
#Transactional
public void save(Op op) {
System.out.println("Transaction active:::: " + TransactionSynchronizationManager.isActualTransactionActive());
...
}
}
and this in your test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:/integration-context.xml"})
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class RepositoryTest extends AbstractTransactionalJUnit4SpringContextTests{
#Autowired
private IRepository repository;
#Test
public void testRepositoryPersistence() {
Op op = mock(Op.class);
repository.save(op);
}
}
see this tutorial.
I am going to be confused. I am trying to get Hibernate work with Spring, I can not get rid of a BeanCreationException. Please help me. I am new to Spring (and also Hibernate).
The problem is caused in a controller, having a private attribute userService which is annotated with #Autowired.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.aerts.service.UserService com.aerts.controller.TestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.aerts.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I am really confused, please help me somebody.
Here is my root-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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven />
<context:component-scan base-package="com.aerts.controller">
</context:component-scan>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:application.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://....."/>
<property name="username" value="....."/>
<property name="password" value="....."/>
<property name="initialSize" value="5"/>
<property name="maxActive" value="20"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Here is my User.java
package com.aerts.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue()
#Column(name="id")
int id;
#Column(name="gender")
private Gender gender;
#Column(name="birthdate")
private Date birthdate;
#Column(name="firstname")
private String firstname;
#Column(name="surname")
private String surname;
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date age) {
this.birthdate = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname.trim();
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname.trim();
}
}
My UserDaoImpl:
package com.aerts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.aerts.domain.User;
#Service
public class UserDaoImpl implements UserDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User")
.list();
}
#Override
public void removeUser(int id) {
User user = (User) sessionFactory.getCurrentSession().get(
User.class, id);
if (user != null) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
}
And my UserServiceImpl:
package com.aerts.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aerts.dao.UserDao;
import com.aerts.domain.User;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
#Transactional
public void addUser(User user) {
userDao.addUser(user);
}
#Override
#Transactional
public List<User> listUser() {
return userDao.listUser();
}
#Override
#Transactional
public void removeUser(int id) {
userDao.removeUser(id);
}
#Override
#Transactional
public void updateUser(User user) {
userDao.updateUser(user);
}
}
I would really appreciate it if somebody could help me, i am going to be desperate...
Add the service class package to the component-scan base-package list in the application context file
<context:component-scan
base-package="
com.aerts.controller
com.aerts.service">
</context:component-scan>
I'm not expertise in spring but I assume that you have a problem with your service, if you use an interface you should inject ut and not your class...
see this track...
Spring expected at least 1 bean which qualifies as autowire candidate for this dependency