日期:2014-05-19  浏览次数:20733 次

用Annotation整合 spring 和hibernate时出错,大侠看看!
model包下实体类:
@Entity
public class User {

private int id;
private String name;

@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

dao包下UserDAO:

@Component
public class UserDAO {

private HibernateTemplate hibernateTemplate;

public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}

@Resource
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}

public void save(User user){

  this.getHibernateTemplate().save(user);

System.out.println("a user saved");
}
}

service包下UserService:

@Component("userService")
public class UserService {

private UserDAO userDao;

public UserDAO getUserDao() {
return userDao;
}

@Resource
public void setUserDao(UserDAO userDao) {
this.userDao = userDao;
}

public void add(User user){
userDao.save(user);
}
}

bean.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:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="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
  ">

<context:annotation-config />
<context:component-scan base-package="com.spring" />

<!-- more bean definitions go here -->
<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://localhost/spring" />
<property name="username" value="root" />
<property name="password" value="123" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.spring.model.User
</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">
true
</prop>
</props>
</property>
</bean>
  <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory" />
  </bean>

</beans>

测试代码如下(用jUnit):
@Test
public void testAdd() throw