2

这是一个非常简单的 spring + hibernate 示例。我在这里做错了什么?

DTO:

package com.xx.dto;

import java.util.Date;
import javax.persistence.*;

@Entity
@Table(name = "users")
public class UserData {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;

    @Column(name = "user_firstname")
    private String firstname;

    @Column(name = "user_lastname")
    private String lastname;

    @Column(name = "user_sex")
    private String sex;

    @Column(name = "user_birthdate")
    private Date birthDate;

    @Column(name = "user_email")
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

DAO接口:

package com.xx.dao;

import java.util.List;
import com.provisori.dto.UserData;

public interface UserDataDao {

    void saveUser(UserData user);

    void deleteUser(String key);

    void updateUser(UserData user);

    List<UserData> listUser();
}

DAO 实现:

package com.xx.imp;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.provisori.dao.UserDataDao;
import com.provisori.dto.UserData;

public class UserDataImp implements UserDataDao{

    @Autowired
    SessionFactory sessionFactory;

    @Transactional
    @Override
    public void saveUser(UserData user) {
        sessionFactory.getCurrentSession().save(user);
    }

    @Transactional
    @SuppressWarnings("unchecked")
    @Override
    public List<UserData> listUser() {
        return sessionFactory.getCurrentSession()
                .createCriteria(UserData.class).list();
    }

    @Transactional
    @Override
    public void updateUser(UserData user) {
        sessionFactory.getCurrentSession().update(user);

    }

    @Transactional
    public UserData getUser(String key) {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(UserData.class);
        criteria.add(Restrictions.eq("key", key));
        return (UserData) criteria.uniqueResult();
    }

    @Transactional
    @Override
    public void deleteUser(String key) {
        UserData user = getUser(key);
        sessionFactory.getCurrentSession().delete(user);
    }
}

春天.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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <!-- Needed for Autowiring -->
    <context:annotation-config />

    <!-- MySQL DataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/xx" />
        <property name="user" value="root" />
        <property name="password" value="" />
    </bean>

    <!-- Hibernate SessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.provisori.dto.UserData</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.hbm2ddl.auto=update
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
            </value>
        </property>
    </bean>

    <!-- Transaction Management -->
    <tx:annotation-driven transaction-manager="txManager" />
    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Java Bean -->
    <bean id="userDataDao" class="com.provisori.imp.UserDataImp" />

</beans>

主类

package com.provisori.dto;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.provisori.dao.UserDataDao;
import com.provisori.imp.UserDataImp;

public class TestMain {

   public static void main(String[] args) {

      // Construct the spring application context
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

      // Register hook to shutdown Spring gracefully
      // See http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-shutdown
      context.registerShutdownHook();

      // Get the business bean from context
      UserDataDao dao = (UserDataImp) context.getBean("userDataDao");

      // Create simple property objects
      UserData user = new UserData();
      user.setFirstname("firstnameTest");
      user.setLastname("lastnameTest");
      dao.saveUser(user);
   }
}

结果

线程“主”java.lang.ClassCastException 中的异常:$Proxy13 无法在 com.provisori.dto.TestMain.main(TestMain.java:21) 处转换​​为 com.provisori.imp.UserDataImp

4

2 回答 2

5

错误是一个很好的指标——接口不能被实例化。使用 bean 实现:

<bean id="userDataDao" class="com.provisori.imp.UserDataImp"> 
于 2012-11-18T21:33:47.633 回答
3

您无法实例化接口。

你的代码:

<!-- Business Bean -->
<bean id="userDataDao" class="com.provisori.dao.UserDataDao">  
    <property name="userDataImp" ref="userDataImp" />  
</bean>
<bean id="userDataImp" class="com.provisori.imp.UserDataImp" />

您需要删除第一个名为userDataDao. 我建议您阅读 Spring Docs,因为您可能不了解/了解 Spring IoC 容器基础知识。

文档是你的朋友:阅读

编辑在您更改源代码后,您的问题中的堆栈跟踪:

你的代码:

UserDataDao dao = (UserDataImp) context.getBean("userDataDao");

尝试将其更改为:

UserDataDao dao = (UserDataDao) context.getBean("userDataDao"); 

您当前的错误是由 Spring 生成的代理类引起的,该代理类不是其子类,UserDataImp但它实现了相同的接口。所以它不能被投射到你的具体实现中。相反,您需要用户界面。

于 2012-11-18T21:41:35.347 回答