Too many connections with Spring + MyBatis + MySQL + JDBC - java

I am trying to work with spring, mybatis and mysql with jdbc. The only small problem I have after some queries, it throws an exception. The DB says: Too many connections.
So what I am trying to do to prevent the too many connection issue is to set up a connection pool. I have tried dbcp and bonecp also but both have the same behaviour. When I reload my page it just keeps loading in the browser and after some debugging it seems it hangs after the 9th or 10th select.
My scenario looks like this:
1: "select * from maincategory"
This query returns around 15 categories. I map the resultset into a List containing MainCategory elements.
Then what I do is I walk through the MainCategory List and get the IDs from each MainCategory and then I do an other select to get their sub categories:
2: "select * from subcategories where id = ${id_from_main_category_actual_row}"
And it seems it hangs after the 9th or 10th subcategory selection.
Here is my transaction manager and sqlsessionfactory configuration:
<beans:bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="configLocation" value="WEB-INF/spring/myBatis/mybatis.xml" />
<beans:property name="mapperLocations" value="WEB-INF/spring/myBatis/mbmapper-*.xml" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
And here is the configuration for a datasource with dbcp:
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
</beans:bean>
And my other try was with the bonecp:
<beans:bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<beans:property name="driverClass" value="com.mysql.jdbc.Driver" />
<beans:property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
<beans:property name="idleConnectionTestPeriodInSeconds" value="30"/>
<beans:property name="idleMaxAgeInMinutes" value="1"/>
<beans:property name="maxConnectionsPerPartition" value="7"/>
<beans:property name="minConnectionsPerPartition" value="7"/>
<beans:property name="partitionCount" value="1"/>
<beans:property name="acquireIncrement" value="1"/>
<beans:property name="acquireRetryAttempts" value="1"/>
<beans:property name="acquireRetryDelayInMs" value="5000"/>
<beans:property name="maxConnectionAgeInSeconds" value="0"/>
<beans:property name="connectionTestStatement" value="SELECT 1"/>
<beans:property name="statementsCacheSize" value="100"/>
<beans:property name="disableConnectionTracking" value="true"/>
</beans:bean>
As you can see I tried many optimization on this with the properties. I think regardless if the method querying for main and their subcategories is a good or wrong practise, its only 10 small queries with some data returned so it should work.
If I use the "org.springframework.jdbc.datasource.DriverManagerDataSource" as the datasource, the db says the "too many connection" after some page refresh, while the tried connection pools just hang after the mentioned amount of query.
UPDATE based on comments:
Here is my detailed code as requested:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/appServlet/ApplicationContext.xml
/WEB-INF/spring/appServlet/ApplicationContext-security.xml
</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
root-context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
ApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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-2.5.xsd">
<beans:bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<context:annotation-config />
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<!--
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
-->
<context:component-scan base-package="com.test.packit" />
<!-- Thymeleaf Template & View Resolver configurations -->
<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<beans:property name="prefix" value="/WEB-INF/templates/" />
<beans:property name="suffix" value=".html" />
<beans:property name="templateMode" value="HTML5" />
<beans:property name="cacheable" value="false" />
</beans:bean>
<beans:bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<beans:property name="templateResolver" ref="templateResolver" />
<beans:property name="additionalDialects">
<beans:set>
<beans:bean class="org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect" />
</beans:set>
</beans:property>
</beans:bean>
<beans:bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<beans:property name="templateEngine" ref="templateEngine" />
</beans:bean>
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="localization/general/messages" />
</beans:bean>
<beans:bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<beans:property name="driverClass" value="com.mysql.jdbc.Driver" />
<beans:property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
<beans:property name="idleConnectionTestPeriodInSeconds" value="30"/>
<beans:property name="idleMaxAgeInMinutes" value="1"/>
<beans:property name="maxConnectionsPerPartition" value="7"/>
<beans:property name="minConnectionsPerPartition" value="7"/>
<beans:property name="partitionCount" value="1"/>
<beans:property name="acquireIncrement" value="1"/>
<beans:property name="acquireRetryAttempts" value="1"/>
<beans:property name="acquireRetryDelayInMs" value="5000"/>
<beans:property name="maxConnectionAgeInSeconds" value="0"/>
<beans:property name="connectionTestStatement" value="SELECT 1"/>
<beans:property name="statementsCacheSize" value="100"/>
<beans:property name="disableConnectionTracking" value="true"/>
</beans:bean>
<!--
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root"/>
<beans:property name="password" value=""/>
</beans:bean>
-->
<!-- Original data source without connection pooling -->
<!--
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/testdb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
-->
<beans:bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<beans:property name="configLocation" value="WEB-INF/spring/myBatis/mybatis.xml" />
<beans:property name="mapperLocations" value="WEB-INF/spring/myBatis/mbmapper-*.xml" />
<beans:property name="dataSource" ref="dataSource" />
</beans:bean>
<!-- MAPPER: ACCOUNT -->
<beans:bean id="accountDao" class="com.test.packit.dao.AccountDao">
<beans:property name="sessionFactory" ref="sqlSessionFactory" />
</beans:bean>
<beans:bean id="accountService" class="com.test.packit.service.AccountService">
<beans:property name="accountDao" ref="accountDao" />
</beans:bean>
<!-- MAPPER: MAIN_CATEGORY -->
<beans:bean id="mainCategoryDao" class="com.test.packit.dao.MainCategoryDao">
<beans:property name="sessionFactory" ref="sqlSessionFactory" />
</beans:bean>
<beans:bean id="mainCategoryService" class="com.test.packit.service.MainCategoryService">
<beans:property name="mainCategoryDao" ref="mainCategoryDao" />
</beans:bean>
<!-- MAPPER: SUB_CATEGORY -->
<beans:bean id="subCategoryDao" class="com.test.packit.dao.SubCategoryDao">
<beans:property name="sessionFactory" ref="sqlSessionFactory" />
</beans:bean>
<beans:bean id="subCategoryService" class="com.test.packit.service.SubCategoryService">
<beans:property name="subCategoryDao" ref="subCategoryDao" />
</beans:bean>
</beans:beans>
ApplicationContext-security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
<intercept-url pattern="/user.jsp" access="ROLE_USER" />
<session-management session-fixation-protection="none">
<concurrency-control />
</session-management>
<form-login
login-page="/login"
login-processing-url="/letmein"
default-target-url="/"
authentication-failure-url="/login-error"
username-parameter="bm_username"
password-parameter="bm_password" />
<logout logout-url="/logout"/>
<!-- enable csrf protection -->
<csrf/>
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT username, password, enabled
FROM bm_users
WHERE username=?"
authorities-by-username-query="SELECT username, role
FROM bm_roles
WHERE username=?" />
<password-encoder hash="bcrypt"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
mbmapper-mainCategory-mapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="maincategory">
<cache type="org.mybatis.caches.hazelcast.LoggingHazelcastCache"/>
<select id="getAllMainCategories" resultType="list" resultMap="mainCategoryMap.mainCategoryResultMap">
SELECT * FROM packit.bm_maincategory;
</select>
</mapper>
mbmapper-mainCategory-resultMap.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mainCategoryMap">
<resultMap type="com.test.packit.model.MainCategory" id="mainCategoryResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
</mapper>
mbmapper-subCategory-mapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="subcategory">
<cache type="org.mybatis.caches.hazelcast.LoggingHazelcastCache"/>
<select id="getAllSubCategoriesForMainCategory" parameterType="int" resultType="list" resultMap="subCategoryMap.subCategoryResultMap">
SELECT * FROM packit.bm_subcategory WHERE maincategory_id = #{id};
</select>
</mapper>
mbmapper-subCategory-resultMap.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="subCategoryMap">
<resultMap type="com.test.packit.model.SubCategory" id="subCategoryResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
</mapper>
MainCategory.java:
package com.test.packit.model;
import java.io.Serializable;
import java.util.List;
public class MainCategory implements Serializable {
private static final long serialVersionUID = -7970848646314840509L;
private Integer id;
private String name;
private List<SubCategory> subCategories;
public List<SubCategory> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
}
public MainCategory() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MainCategoryDao.java:
package com.test.packit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.test.packit.model.MainCategory;
#Repository
public class MainCategoryDao {
#Resource
private SqlSessionFactory sessionFactory;
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public List<MainCategory> getAllMainCategories(){
SqlSession session = sessionFactory.openSession();
List<MainCategory> mainCategoriesFromDb = (List<MainCategory>)(List<?>) session.selectList("maincategory.getAllMainCategories");
return mainCategoriesFromDb;
}
}
MainCategoryService.java:
package com.test.packit.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.test.packit.dao.MainCategoryDao;
import com.test.packit.model.MainCategory;
#Repository
public class MainCategoryService {
#Resource
private MainCategoryDao mainCategoryDao;
public List<MainCategory> getAllCategories() {
return mainCategoryDao.getAllMainCategories();
}
public MainCategoryDao getMainCategoryDao() {
return mainCategoryDao;
}
public void setMainCategoryDao(MainCategoryDao mainCategoryDao) {
this.mainCategoryDao = mainCategoryDao;
}
}
SubCategory.java:
package com.test.packit.model;
import java.io.Serializable;
public class SubCategory implements Serializable {
private static final long serialVersionUID = -7970848646314840509L;
private Integer id;
private Integer mainCategoryId;
private String name;
public Integer getMainCategoryId() {
return mainCategoryId;
}
public void setMainCategoryId(Integer mainCategoryId) {
this.mainCategoryId = mainCategoryId;
}
public SubCategory() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
SubCategoryDao.java:
package com.test.packit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.test.packit.model.SubCategory;
#Repository
public class SubCategoryDao {
#Resource
private SqlSessionFactory sessionFactory;
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public List<SubCategory> getAllSubCategoriesForMainCategory(int id){
SqlSession session = sessionFactory.openSession();
List<SubCategory> subCategoriesFromDb = (List<SubCategory>)(List<?>) session.selectList("subcategory.getAllSubCategoriesForMainCategory", id);
return subCategoriesFromDb;
}
}
SubCategoryService.java:
package com.test.packit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;
import com.test.packit.model.SubCategory;
#Repository
public class SubCategoryDao {
#Resource
private SqlSessionFactory sessionFactory;
public SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SqlSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public List<SubCategory> getAllSubCategoriesForMainCategory(int id){
SqlSession session = sessionFactory.openSession();
List<SubCategory> subCategoriesFromDb = (List<SubCategory>)(List<?>) session.selectList("subcategory.getAllSubCategoriesForMainCategory", id);
return subCategoriesFromDb;
}
}
HomeController.java:
package com.test.packit;
import com.test.packit.authentication.AuthenticatorController;
import com.test.packit.model.MainCategory;
import com.test.packit.model.SubCategory;
import com.test.packit.service.MainCategoryService;
import com.test.packit.service.SubCategoryService;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#Resource
private MainCategoryService mainCategoryService;
private List<MainCategory> mainCategories;
#Resource
private SubCategoryService subCategoryService;
private List<SubCategory> subCategories;
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Locale locale, Model model) {
// Get all main categories
mainCategories = mainCategoryService.getAllCategories();
for(MainCategory mainCategory : mainCategories) {
logger.info("Main Category: {}", mainCategory.getName());
// Get all sub categories
subCategories = subCategoryService.getAllSubCategoriesForMainCategory(mainCategory.getId());
mainCategory.setSubCategories(subCategories);
for(SubCategory subCategory : subCategories) {
logger.info("\t\t- {}", subCategory.getName());
}
}
model.addAttribute("mainCategories", mainCategories);
return "index";
}
}
Any suggestion are very welcomed.

1. When creating SqlSessions manually you have to make sure that you close them after use.
Look for all places where you are opening a SqlSession:
SqlSession session = sessionFactory.openSession();
Make sure that you're closing the session after use. You should do that in try-finally block, like below:
SqlSession session = sqlSessionFactory.openSession();
try {
// following 3 lines pseudocode for "doing some work"
session.insert(...);
session.update(...);
session.delete(...);
session.commit();
} finally {
session.close();
}
More information on how to handle MyBatis SqlSessions can be found here: http://mybatis.github.io/mybatis-3/java-api.html#sqlSessions
2. You can use MyBatis-Spring to create and manage the lifecycle of SqlSessions.
Instead of injecting DAO's with SqlSessionFactory, you can ask spring to inject the SqlSessions directly. When you do this, Spring will manage the SqlSessions for you, so you will not have to open/close sessions by yourself.
More information how to do this is here: http://mybatis.github.io/spring/sqlsession.html

Related

saveOrupdate is working in second attempt in hibernate not in first

I am working on Spring Hibernate application.
There i am trying to update Table to using session.saveOrUpdate method.
But it is not working in very first time. from second attempt i am able to update data in DB.
In first time no exception is coming. Everything is correct.
config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
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-4.0.xsd">
<!-- This bean configuration only for your local tomcat deployment -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="${db.driverClassName}" />
<beans:property name="url" value="${db.url}" />
<beans:property name="username" value="${db.username}" />
<beans:property name="password" value="${db.password}" />
</beans:bean>
<!-- weblogic server Jndi configuration for LYRA DB Datasource -->
<!-- <beans:bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="jdbc/lyraDB" />
</beans:bean> -->
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.orange.lyra.web.model.AdminGestionProfiles</beans:value>
<beans:value>com.orange.lyra.web.model.BuzonesPermisions</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="scoreCardDao" class="com.orange.lyra.web.dao.impl.ScoreCardDaoImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="administracionDao" class="com.orange.lyra.web.dao.impl.AdminControllerDaoImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
Modal Bean class
package com.orange.lyra.web.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "LYRA_ADMIN_GESTION_PROFILE")
public class AdminGestionProfiles {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
#Column(name = "ID")
private String Id;
#Column(name = "PROFILE_ID")
private String profileIds;
#Column(name = "BUZONE_ID")
private String buzoneIds;
#Column(name = "PERMISOS_ID")
private String permisosIds;
#Column(name = "STATUS")
private String statusCheck;
public String getProfileIds() {
return profileIds;
}
public void setProfileIds(String profileIds) {
this.profileIds = profileIds;
}
public String getBuzoneIds() {
return buzoneIds;
}
public void setBuzoneIds(String buzoneIds) {
this.buzoneIds = buzoneIds;
}
public String getPermisosIds() {
return permisosIds;
}
public void setPermisosIds(String permisosIds) {
this.permisosIds = permisosIds;
}
public String getStatusCheck() {
return statusCheck;
}
public void setStatusCheck(String statusCheck) {
this.statusCheck = statusCheck;
}
}
ServiceImpl class
#Override
#Transactional
public String updatePermisosStatusByAdmin(String profileId, String buzoneID, String[] permisosIdList) {
List<AdminGestionProfiles> adminList = administracionDao.getAdminisotable(profileId,buzoneID);
for(int j =0;j<permisosIdList.length;j++)
{
for (AdminGestionProfiles adminGestionProfiles : adminList) {
if(permisosIdList[j].toString().equals(adminGestionProfiles.getPermisosIds())){
adminGestionProfiles.setStatusCheck("1");
}
}
}
String message = administracionDao.updatePermisosStatusByAdmin(adminList);
return message;
}
DaoImpl class
public class AdminControllerDaoImpl implements AdminControllerDao{
private static final Logger LOGGER = Logger .getLogger(AdminControllerDaoImpl.class);
/** The session factory. */
private SessionFactory sessionFactory;
/**
* Sets the session factory.
* #param sf
* the new session factory
*/
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#Override
public String updatePermisosStatusByAdmin(List<AdminGestionProfiles> adminList) { LOGGER.debug("AdminControllerDaoImpl::updatePermisosStatusByAdmin::start");
try{
Session session = this.sessionFactory.getCurrentSession();
for (AdminGestionProfiles adminGestionProfiles : adminList) {
session.saveOrUpdate(adminGestionProfiles);
}
}catch(HibernateException error){
String err = error.getMessage();
LOGGER.debug("Hibernate Exception throw in updatePermisosStatusByAdmin mehthod ::" +err);
}
LOGGER.debug("AdminControllerDaoImpl::updatePermisosStatusByAdmin::End");
return "El proceso se ha realizado correctamente";
}
}
You are retrieving the Admins from the DB and updating some value, just call "update()" instead of "saveOrUpdate()", you know that the record already exists in the DB.
If this don't solve your problem post the exception please.
PS: Sorry for posting and answer directly, but i can't comment yet :)

Not able to use injected properties in spring beans

below is my spring-database.xml file. I can use sessionFactory in userDao. I also can use userDao in myUserDetailsService class. but when i try to use sessionFactory in registrationDao it gives me NullPointerException. same happens when i try to use registrationDao in registrationService service.
i am getting confused. please help.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/myds" />
<property name="username" value="root" />
<property name="password" value="mypass" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.findsuvidha.web.entity"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDao" class="com.findsuvidha.web.dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="myUserDetailsService" class="com.findsuvidha.web.service.MyUserDetailsService">
<property name="userDao" ref="userDao" />
</bean>
<bean id="registrationDao" class="com.findsuvidha.web.dao.RegistrationDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="registrationService" class="com.findsuvidha.web.service.RegistrationService">
<property name="registrationDao" ref="registrationDao" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.findsuvidha.web.service.*Service.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut" />
</aop:config>
</beans>
Edit1:-Dao and DaoImpl which are able to use injected property
UserDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.entity.LoginMaster;
public interface UserDao {
LoginMaster findByUserName(String username);
}
UserDaoImpl.java
package com.findsuvidha.web.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.SessionFactory;
import com.findsuvidha.web.entity.LoginMaster;
public class UserDaoImpl implements UserDao {
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public LoginMaster findByUserName(String email) {
List<LoginMaster> users = new ArrayList<LoginMaster>();
users = getSessionFactory().getCurrentSession().createQuery("from LoginMaster where email=?")
.setParameter(0, email).list();
if (users.size() > 0) {
return users.get(0);
} else {
return null;
}
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
Dao and DaoImpl which are not able to use injected property
RegistrationDao.java
package com.findsuvidha.web.dao;
import com.findsuvidha.web.transferobject.NewUser;
public interface RegistrationDao {
void insertUser(NewUser user);
}
RegistrationDaoImpl.java
package com.findsuvidha.web.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.findsuvidha.web.entity.LoginMaster;
import com.findsuvidha.web.entity.UserDetail;
import com.findsuvidha.web.transferobject.NewUser;
public class RegistrationDaoImpl implements RegistrationDao{
private SessionFactory sessionFactory;
private LoginMaster loginUser = new LoginMaster();
private UserDetail userDetail = new UserDetail();
#Override
public void insertUser(NewUser user) {
System.out.println("entered dao impl");
userDetail.setEmail(user.getEmail());
userDetail.setFirstName(user.getFirstName());
userDetail.setLastName(user.getLastName());
userDetail.setMobileNo(user.getMobileNumber());
loginUser.setEmail(user.getEmail());
loginUser.setPassword(user.getPassword());
loginUser.setRoleFlag("ROLE_USR");
loginUser.setUserDetail(userDetail);
System.out.println("before session save");
getSessionFactory().getCurrentSession().save(loginUser);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}

how to solve org.hibernate.TypeMismatchException?

I try to develop some server program using spring mvc and hibernate.
At my tables, some tables have two primray keys.
So, I want to use these keys.
Simply, I use double #Id annotations.
In the result, I got org.hibernate.TypeMismatchException.
Although I searched to solve error, I can't solve this problem...
help me please.
This is my model class.
package kr.ac.jbnu.jinggumdari.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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 org.hibernate.annotations.NaturalId;
import org.hibernate.annotations.Parameter;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="festival_info")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Interest implements Serializable{
#Id
#Column(name="interest")
private String interest;
#Id
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
public Interest(){
festivalNumber = "";
interest = "";
}
public Interest(String festivalNumber, String interest) {
this.festivalNumber = festivalNumber;
this.interest = interest;
}
public String getFestivalNumber() {
return festivalNumber;
}
public void setFestival_number(String festivalNumber) {
this.festivalNumber = festivalNumber;
}
public String getInterest() {
return interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
#Override
public String toString(){
return festivalNumber + "," + interest;
}
}
This is my servlet-context.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="favorPathExtension" value="true" />
<beans:property name="ignoreAcceptHeader" value="true" />
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="json" value="application/json" />
<beans:entry key="html" value="text/html" />
</beans:map>
</beans:property>
</beans:bean>
<context:component-scan base-package="kr.ac.jbnu.jinggumdari" />
<beans:bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/jinggumdari" />
<beans:property name="username" value="root" />
<beans:property name="password" value="mysql1234" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.Festival</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.FestivalImage</beans:value>
<beans:value>kr.ac.jbnu.jinggumdari.model.Interest</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
<beans:property name="packagesToScan" value="com.hibernate.yourpackage" />
</beans:bean>
<beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="memberService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberServiceImpl">
<beans:property name="memberDAO" ref="memberDAO"></beans:property>
</beans:bean>
<beans:bean id="festivalDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="festivalService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalServiceImpl">
<beans:property name="festivalDAO" ref="festivalDAO"></beans:property>
</beans:bean>
<beans:bean id="festivalImageDAO" class="kr.ac.jbnu.jinggumdari.DAO.FestivalImageDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="festivalImageService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.FestivalImageServiceImpl">
<beans:property name="festivalImageDAO" ref="festivalImageDAO"></beans:property>
</beans:bean>
<beans:bean id="interestDAO" class="kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="interestService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl">
<beans:property name="interestDAO" ref="interestDAO"></beans:property>
</beans:bean>
<beans:bean id="reviewDAO" class="kr.ac.jbnu.jinggumdari.DAO.ReviewDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="reviewService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.ReviewServiceImpl">
<beans:property name="reviewDAO" ref="reviewDAO"></beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
This is my DAO.
package kr.ac.jbnu.jinggumdari.DAO;
import java.util.List;
import kr.ac.jbnu.jinggumdari.model.Interest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
public class InterestDAOImpl implements InterestDAO {
private static final Logger logger = LoggerFactory
.getLogger(FestivalDAOImpl.class);
private SessionFactory sessionFactory;
private boolean isSuccess;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#Override
#Transactional
public boolean addInterest(Interest interest) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
session.persist(interest);
logger.info("Festival saved successfully, Festival Details=" + interest);
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public boolean modifyInterest(Interest interest) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
session.update(interest);
logger.info("Festival modified successfully, Festival Details="
+ interest);
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public boolean removeInterests(String festivalNumber) {
// TODO Auto-generated method stub
isSuccess = false;
Session session = this.sessionFactory.getCurrentSession();
Long numberOfInterests = getNumberOfInterests(festivalNumber, session);
for (int i = 0; i < numberOfInterests; i++) {
Interest targetInterest = (Interest) session.load(Interest.class,
festivalNumber);
if (targetInterest != null) {
session.delete(targetInterest);
}
logger.info("Interest deleted successfully, Interest details="
+ targetInterest);
}
isSuccess = true;
return isSuccess;
}
#Override
#Transactional
public List<Interest> getInterests(String festivalNumber) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
List<Interest> interestsList = session.createQuery("from Interest")
.list();
for (Interest i : interestsList) {
logger.info("Person List::" + i);
}
return interestsList;
}
#Transactional
private Long getNumberOfInterests(String festivalNUmber, Session session) {
String hql = "Select count(*) from Interest where festival_number='"
+ festivalNUmber + "'";
List list = session.createQuery(hql).list();
return (Long) list.get(0);
}
}
This is error stack.
org.hibernate.TypeMismatchException: Provided id of the wrong type for class kr.ac.jbnu.jinggumdari.model.Interest. Expected: class kr.ac.jbnu.jinggumdari.model.Interest, got class java.lang.String
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:134)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1106)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.getReference(SessionImpl.java:2564)
at org.hibernate.internal.SessionImpl.load(SessionImpl.java:981)
at kr.ac.jbnu.jinggumdari.DAO.InterestDAOImpl.removeInterests(InterestDAOImpl.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
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.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy54.removeInterests(Unknown Source)
at kr.ac.jbnu.jinggumdari.serviceImplementation.InterestServiceImpl.removeInterests(InterestServiceImpl.java:31)
at kr.ac.jbnu.jinggumdari.controller.JinggumdariController.test2(JinggumdariController.java:309)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Your problem is that you are using two #Id annotations in the same entity, you would rather use #EmbeddeId instead, so change this code:
#Id
#Column(name="interest")
private String interest;
#Id
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
To the following code:
public class Interest implements Serializable{
#EmbeddedId
private InterestId id;
//getters and setters and the rest of your code go here
}
And the InterestId class:
#Embeddable
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="interest")
private String interest;
#Column(name="festival_number", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="festival_info"))
private String festivalNumber;
// and getters and setters here
}
You can refer to this tutorial and the Documentation here for further information.
You cannot use 2 #Id annotations for a composite primary key. You have to use #EmbeddedId Check this documentation and this Stackoverflow link.

org.hibernate.hql.ast.QuerySyntaxException: UserType is not mapped [from UserType]

The exception is about table not mapping to class, however I failed to debug what went wrong.
I have checked the xml configurations. the class is UserType and the database table is called UserType as well.
UserType.java:
package com.howtodoinjava.entity;
public class UserType {
private int _userTypeID;
private String _userTypeName;
private boolean _typeIsSuperUser;
public int getUserTypeID() { return _userTypeID; }
public String getUserTypeName() {return _userTypeName; }
public boolean getTypeIsSuperUser() {return _typeIsSuperUser; }
public UserType setUserTypeID(int id) { _userTypeID = id; return this; }
public UserType setUserTypeName(String name) { _userTypeName = name; return this; }
public UserType setTypeIsSuperUser(boolean isSuperUser) { _typeIsSuperUser = isSuperUser; return this; }
}
UserTypeDAOImpl.java:
package com.howtodoinjava.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.entity.UserType;
#Repository
public class UserTypeDAOImpl implements UserTypeDAO {
#Autowired
private SessionFactory sessionFactory;
public void add(UserType ut) {
this.sessionFactory.getCurrentSession().save(ut);
}
#SuppressWarnings("unchecked")
public List<UserType> getAll() {
return this.sessionFactory.getCurrentSession().createQuery("from UserType").list();
}
public void delete(Integer id) {
UserType ut= (UserType) sessionFactory.getCurrentSession().load(
UserType.class, id);
if (null != ut) {
this.sessionFactory.getCurrentSession().delete(ut);
}
}
}
EditUserTypeController.java:
#Controller
public class EditUserTypeController{
#Autowired
private UserTypeManager userTypeManager;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String list(ModelMap map)
{
map.addAttribute("UserType", new UserType());
map.addAttribute("UserTypeList", userTypeManager.getAll());
return "editEUserTypeList";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUserType(#ModelAttribute(value="ut") UserType ut, BindingResult result)
{
userTypeManager.add(ut);
return "redirect:/";
}
#RequestMapping("/delete/{id}")
public String deleteUserType(#PathVariable("id") Integer id)
{
userTypeManager.delete(id);
return "redirect:/";
}
public void setUserTypeManager(UserTypeManager new_utm) {
this.userTypeManager = new_utm;
}
}
my UserType-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<context:component-scan base-package="com.howtodoinjava.controller" />
<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="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="UserTypeDAO" class="com.howtodoinjava.dao.UserTypeDAOImpl"></bean>
<bean id="UserTypeManager" class="com.howtodoinjava.service.UserTypeManagerImpl"> </bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="UserType.hbm.xml" />
</session-factory>
</hibernate-configuration>
UserType.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.howtodoinjava.entity.UserType" table="UserType">
<meta attribute="class-description">
user type
</meta>
<id name="_userTypeID" column="UserTypeId" type="int"> <generator class="native"/> </id>
<property name="_userTypeName" column="UserTypeName" type="string"/>
<property name="_typeIsSuperUser" column="TypeIsSuperUser" type="string"/>
</class>
</hibernate-mapping>
I appreciate any helps!
The problem is in hibernate mapping configuration:
name: should be same as class field name and
column: is the name of database table column, or the column name to be set while table creation by hibernate.
Note: The mapping file instructs Hibernate how to map the defined class to the database table.
your UserType.hbm.xml should be look like:
<hibernate-mapping>
<class name="com.howtodoinjava.entity.UserType" table="UserType">
<meta attribute="class-description">
user type
</meta>
<id name="_userTypeID" column="userTypeID" type="int">
<generator class="native"/>
</id>
<property name="_userTypeName" column="userTypeName" type="string"/>
<property name="_typeIsSuperUser" column="typeIsSuperUser" type="string"/>
</class>
</hibernate-mapping>
It turned out this is related to the HQL issue: instead of using from UserType, use from com.howtodojava.entity.UserType;
and the error message will be gone.

java persistence works with reading from database,fails to insert / update

hi guys i m new to Hibernate and JPA.
This is my VO class.
Product.java
package com.sample.myproduct.valueobject;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.sample.myproduct.constants.MyproductConstants;
#Entity
#Table(name = "product")
#NamedQuery(
name=MyproductConstants.PRODUCT_NAMED_QUERY,
query=MyproductConstants.SELECT_QUERY_PRODUCT
)
public class Product {
#Id
#Column(name="Product_id")
int productId;
#Column(name="Name")
String name;
#Column(name="Desc")
String desc;
#Column(name="Rating")
int rating;
#Column(name="stock")
int stock;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
Impl Class
package com.sample.myproduct.servicedao;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import com.sample.myproduct.constants.MyproductConstants;
import com.sample.myproduct.valueobject.Product;
#Transactional
public class ProductDAOImpl implements ProductDAO {
#PersistenceContext
private EntityManager entityManagerFactory;
public EntityManager getEntityManagerFactory() {
return entityManagerFactory;
}
public void setEntityManagerFactory(EntityManager entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
public void save(Product product){
entityManagerFactory.persist(product);
}
public Product getProductById(int id) throws DataAccessException{
return entityManagerFactory.find(Product.class,id);
}
}
}
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="JpaPersistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.sample.myproduct.servicedao.ProductDAOImpl</class>
</persistence-unit>
</persistence>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.sample.myproduct" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
p:url="jdbc:mysql://localhost/testdb" p:username="root" p:password="" />
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="com.sample.myproduct" />
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
<beans:property name="persistenceUnitName" value="entityManager" />
</beans:bean>
<beans:bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<context:spring-configured />
<context:annotation-config />
<beans:bean id="productService"
class="com.sample.myproduct.servicebo.ProductService">
</beans:bean>
<beans:bean id="productDAO" class="com.sample.myproduct.servicedao.ProductDAOImpl"></beans:bean>
</beans:beans>
I am able to read data from db but not able to insert data..its not giving any exception.when i added entityManager.flush() after persist function;.
its giving exception as no transaction is in progress
I am not able to find solution for this..
When using JpaTransactionManager, you should specify the dialect as well as below.
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="jpaDialect" ref="jpaDialect"/>
</bean>
Update:
No transaction is required to read data from database but active transaction is required to write data to database.
If you don't configure the transactionManager correctly, #Transaction annotation will be ignored silently and all your operation will run as if no transaction is available; therefore, your write operation will fail.

Categories