Based on this tutorial, I was trying to manage Hibernate 5 transactions with Spring 4. It seems that the transaction has not been started when session.get() method is reached. How does Spring knows when to start and end a transaction? Shouldn't the #Transactional annotation do precisely this?
Entity
package coproject.cpweb.utils.db.entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import coproject.cpweb.utils.db.entities.Project;
import coproject.cpweb.utils.db.entities.User;
#Entity
#Table( name = "users" )
public class Cbtion {
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy = "increment")
private Integer id;
#ManyToOne
private Project project;
#ManyToOne
private User creator;
private Date creationDate;
private String title;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public User getCreator() {
return creator;
}
public void setCreator(User creator) {
this.creator = creator;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DAO
package coproject.cpweb.utils.db.daos;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import coproject.cpweb.utils.db.entities.User;
#Service
public class CbtionDAO {
#Autowired
SessionFactory sessionFactory;
public void saveUser(User user) {
Session session = sessionFactory.getCurrentSession();
User user_indb = session.get(User.class,user.getId());
if(user_indb == null) {
session.save(user);
}
else {
user = user_indb;
}
}
public User getUser(Integer id) {
Session session = sessionFactory.getCurrentSession();
User user = session.get(User.class,id);
return user;
}
}
Service
package coproject.cpweb.utils.db.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import coproject.cpweb.utils.DbServicesIf;
import coproject.cpweb.utils.db.daos.CbtionDAO;
import coproject.cpweb.utils.db.entities.User;
#Service
public class DbServicesImp implements DbServicesIf{
#Autowired
private CbtionDAO cbtionDAO;
#Transactional
public void saveUser(User user) {
cbtionDAO.saveUser(user);
}
#Transactional
public User getUser(Integer id) {
return cbtionDAO.getUser(id);
}
}
context 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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" >
<tx:annotation-driven />
<context:component-scan base-package="coproject.cpweb.utils.db.entities" />
<context:component-scan base-package="coproject.cpweb.utils.db.daos" />
<context:component-scan base-package="coproject.cpweb.utils.db.services" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="jaof" />
<property name="password" value="iris" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<list>
<value>coproject.cpweb.utils.db.entities</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
<property name="sessionFactory" ref="mySessionFactory" />
</bean>
</beans>
Main
package coproject.cploc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import coproject.cpweb.utils.db.entities.User;
import coproject.cpweb.utils.db.services.DbServicesImp;
public class FillRandomDb {
public static void main(String[] args) throws Exception {
#SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// TEST String[] bean_names = context.getBeanDefinitionNames();
DbServicesImp dbServices = (DbServicesImp) context.getBean("dbServicesImp");
User user = new User();
user.setUsername("johndoe");
user.setFirstname("John");
user.setLastname("Doe");
dbServices.saveUser(user);
User user_ret = dbServices.getUser(user.getId());
System.out.println(user_ret.getFirstname());
}
}
Stack
nov 29, 2015 1:45:37 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#506e6d5e: startup date [Sun Nov 29 13:45:37 CE
T 2015]; root of context hierarchy
nov 29, 2015 1:45:37 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
nov 29, 2015 1:45:38 PM org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
nov 29, 2015 1:45:38 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
nov 29, 2015 1:45:38 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
nov 29, 2015 1:45:38 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
nov 29, 2015 1:45:38 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
nov 29, 2015 1:45:39 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
nov 29, 2015 1:45:45 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
nov 29, 2015 1:45:46 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
nov 29, 2015 1:45:46 PM org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource#5e1d03d7] of Hibernate SessionFactory for HibernateTransactionMana
ger
Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:33
4)
at com.sun.proxy.$Proxy23.get(Unknown Source)
at coproject.cpweb.utils.db.daos.CbtionDAO.saveUser(CbtionDAO.java:19)
at coproject.cpweb.utils.db.services.DbServicesImp.saveUser(DbServicesImp.java:20)
at coproject.cpweb.utils.db.services.DbServicesImp$$FastClassBySpringCGLIB$$cd649fcb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281
)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at coproject.cpweb.utils.db.services.DbServicesImp$$EnhancerBySpringCGLIB$$75288f15.saveUser(<generated>)
at coproject.cploc.FillRandomDb.main(FillRandomDb.java:24)
Try to change this line in your file context beans.xml:
<prop key="hibernate.current_session_context_class">thread</prop>
With this line:
<prop key="current_session_context_class">thread</prop >
And for annotation support, in your spring config bean, add this:
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true" />
DAO class should be annotated as #Repository.
Related
I started with spring ORM + Hibernate tutorials. While running the main.java, getting bellow exception and since exception does not have more details about the error. I am not able to figure out the issue. Could please someone can help where is an issue in my code.
config.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<context:component-scan base-package="demo.spring.orm.userService.userEntity" />
<context:component-scan base-package="demo.spring.orm.userService.UserService" />
<context:annotation-config />
<tx:annotation-driven/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name="ds">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=pathDB_New" />
<property name="username" value="sa" />
<property name="password" value="arst#dm1n" />
</bean>
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" name="lsfb">
<property name="dataSource" ref="ds"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>demo.spring.orm.userEntity.User</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTemplate" name="ht">
<property name="sessionFactory" ref="lsfb"></property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" name="transactionManager">
<property name="sessionFactory" ref="lsfb"></property>
</bean>
<bean class="demo.spring.orm.userService.UserService" name="userService">
<property name="hibernateTemplate" ref="ht"></property>
</bean>
</beans>
UserService.java
package demo.spring.orm.userService;
import javax.transaction.Transactional;
import org.springframework.orm.hibernate5.HibernateTemplate;
import demo.spring.orm.userDao.UserDao;
import demo.spring.orm.userEntity.User;
public class UserService implements UserDao{
public HibernateTemplate hibernateTemplate;
#Transactional
public void add(User user) {
hibernateTemplate.save(user);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
User.java
package demo.spring.orm.userEntity;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int userId;
private String userName;
private String email;
private String title;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int userId, String userName, String email, String title) {
super();
this.userId = userId;
this.userName = userName;
this.email = email;
this.title = title;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
main.java
package demo.spring.orm;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import demo.spring.orm.userEntity.User;
import demo.spring.orm.userService.UserService;
public class main {
public static void main(String args[])
{
ApplicationContext context= new ClassPathXmlApplicationContext("config.xml");
UserService userService=context.getBean("userService",UserService.class);
User user=new User(2,"Arunendra","mail#mail.com","Software Engineer");
userService.add(user);
}
}
Exception:
Jul 27, 2021 8:48:39 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.4.30.Final
Jul 27, 2021 8:48:40 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jul 27, 2021 8:48:44 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Hibernate: create table User (userId int not null, email varchar(255), title varchar(255), userName varchar(255), primary key (userId))
Jul 27, 2021 8:48:46 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL "create table User (userId int not null, email varchar(255), title varchar(255), userName varchar(255), primary key (userId))" via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table User (userId int not null, email varchar(255), title varchar(255), userName varchar(255), primary key (userId))" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:318)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:468)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:616)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at demo.spring.orm.main.main(main.java:11)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near the keyword 'User'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1632)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:872)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:767)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7225)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:3053)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:247)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:222)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.execute(SQLServerStatement.java:743)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
... 28 more
Jul 27, 2021 8:48:46 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Exception in thread "main" org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userService' is expected to be of type 'demo.spring.orm.userService.UserService' but was actually of type 'com.sun.proxy.$Proxy20'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:395)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1114)
at demo.spring.orm.main.main(main.java:12)
You can solve that problem by enabling CGLIB proxy, add proxy-target-class attribute in your spring context :
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
I am new to Spring and while setting all the bean for spring orm configuration, I am getting this error: org.springframework.beans.factory.BeanCreationException
I do not know what exactly I am doing wrong and how to get the desired result.
here is my code:
App.java
package com.spring.orm;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.orm.dao.StudentDao;
import com.spring.orm.entities.Student;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("config.xml");
StudentDao studentDao= context.getBean("studentDao", StudentDao.class);
Student student=new Student(1, "Ayush Bansal", "Delhi");
studentDao.saveStudent(student);
}
}
studentDao
package com.spring.orm.dao;
import javax.transaction.Transactional;
import org.springframework.orm.hibernate5.HibernateTemplate;
import com.spring.orm.entities.Student;
public class StudentDao {
private HibernateTemplate hibernateTemplate;
#Transactional
public void saveStudent(Student student) {
hibernateTemplate.save(student);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
}
Student.java
package com.spring.orm.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student_details")
public class Student {
#Id
#Column(name="student_id")
private int id;
#Column(name="student_name")
private String name;
#Column(name="student_city")
private String city;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
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;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Config.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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:c="http://www.springframework.org/schema/c"
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">
<tx:annotation-driven/>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name="ds">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myhiber"/>
<property name="username" value="root"/>
<property name="password" value="Vampire#911"/>
</bean>
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" name="factory">
<!-- dataSource -->
<property name="dataSource" ref="ds"></property>
<!-- hibernate properties -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<!-- annotated classes -->
<property name="annotatedClasses">
<list>
<value>
com.spring.orm.entities.Student
</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTemplate" name="hibernateTemplate">
<property name="sessionFactory" ref="factory"></property>
</bean>
<bean class="com.spring.orm.dao.StudentDao" name="studentDao">
<property name="hibernateTemplate" ref="hibernateTempLate"></property>
</bean>
<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" name="transactionManager">
<property name="sessionFactory" ref="factory"/>
</bean>
</beans>
Error
Jul 24, 2021 8:21:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.2.Final}
Jul 24, 2021 8:21:58 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Jul 24, 2021 8:21:59 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : Could not create connection to database server.
Jul 24, 2021 8:21:59 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists student_details
Jul 24, 2021 8:22:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
Jul 24, 2021 8:22:00 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Could not create connection to database server.
Jul 24, 2021 8:22:00 PM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'factory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at com.spring.orm.App.main(App.java:19)
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:69)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.jdbcStatement(GenerationTargetToDatabase.java:77)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:53)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:375)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:241)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:145)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:616)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792)
... 12 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2588)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:189)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:154)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:145)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)
... 30 more
Caused by: java.lang.NullPointerException: Cannot invoke "java.util.Map.get(Object)" because "this.serverVariables" is null
at com.mysql.jdbc.ConnectionImpl.getServerCharacterEncoding(ConnectionImpl.java:3307)
at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1985)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1911)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2506)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2539)
... 50 more
Thanks for helping in advance.
I am getting the following error while trying to connect to mysql using hibernate. I have a Super class Employee and three subclasses: SoftwareEmployee, HardWareEmployee and Admin.I also have two xml files: hibernateisapersubclass.cfg.xml and employeeisapersubclass.hbm.xml. I am trying to populate data in 4 different table using 'joined-subclass' tag in my xml. Please help.
Error that I am getting are as follows:
Dec 04, 2016 7:45:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.5.Final}
Dec 04, 2016 7:45:34 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 04, 2016 7:45:34 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/hqlstudent]
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sun Dec 04 19:45:35 EST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Dec 04, 2016 7:45:35 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 04, 2016 7:45:36 PM org.hibernate.AssertionFailure <init>
ERROR: HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: Table hqlstudent.superemployee not found
Dec 04, 2016 7:45:36 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost/hqlstudent]
Exception in thread "main" org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:128)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:297)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at test.ClientIsAPerSubClass.main(ClientIsAPerSubClass.java:22)
Caused by: org.hibernate.AssertionFailure: Table hqlstudent.superemployee not found
at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5168)
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 7 more
Following are my five java files and two xml files:
ClientIsAPerSubClass.java
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import beans.Admin;
import beans.Admin1;
import beans.HardwareEmployee;
import beans.HardwareEmployee1;
import beans.SoftwareEmployee;
import beans.SoftwareEmployee1;
public class ClientIsAPerSubClass {
public static void main(String [] args){
Configuration configuration = new Configuration();
configuration.configure("resources/hibernateisapersubclass.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction= session.beginTransaction();//student object will move database;
SoftwareEmployee1 softwareEmployee= new SoftwareEmployee1();
softwareEmployee.setId(1);
softwareEmployee.setName("bishwash");
softwareEmployee.setEmail("20wash.sharma#gmail.com");
softwareEmployee.setSalary(60000);
softwareEmployee.setTool("hibernate");
HardwareEmployee1 hardwareEmployee = new HardwareEmployee1();
hardwareEmployee.setId(2);
hardwareEmployee.setName("mahendra");
hardwareEmployee.setEmail("mahendra#mahendra.com");
hardwareEmployee.setSalary(55000);
hardwareEmployee.setWorkinghour(20);
Admin1 admin= new Admin1();
admin.setId(3);
admin.setName("ashish#ashish.com");
admin.setEmail("mahendra#mahendra.com");
admin.setSalary(60000);
admin.setBranchname("Kathmandu");;
session.save(softwareEmployee);
session.save(hardwareEmployee);
session.save(admin);
transaction.commit();
session.close();
sessionFactory.close();
//System.out.println("no of rows dumped from old to new table"+i);
}
}
Admin.java
package beans;
public class Admin extends Employee {
private String branchname;
public Admin() {
}
public Admin(int id, String name, String email, double salary, String branchname) {
super(id, name, email, salary);
this.branchname= branchname;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
}
package beans;
public class HardwareEmployee extends Employee {
private int workinghour;
public HardwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public HardwareEmployee(int id, String name, String email, double salary, int workinghour) {
super(id, name, email, salary);
this.workinghour= workinghour;
}
public int getWorkinghour() {
return workinghour;
}
public void setWorkinghour(int workinghour) {
this.workinghour = workinghour;
}
}
SoftwareEmployee.java
package beans;
public class SoftwareEmployee extends Employee {
private String tool;
public SoftwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public SoftwareEmployee(int id, String name, String email, double salary ,String tool) {
super(id, name, email, salary);
this.tool= tool;
}
public String getTool() {
return tool;
}
public void setTool(String tool) {
this.tool = tool;
}
}
HardwareEmployee.java
package beans;
public class HardwareEmployee extends Employee {
private int workinghour;
public HardwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public HardwareEmployee(int id, String name, String email, double salary, int workinghour) {
super(id, name, email, salary);
this.workinghour= workinghour;
}
public int getWorkinghour() {
return workinghour;
}
public void setWorkinghour(int workinghour) {
this.workinghour = workinghour;
}
}
employeeisapersubclass.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Employee" table ="superemployee" schema="hqlstudent">
<id name="id"/>
<property name="name" />
<property name="email" />
<property name="salary" />
<joined-subclass name="beans.SoftwareEmployee" table="softwareemployee">
<key column ="id"/>
<property name="tool"/>
</joined-subclass>
<joined-subclass name="beans.HardwareEmployee" table="hardwareemployee">
<key column ="id"/>
<property name="workinghour"/>
</joined-subclass>
<joined-subclass name="beans.Admin" table="admin">
<key column ="id"/>
<property name="branchname"/>
</joined-subclass>
</class>
</hibernate-mapping>
hibernateisapersubclass.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.hbm2ddl.auto">
create
</property>
<property name="hibernate.show_sql">
true
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume customstudent is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hqlstudent
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
password
</property>
<mapping resource="resources/employeeisapersubclass.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I am developing small student app, based on Spring MVC which should implement simple CRUD students operations via rest web services onto mysql database.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
mvc-dispatcher-servlet.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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:database.properties" />
<context:component-scan base-package="com.training.dao" />
<context:component-scan base-package="com.training.service" />
<context:component-scan base-package="com.training.controller" />
<context:component-scan base-package="com.training.bean" />
<context:component-scan base-package="com.training.dto" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.training.bean.StudentBean</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
StudentsController.java:
package com.training.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.training.bean.StudentBean;
import com.training.dto.ResponseDTO;
import com.training.service.StudentService;
#RestController
#RequestMapping(value = "/student")
#EnableWebMvc
public class StudentController {
#Autowired
StudentService studentService;
ResponseDTO responseDTO;
#RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public #ResponseBody ResponseDTO getStudent(#PathVariable("id") int studentId) {
try {
StudentBean student = studentService.getStudent(studentId);
responseDTO = studentService.converToDTO(true, "success", student, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public #ResponseBody ResponseDTO createStudent(#RequestBody StudentBean student) {
try {
studentService.addStudent(student);
responseDTO = studentService.converToDTO(true, "success", null, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public #ResponseBody ResponseDTO deleteStudent(#PathVariable("id") int studentId) {
try {
studentService.deleteStudent(studentId);
responseDTO = studentService.converToDTO(true, "success", null, null);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/getAll", method = RequestMethod.GET)
public #ResponseBody ResponseDTO getAllStudents() {
try {
java.util.List<StudentBean> students = studentService.getAllStudents();
responseDTO = studentService.converToDTO(true,"success", null, students);
} catch (Exception e) {
responseDTO = studentService.converToDTO(false,e.getMessage(), null, null);
}
return responseDTO;
}
#RequestMapping(value = "/about")
public String aboutPage() {
return "about";
}
}
Now when I call for example
localhost:8080/student/getAll
or any of the mapped methods the reponse is
HTTP Status 404 - /student/getAll
The requested resource is not available.
Here is catalina.out, no errors there:
Oct 22, 2016 10:23:17 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
INFO: Mapped "{[/about/app]}" onto public java.lang.String com.training.controller.AboutController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/delete/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.deleteStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/get/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/getAll],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getAllStudents()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/about]}" onto public java.lang.String com.training.controller.StudentController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/add],methods=[POST]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.createStudent(com.training.bean.StudentBean)
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sat Oct 22 10:23:17 EEST 2016]; root of context hierarchy
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 3912 ms
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 22, 2016 10:23:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7653 ms
#EnableWebMvc applies to Spring configuration classes (i.e. classes annotated with #Configuration). It's not having any effect on your controller. From the first line of the #EnableWebMvc Javadoc page (emphasis mine):
Adding this annotation to an #Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport...
Since you're using XML configuration instead of Java Annotation driven configuration, simply add this to your mvc-dispatcher-servlet.xml: file:
<mvc:annotation-driven/>
As is, without this configuration active, Spring is trying to route to a view with the same name as your request mapping. Since it doesn't exist, you're getting the 404 Not Found error.
I'm trying to find out what have I done wrong. It would be great if anyone could help me. I keep getting this in an infinite loop:
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#799f7e29: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
May 02, 2015 9:41:57 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#548a9f61: startup date [Sat May 02 21:41:57 EEST 2015]; root of context hierarchy
May 02, 2015 9:41:57 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
UsersDAOImp :
public class UsersDAOImp extends GenericEntityDAO implements UsersDAO {
private SessionFactory sessionFactory = (SessionFactory) BeanManager.getBean("sessionFactory");
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Users> selectAll() {
Session session = getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(Users.class);
List<Users> users = (List<Users>) criteria.list();
session.getTransaction().commit();
return users;
}
}
UsersService
public class UsersService {
UsersDAOImp usersDAO = new UsersDAOImp();
public void setUsersDAO(UsersDAOImp usersDAO) {
this.usersDAO = usersDAO;
}
public UsersDAOImp getUsersDAO() {
return usersDAO;
}
public List<Users> getAllUsers() {
return getUsersDAO().selectAll();
}
}
Bean manager used to get context
public class BeanManager {
/* BeanManager is used to parse Beans.xml file */
private static ApplicationContext context;
private BeanManager() {
}
public static ApplicationContext getContext() {
return context;
}
public static void setContext(ApplicationContext context) {
BeanManager.context = context;
}
public static Object getBean(String beanId) {
if (context == null) {
context = new ClassPathXmlApplicationContext("Beans.xml");
}
Object result = context.getBean(beanId);
return result;
}
}
This is my 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" 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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="usersDAO" class="com.survey.persistance.DAO.UsersDAOImp" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/app" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>