org.springframework.orm.hibernate4.LocalSessionFactoryBean无法强制转换为org.hibernate.SessionFactory

时间:2017-10-11 07:18:02

标签: java spring hibernate maven spring-mvc

我正在尝试将Spring-MVC与Hibernate集成(即-HibernateTemplate) 但是遇到了这个 ClassCastException ,即 org.springframework.orm.hibernate4.LocalSessionFactoryBean无法强制转换为org.hibernate.SessionFactory 。 我正在使用Hibernate-4(ie-org.springframework.orm.hibernate4包)实现-HibernateTemplate,HibernateTransactionManager,LocalSessionFactoryBean。

我无法将LocalSessionFactoryBean的依赖注入到HibernateTemplate和HibernateTransactionManager中 ie-对于SessionFactory(org.hibernate.SessionFactory),LocalSessionFactoryBean(org.springframework.orm.hibernate4.LocalSessionFactoryBean)的转换失败 但是这种依赖注入已被Spring推荐。

project-structure

的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>SpringMVC_HibernateTemp2</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC_HibernateTemp2 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.16</version>
        <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.3.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.11.RELEASE</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.39</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-dbcp -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-dbcp</artifactId>
        <version>7.0.65</version>
    </dependency>

    <!-- Its for Spring-jdbc template -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>2.0.6</version>
    </dependency>

    <!-- Its is for Hibernate template -->
    <!-- https://mvnrepository.com/artifact/javax.transaction/jta -->
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.10.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>
</dependencies>
<build>
    <finalName>SpringMVC_HibernateTemp2</finalName>
</build>

的index.jsp

<html>
<body>
<h2>Welcome to Spring CRUD operation using jdbc</h2>
<marquee><h4>Welcome Admin</h4></marquee>
<form action="./addemp.htm">
Enter id : <input type="text" name="id">
Enter name : <input type="text" name="name">
Enter Salary : <input type="text" name="salary">
<input type="submit" value="submit">
</form>
</body>
</html>

的web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
    <web-app>
     <display-name>Archetype Created Web Application</display-name>
   </web-app>

MyConfig.java

@Configuration
@EnableWebMvc
@ComponentScan({ "com.spring" })
public class MyConfig {

    @Bean(name = "bds")
    public BasicDataSource m1() {
        System.out.println("Basic data source started..........");
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("com.mysql.jdbc.Driver");
        bds.setUrl("jdbc:mysql://localhost:3306/mysqldb");
        bds.setUsername("root");
        bds.setPassword("root");
        System.out.println("Basic data source end..........");
        return bds;
    }

    @Bean(name = "LocalSF")
    public LocalSessionFactoryBean m12() {
        System.out.println(" local SF started...");
        LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
        MyConfig conf = new MyConfig();
        BasicDataSource bds1 = conf.m1();
        sf.setDataSource(bds1);// property 1
        Properties prop = new Properties();
        prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        prop.setProperty("hibernate.hbm2ddl.auto", "create");
        prop.setProperty("hibernate.show_sql", "true");
        prop.setProperty("hibernate.format_sql", "true");
        sf.setHibernateProperties(prop); // property 2
        sf.setAnnotatedClasses(Employee.class); // property 3
        System.out.println(" local SF end...");
        return sf;
    }

    @Bean(name = "txManager")
    public HibernateTransactionManager m13() {
        System.out.println("Tranx Manager started....");
        HibernateTransactionManager htm = new HibernateTransactionManager();
        MyConfig conf = new MyConfig();
        LocalSessionFactoryBean lsf = conf.m12();
        htm.setSessionFactory((SessionFactory) lsf);
        System.out.println("tranx Manager end....");
        return htm;
    }

    @Bean(name = "hiberTemp")
    public HibernateTemplate m14() {
        System.out.println("hibernate template started...");
        HibernateTemplate ht = new HibernateTemplate();
        MyConfig conf = new MyConfig();
        LocalSessionFactoryBean lsf = conf.m12();
        SessionFactory sf = (SessionFactory) lsf;
        ht.setSessionFactory(sf);
        System.out.println("hibernate template end...");
        return ht;
    }

    @Bean
    public InternalResourceViewResolver m2() {
        InternalResourceViewResolver ivr = new InternalResourceViewResolver();
        ivr.setPrefix("/output/");
        ivr.setSuffix(".jsp");
        return ivr;
    }

}

MyWebInitializer.java

public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MyConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "*.htm" };
    }

}

EmpController.java

@Controller(value = "empcontr")
public class EmpController {
    @Autowired
    @Qualifier(value = "servimp")
    private EmpService empserv;

    @RequestMapping(value = "/addemp.htm")
    public ModelAndView m1(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String eid = req.getParameter("id");
        String ename = req.getParameter("name");
        String salary = req.getParameter("salary");

        Employee e1 = new Employee();
        e1.setEid(Integer.parseInt(eid));
        e1.setEname(ename);
        e1.setSalary(Double.parseDouble(salary));

        int i = empserv.saveEmp(e1);
        System.out.println(i + " Inserted..");
        ModelAndView mav = null;
        return mav = i != 0 ? new ModelAndView("success") : new ModelAndView("failure");
    }

}

EmpService.java

public interface EmpService {
 public int saveEmp(Employee e) throws SQLException;
}

EmpServiceImpl.java

@Service(value = "servimp")
public class EmpServiceImpl implements EmpService {
    @Autowired
    @Qualifier(value = "daoimp")
    private EmpDAO edao;

    public int saveEmp(Employee e) throws SQLException {
        return edao.addEmp(e);
    }
}

EmpDAO.java

public interface EmpDAO {
    public int addEmp(Employee e) throws SQLException;
}

EmpDAOImpl.java

@Repository(value = "daoimp")
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class EmpDAOImpl implements EmpDAO {

    @Autowired
    @Qualifier(value = "hiberTemp")
    private HibernateTemplate ht;

    public int addEmp(Employee e) throws SQLException {
        int i = (Integer) ht.save(e);
        return i;
    }

}

Employee.java

@Setter @Getter @ToString
@Entity
@Table(name="employee_table1")
public class Employee {
    @Id
    private int eid;
    private String ename;
    private double salary;

}

我已经如上所述分析了这个Casting问题。 我的maven依赖配置,bean中的依赖注入等都有问题。 我曾尝试阅读很多关于此的帖子,但没有任何帮助。我只是错过了一些东西吗?

这是我从头开始的第一个Spring-MVC / Hibernate项目。 请帮帮我

2 个答案:

答案 0 :(得分:1)

您无法将LocalSessionFactoryBean强制转换为SessionFactory,但不会对其进行扩展或实施,LocalSessionFactoryBeanFactory<>类型为SessionFactory的对象, Factory<SessionFactory>。如果您按住Ctrl +单击类LocalSessionFactoryBean,您可以看到它自己也可以看到它声明了SessionFactory个对象并且getObject()方法返回它。 所以,你的代码应该是:

    @Bean(name = "hiberTemp")
    public HibernateTemplate m14() {
      System.out.println("hibernate template started...");
      HibernateTemplate ht = new HibernateTemplate();
      MyConfig conf = new MyConfig();
      LocalSessionFactoryBean lsf = conf.m12();
      SessionFactory sf = 1sf.getObject();
      ht.setSessionFactory(sf);
      System.out.println("hibernate template end...");
      return ht;
}

答案 1 :(得分:1)

我重写了以下文件:

  1. MyConfig.java
  2. EmpDAOImpl.java
  3. 所有其他文件与问题陈述中提到的相同。

    MyConfig.java

    @Configuration
    @EnableWebMvc
    @EnableTransactionManagement(proxyTargetClass = true)
    @ComponentScan({ "com.spring" })
    public class MyConfig implements TransactionManagementConfigurer {
    
        @Bean(name = "bds")
        public BasicDataSource basicDataSource() {
            System.out.println("Basic data source started..........");
            BasicDataSource bds = new BasicDataSource();
            bds.setDriverClassName("com.mysql.jdbc.Driver");
            bds.setUrl("jdbc:mysql://localhost:3306/mysqldb");
            bds.setUsername("root");
            bds.setPassword("root");
            System.out.println("Basic data source end..........");
            return bds;
        }
    
        @Bean(name = "LocalSF")
        public LocalSessionFactoryBean localSessionFactory() throws IOException {
            System.out.println(" local SF started...");
            LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
            sf.setDataSource(basicDataSource());// property 1
            Properties prop = new Properties();
            prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            prop.setProperty("hibernate.hbm2ddl.auto", "update");
            prop.setProperty("hibernate.show_sql", "true");
            prop.setProperty("hibernate.format_sql", "true");
            sf.setHibernateProperties(prop); // property 2
            sf.setAnnotatedClasses(Employee.class); // property 3
            System.out.println(" local SF end...");
            sf.afterPropertiesSet();
    
            return sf;
        }
    
        @Bean(name = "transactionManager")
        @Autowired
        public HibernateTransactionManager transactionManager() {
            System.out.println("Tranx Manager started....");
            HibernateTransactionManager htm = new HibernateTransactionManager();
    
            try {
                SessionFactory sf = localSessionFactory().getObject();
                htm.setSessionFactory(sf);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("tranx Manager end....");
            return htm;
        }
    
        @Bean(name = "hiberTemp")
        public HibernateTemplate m14() throws IOException {
            System.out.println("hibernate template started...");
            HibernateTemplate ht = new HibernateTemplate();
            SessionFactory sf = localSessionFactory().getObject();
            ht.setSessionFactory(sf);
    
            System.out.println("hibernate template end...");
            return ht;
        }
    
        @Bean
        public InternalResourceViewResolver internalViewResolver() {
            InternalResourceViewResolver ivr = new InternalResourceViewResolver();
            ivr.setPrefix("/output/");
            ivr.setSuffix(".jsp");
            return ivr;
        }
    
        @Bean
        public PlatformTransactionManager annotationDrivenTransactionManager() {
            return transactionManager();
        }
    
    }
    

    EmpDAOImpl.java

    @Repository(value = "daoimp")
    @Transactional
    public class EmpDAOImpl implements EmpDAO {
    
        @Autowired
        @Qualifier(value = "hiberTemp")
        private HibernateTemplate ht;
    
        public int addEmp(Employee e) throws SQLException {
            int i = (Integer) ht.save(e);
    
            return i;
        }
    }
    

    如果上述代码需要更正,请提供建议。 谢谢大家的建议。