Reputation: 4926
I am trying to integrate Spring-MVC with Hibernate(ie-HibernateTemplate) but got stuck with this ClassCastException ie org.springframework.orm.hibernate4.LocalSessionFactoryBean cannot be cast to org.hibernate.SessionFactory. I am implementing -HibernateTemplate,HibernateTransactionManager,LocalSessionFactoryBean using Hibernate-4 (ie-org.springframework.orm.hibernate4 package).
I am not able to do Dependency Injection of LocalSessionFactoryBean into HibernateTemplate and HibernateTransactionManager ie- Casting fails for LocalSessionFactoryBean(org.springframework.orm.hibernate4.LocalSessionFactoryBean) to SessionFactory(org.hibernate.SessionFactory) but this Dependency Injection has been recommended by Spring.
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;
}
I have analyzed this Casting problem as mentioned above. Is anything wrong with my maven dependency configuration, Dependency Injection in bean,etc.. I have tried reading many posts about this, but nothing helped me. Am I just missing something?
This is my first Spring-MVC/Hibernate project from-scratch. Please help me
Upvotes: 1
Views: 2939
Reputation: 4926
I have re-written the following files:
All the other files are same as mentioned in question statement.
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;
}
}
Please provide me suggestion if any correction required for above code. Thank you all for your suggestions.
Upvotes: 2
Reputation: 209
You cannot cast a LocalSessionFactoryBean
to SessionFactory
, it does not extend it or implement, however, LocalSessionFactoryBean
si a Factory<>
object of type SessionFactory
, Factory<SessionFactory>
. If you ctrl+click on the class LocalSessionFactoryBean
, you can see that for yourself, you can also see that it has a SessionFactory
object declared and that getObject()
method returns it.
So, your code should be:
@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;
}
Upvotes: 4