How to create automatic tables in spring application? - java

"HI
automatic tables are not creating in spring application and application didnt get any error."
DB:MYSQL
"dispatcher-servlet.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">
<annotation-driven />
<!-- Getting Database properties -->
<context:property-placeholder location="classpath:database.properties" />
<!-- Specifying the Resource location to load JS, CSS, Images etc -->
<resources mapping="/resources/**" location="/resources/" />
<!-- View Resolver -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/jsp/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<beans:property name="driverClassName" value="${database.driver}" />
<beans:property name="url" value="${database.url}" />
<beans:property name="username" value="${database.username}" />
<beans:property name="password" value="${database.password}" />
</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.msebbz.beans.Calendar</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
<beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
<beans:prop key="hibernate.format_sql">${hibernate.format_sql}</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl}</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<!-- Specifying base package of the Components like Controller, Service, DAO -->
<context:component-scan base-package="com.msebbz.*" />
<!-- Transaction -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="Calendar" class="com.msebbz.beans.Calendar"/>
</beans:beans>
database.properties
#Database related properties
database.driver = com.mysql.jdbc.Driver
database.url = jdbc:mysql://localhost:3306/#######
database.username = #######
database.password = #######
#Hibernate related properties
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl = update
"Bean class"
package com.msebbz.beans;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="calendar")
public class Calendar {
#Id
private String calendarId;
private String calendarName;
private String creationDate;
private String fromDate;
private String toDate;
private String status="Active";
private String calendarYear;
private String compOffExp;
private String holidays;
private String weekOff;
public String getCalendarId() {
return calendarId;
}
public void setCalendarId(String calendarId) {
this.calendarId = calendarId;
}
public String getCalendarName() {
return calendarName;
}
public void setCalendarName(String calendarName) {
this.calendarName = calendarName;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCalendarYear() {
return calendarYear;
}
public void setCalendarYear(String calendarYear) {
this.calendarYear = calendarYear;
}
public String getCompOffExp() {
return compOffExp;
}
public void setCompOffExp(String compOffExp) {
this.compOffExp = compOffExp;
}
public String getHolidays() {
return holidays;
}
public void setHolidays(String holidays) {
this.holidays = holidays;
}
public String getWeekOff() {
return weekOff;
}
public void setWeekOff(String weekOff) {
this.weekOff = weekOff;
}
}
"Thanks in advance :)"
automatic tables are not creating in spring application and application didnt get any error."
automatic tables are not creating in spring application and application didnt get any error."
automatic tables are not creating in spring application and application didnt get any error."
automatic tables are not creating in spring application and application didnt get any error."
automatic tables are not creating in spring application and application didnt get any error."
automatic tables are not creating in spring application and application didnt get any error."

Related

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion

I'm newer in java development. I want to add validators to our project. But I had a problem. Please help me!
I add
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.0.Final</version>
</dependency>
in my pom.xml .My project is a Maven Modules Project.
My MVC Config:
<bean
id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property
name="providerClass"
value="org.hibernate.validator.HibernateValidator" />
<property
name="validationMessageSource"
ref="messageSource" />
</bean>
<bean
id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:development/messages</value>
</list>
</property>
<property
name="useCodeAsDefaultMessage"
value="false" />
<property
name="defaultEncoding"
value="UTF-8" />
<property
name="cacheSeconds"
value="60" />
</bean>
And my DTO:
public class User4BlackListRequest implements Serializable {
private static final long serialVersionUID = -4886429042153823406L;
#Size(max=4,min=2,message="realName's length must be 2 ~ 4")
private String realName;
private Integer isDelete;
private UserTypeEnum userType;
public User4BlackListRequest(){}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Integer getIsDelete() {
return isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public void setUserType(UserTypeEnum userType) {
this.userType = userType;
}
public UserTypeEnum getUserType() {
return userType;
}
}
User4BlackListResponse
public class User4BlackListResponse implements Serializable {
private static final long serialVersionUID = -4175005832458864444L;
private String userId;
private String realName;
private UserTypeEnum userType;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public UserTypeEnum getUserType() {
return userType;
}
public void setUserType(UserTypeEnum userType) {
this.userType = userType;
}
}
controller
#RequestMapping(value="/getList4BlackList",method=RequestMethod.GET)
#ResponseBody
public DataResult<PageInfo<User4BlackListResponse>> getList4BlackList (#Valid User4BlackListRequest request,Errors result, PageParam pageParam,SortParam sortParam){
if(result.hasErrors()){
String msg = result.getAllErrors().get(0).getDefaultMessage();
logger.info(msg);
}
return DataResult.SuccessData(userService.getList4BlackList(request, pageParam, sortParam));
}
then I test, but log show:
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]->org.springframework.validation.BeanPropertyBindingResult["model"]->java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]->org.springframework.validation.BeanPropertyBindingResult["model"]->java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]->org.springframework.validation.BeanPropertyBindingResult["model"]->java.util.LinkedHashMap["org.springframework.validation.BindingResult.user4BlackListRequest"]-....at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:706) at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:633)
at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:536)
at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:30)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690)
applicationContext.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:task="http://www.springframework.org/schema/task"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
<mvc:annotation-driven validator="validator" />
<task:scheduled-tasks scheduler="myScheduler">
<task:scheduled ref="userScheduledManager" method="editActive" cron="0 0/15 * * * *"/>
<task:scheduled ref="invitScheduledManager" method="expireInvite" cron="0 0/60 * * * *"/>
</task:scheduled-tasks>
<task:scheduler id="myScheduler" pool-size="10"/>
<bean id="apiObjectMapper"
class="com.xxxxx.zpxt.common.convert.ApiObjectMapper">
<constructor-arg name="jsonDefaultValue" value="true"></constructor-arg>
<property name="timeZone">
<bean class="java.util.TimeZone" factory-method="getTimeZone">
<constructor-arg value="GMT+08" />
</bean>
</property>
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
</bean>
<context:component-scan base-package="com.xxxxx.zpxt">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
scope="singleton" lazy-init="true">
<property name="corePoolSize" value="4" />
<property name="maxPoolSize" value="80" />
<property name="queueCapacity" value="500" />
</bean>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean
class="com.xxxxx.zpxt.common.convert.ValueToEnumConverterFactory" />
<bean
class="com.xxxxx.zpxt.common.convert.StringToDateConverter"></bean>
</list>
</property>
</bean>
<bean id="loggerMethodInterceptor" class="com.xxxxx.zpxt.common.interceptor.LoggerMethodInterceptor"/>
<bean id="repeatSubmitMethodInterceptor" class="com.xxxxx.zpxt.common.interceptor.RepeatSubmitMethodInterceptor"/>
<bean id="kickoutMethodInterceptor" class="com.xxxxx.zpxt.common.interceptor.KickoutMethodInterceptor"/>
<bean id="cacheServiceInterceptor" class="com.xxxxx.zpxt.common.interceptor.CacheServiceInterceptor"/>
<bean
id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property
name="providerClass"
value="org.hibernate.validator.HibernateValidator" />
<property
name="validationMessageSource"
ref="messageSource" />
</bean>
<bean
id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
</list>
</property>
<property
name="useCodeAsDefaultMessage"
value="false" />
<property
name="defaultEncoding"
value="UTF-8" />
<property
name="cacheSeconds"
value="60" />
</bean>
</beans>
servlet-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<context:component-scan base-package="com.xxxxx.zpxt.controller"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:component-scan
base-package="com.xxxxx.zpxt.shiro.web.controller"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven conversion-service="conversionService">
<mvc:argument-resolvers>
<bean
class="com.xxxxx.zpxt.controller.util.CurrentUserMethodArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<aop:config>
<aop:pointcut id="webMethodPointcut"
expression="execution(* com.xxxxx.zpxt.controller.*.*.*(..)) and
#annotation(org.springframework.web.bind.annotation.RequestMapping)" />
<aop:advisor advice-ref="loggerMethodInterceptor" pointcut-ref="webMethodPointcut" order="1"/>
<aop:advisor advice-ref="kickoutMethodInterceptor" pointcut-ref="webMethodPointcut" order="2"/>
<aop:advisor advice-ref="repeatSubmitMethodInterceptor" pointcut-ref="webMethodPointcut" order="3"/>
</aop:config>
<mvc:default-servlet-handler />
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="1">
<property name="contentType" value="text/html" />
<property name="prefix" value="/" />
<property name="suffix" value="" />
</bean>
<bean id="handlerExceptionResolver"
class="com.xxxxx.zpxt.common.exception.BusinessHandlerExceptionResolver">
<constructor-arg name="objectMapper" ref="apiObjectMapper"></constructor-arg>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="20971520" />
<property name="maxInMemorySize" value="4096" />
</bean>
<import resource="classpath*:/mvc-module/*-module.xml" />
</beans>
I have no idea what's wrong. I google,but I can't find something else like this, pls help me. thank you!
According to m4gic's suggestion.I try code a demo:
controller
#RequestMapping(value="/index")
#ResponseBody
public DataResult<User> index(#Valid User request,Errors errors){
User user = new User();
DataResult<User> result = new DataResult<>();
if(errors.hasErrors()){
result.setMsg(errors.getAllErrors().get(0).getDefaultMessage());
}
result.setData(user);
return result;
}
User.java
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#NotBlank(message = "name is null!")
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
DataResult.java
public class DataResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
private int code;
private String msg;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
But It works well.NO error;Result:
{
"code": 0,
"msg": "name is null!",
"data": {
"name": null,
"age": 0
}
}
I think what you definitely can do is to try to handle validation errors in different way.
Maybe the problem is that you are trying to handle errors in a controller function having #ResponseBody that would mean that the error should be given back as json. If you would use controlleradvice or custom exception handler, that may help you out.
The other thing you can do is to create a proper spring boot project (after figuring out that using boot 1.4.0.RELEASE will create a project that will contain spring 4.3.2.RELEASE and everything else that is compatible). Then try to reproduce your error in this project (with boot-controlled compatible dependency-set). If there is no error, then you have to compare the two projects dependency tree, because very probably you are using some incompatible jars.
Since you are using Hibernate, check if you have bidirectional mapping. Those can cause infinite recursion. For example if you have parent class A and child class B, and A has list of B`s but B also have reference to its parent A. This will be major problem for serialization. Solution is to either break bidirectional mapping or implement some kind of guard to not populate field of type A in class B.

Making hibernate project with spring-rest

I am trying to make a simple spring rest project with hibernate.
I have made DAO and service layer. I have also configured beans in dispatcher-servlet and autowired in controller class with service and in service DAO session factory and transactions.
But I am continuously getting errors.
I have also uploaded a photo of error.
dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.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.xsd">
<!-- <mvc:annotation-driven /> -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!--JDBC ko properties-->
<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/student_database" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<!-- Hibernate ko SessionFactory Bean definition part -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<!-- <beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.mycompany.SpringRestMaven.bean</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:bean>
<context:component-scan base- package="com.mycompany.SpringRestMaven.controller"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
controller class:
package com.mycompany.SpringRestMaven.controller;
/* I have not included imports*/
#RestController
public class StudentController {
#Autowired
ServiceLayer studentService;
#RequestMapping(value = "/insert", method = RequestMethod.POST, headers = "Accept=application/json")
public void insert(#RequestBody Student student) {
studentService.insert(student);
}
#RequestMapping(value = "/update", method = RequestMethod.PUT, headers = "Accept=application/json")
public void update(#RequestBody Student student) {
studentService.update(student);
}
#RequestMapping(value = "/delete", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void delete(#PathVariable("id") int id) {
studentService.delete(id);
}
#RequestMapping(value = "/getAll", method = RequestMethod.GET, headers = "Accept=application/json")
public List<Student> getAll() {
List<Student> listOfStudent = studentService.getAll();
return listOfStudent;
}
#RequestMapping(value = "/searchById/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Student searchById(#PathVariable int id) {
return studentService.searchById(id);
}
}
This is my service layer implementation:
package com.mycompany.SpringRestMaven.Service;
#Service("studentService")
public class ServiceImpl implements ServiceLayer {
#Autowired StudentDAO studentDao;
#Transactional
#Override
public void insert(Student s) {
studentDao.insert(s);
}
#Transactional
#Override
public void update(Student s) {
studentDao.update(s);
}
#Transactional
#Override
public void delete(int id) {
studentDao.delete(id);
}
#Transactional
#Override
public List<Student> getAll() {
return studentDao.getAll();
}
#Transactional
#Override
public Student searchById(int id) {
return studentDao.searchById(id);
}
}
This is my DAO implementation:
package com.mycompany.SpringRestMaven.DAO;
#Repository
public class StudentDAOImpl implements StudentDAO {
#Autowired
private SessionFactory sessionFactory;
private Session session;
private Transaction trans;
#Override
public void insert(Student s) {
session = sessionFactory.openSession();
trans = session.beginTransaction();
session.save(s);
trans.commit();
session.close();
}
#Override
public void update(Student s) {
session = sessionFactory.openSession();
trans = session.beginTransaction();
session.saveOrUpdate(s);
trans.commit();
session.close();
}
#Override
public void delete(int id) {
session = sessionFactory.openSession();
trans = session.beginTransaction();
Student sObject = (Student) session.get(Student.class, id);
session.delete(sObject);
trans.commit();
session.close();
}
#Override
public List<Student> getAll() {
return session.createQuery("SELECT s FROM Student s").list();
}
#Override
public Student searchById(int id) {
return (Student) session.get(Student.class, id);
}
}
I am getting this error:
Change your configuration
<context:component-scan base- package="com.mycompany.SpringRestMaven.controller"/>
To
<context:component-scan base- package="com.mycompany.SpringRestMaven"/>
Then Spring scans all your classes beneath the SpringRestMaven package and creates beans from the annotated classes.
In your current configuration Spring only scans and creates beans from beneath the .controller package. Your ServiceLayer isn't in this package and therefore Spring couldn't find the class, doesn't create a bean and could not autowire the field.

org.hibernate.MappingException: Unknown entity hibernate4 spring4

I am getting the exception
org.hibernate.MappingException: Unknown entity com.pro.entity.User
I have seen similar posts but almost all of them provides solution to change #Entity annotation to javax.persistence instead of hibernate. Which in my case wasn't useful as I am using correct annotation since the beginning. Here's the code for entity class dao and servlet context.
package com.pro.entity;
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="user")
public class User {
private static final long serialVersionUID = 1L;
#Id
#Column(name="userid")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
#Column(name="password")
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Dao class code:
public User getUser(String userid)
{
Session session = this.sessionFactory.getCurrentSession();
User user = (User)session.load(User.class, userid);
return user;
}
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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/orm
http://www.springframework.org/schema/orm/spring-orm-4.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd">
<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 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/pro?useSSL=false" />
<beans:property name="username" value="user" />
<beans:property name="password" value="password" />
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
<beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory"></beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager"/><tx:annotation-driven/>
<beans:bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></beans:bean>
<context:component-scan base-package="com.pro.controller" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans:beans>
chnage <context:component-scan base-package="com.pro.controller" />
to <context:component-scan base-package="com.pro" />
in context.xml
it should work then
Thank you guys. I got the solution.... just needed to add following in my context.xml file
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.pro.User</beans:value>
</beans:list>
</beans:property>

Cannot Autowire repository service Spring JPA

I am trying to use a User repository in my code, but intellij is giving me the error.
interface is not allowed for non abstract beans
I have the following setup.
#Entity
public class User {
#Id
private long id;
private String firstName;
private String lastName;
private String profileUrl;
private String email;
private String location;
protected User(){};
public User(String first, String last, String profileUrl, String email, String location){
this.firstName = first;
this.lastName = last;
this.profileUrl = profileUrl;
this.email = email;
this.location = location;
}
public User(Person person){
this.firstName = person.getName().getGivenName();
this.lastName = person.getName().getFamilyName();
this.profileUrl = person.getImage().getUrl();
this.email = person.getEmails().get(0).getValue();
this.location = person.getCurrentLocation();
}
}
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByProfileId(long id);
}
I have tried to annotate this with #Service and #Repository but to no avail.
#Component
public class UserRepositoryImpl {
#Autowired
private UserRepository userRepository;
public void doSomething() {
List<User> byProfileId = userRepository.findByProfileId(100);
}
}
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"
xmlns:rep="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<rep:repositories base-package="com.planit.persistence.*"/>
<bean id="userRepository" class="com.planit.persistence.registration.UserRepository"/>
<!-- DB CONNECTION-->
<bean class="java.net.URI" id="dbUrl">
<constructor-arg value="#{T(com.ProjectUtils).getDBUrl()}"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url"
value="#{ 'jdbc:postgresql://' + #dbUrl.getHost() + ':' + #dbUrl.getPort() + #dbUrl.getPath() }"/>
<property name="username" value="#{ #dbUrl.getUserInfo().split(':')[0] }"/>
<property name="password" value="#{ #dbUrl.getUserInfo().split(':')[1] }"/>
</bean>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.planit.persistence"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="POSTGRESQL"/>
</bean>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
Error occurs in the line of my spring.xml where I am defining my userRepository bean.
Thanks in advance.
#Repository is missing, try adding above the interface of the repo and remove bean declaration that is not allowed in Spring.
I believe you just need to remove this line:
<bean id="userRepository" class="com.planit.persistence.registration.UserRepository"/>
See the SpringData docs here.

Hibernate does not save data into DB?

I have a form where i input details, but when i click on save it does not get saved in the database... though the table does get created.
My Contact POJO
package your.intermedix.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String email;
private String lastname;
private String designation;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="DESIGNATION")
public String getDesignation(){
return designation;
}
public void setDesignation(String designation){
this.designation = designation;
}
#Column(name="EMAIL")
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
#Column(name="LASTNAME")
public String getLastname(){
return lastname;
}
public void setLastname(String lastname){
this.lastname= lastname;
}
#Column(name="FIRSTNAME")
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String toString()
{
return "designation = '" + designation + "',email='"+ email +"', lastname='"+ lastname +"', name = '" + name + "'";
}
}
My Application-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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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.0.xsd">
<!-- Turn on AspectJ #Configurable support -->
<context:spring-configured />
<context:property-placeholder location="classpath*:*.properties" />
<context:component-scan base-package="your.intermedix"/>
<context:annotation-config/>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- a PlatformTransactionManager is still required -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- (this dependency is defined somewhere else) -->
<property name="dataSource" ref="myDataSource"/>
</bean>
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>your.intermedix.domain.Contact</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<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://127.0.0.1:3306/spring"/>
<property name="username" value="monty"/>
<property name="password" value="indian"/>
</bean>
</beans>
I am not getting any sort of error.... in the console.
Updated code..
package your.intermedix.services;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import your.intermedix.domain.Contact;
import your.intermedix.services.IContact;
#Service
public class ContactSerImpl implements IContact {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Transactional
public void saveContact(Contact contact) {
System.out.println("Hello Guru contact");
System.out.println(contact);
hibernateTemplate.saveOrUpdate(contact);
}
public void hello() {
System.out.println("Hello Guru");
}
}
My Service class where i the print statements work
You need a running transaction. Spring transaction management is the way to go if using HibernateTemplate. Read the documentation. It's too long to include in an answer, but here is in short:
you need to define a transaction manager as a spring bean
you need <tx:annotation-driven />
you need to annotate your transactional methods with #Transactional
I don't know the Spring-Hibernate framework, but often when data is not written it menas it is not flushed to the databackend. What gives you
System.err.println(hibernateTemplate.getFlushMode());

Categories

Resources