java.lang.IllegalStateException: no matching editors or conversion strategy found - java

So i'm building a spring 3.2.3.RELEASE / hibernate 4.0.1.FINAL application and i got the following exception
[2017-03-22 09:29:47,860] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory [localhost-startStop-1] Ignoring bean creation exception on FactoryBean type check: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginService' defined in URL [jar:file:/D:/Programmes/apache-tomcat-7.0.33/webapps/perWeb/WEB-INF/lib/perService-2.0.jar!/applicationContext-transactional-service.xml]: Cannot resolve reference to bean 'loginServiceImpl' while setting bean property 'target'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginServiceImpl' defined in URL [jar:file:/D:/Programmes/apache-tomcat-7.0.33/webapps/perWeb/WEB-INF/lib/perService-2.0.jar!/applicationContext-simple-service.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'ma.dao.impl.GenericDAO' to required type 'ma.dao.IGenericDAO' for property 'dao'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [ma.dao.impl.GenericDAO] to required type [ma.dao.IGenericDAO] for property 'dao': no matching editors or conversion strategy found
Here is my beans: loginservice
<bean id="loginService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManagerPER" />
</property>
<property name="target">
<ref bean="loginServiceImpl" />
</property>
<property name="transactionAttributes">
<props>
<prop key="loadUserByUsername">
PROPAGATION_REQUIRED,-Exception
</prop>
</props>
</property>
</bean>
loginServiceImpl
<bean id="loginServiceImpl"
class="ma.service.login.LoginService">
<property name="dao">
<ref bean="userDAO" />
</property>
</bean>
UserDAO
<bean id="userDAO"
class="ma.dao.impl.GenericDAO">
<constructor-arg>
<value>
ma.dao.mappings.Utilisateur
</value>
</constructor-arg>
<property name="sessionFactory">
<ref bean="sessionFactoryPER" />
</property>
</bean>
Utilisateur.Java
#Entity
#NamedQueries(
{
#NamedQuery(name="findUtilisateurByName",
query = "select user from Utilisateur user where user.login=:userName"
)
}
)
public class Utilisateur implements java.io.Serializable {
private static final long serialVersionUID = 7214071893495381842L;
private Integer id;
private Profil profil;
private String nom;
private String prenom;
private String login;
private String passwd;
public Utilisateur() {
}
public Utilisateur(Integer id) {
this.id = id;
}
#Id #GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne
public Profil getProfil() {
return profil;
}
public void setProfil(Profil profil) {
this.profil = profil;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
Am i missing somthing ?
If you need more informations please let me know

It seems like your GenericDao not able to convert to IGenericDao and for that, there might be several reasons like is your GenericDao implements the IGenericDao, etc.
Also the following link might be useful if you are implementing GenericDao pattern:
https://www.codeproject.com/Articles/251166/The-Generic-DAO-pattern-in-Java-with-Spring-and

Related

Error creating bean with name 'homeController': Injection of autowired dependencies failed

I am trying to create e-commerce in spring. After including "Hibernate" and "H2" database in my project, I get the error. The error is given below. I am trying very much but not found any solution.
Error:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'homeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.home.dao.ProductDao
com.home.controller.homeController.productDao; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'productDaoImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private org.hibernate.SessionFactory
com.home.dao.impl.ProductDaoImpl.sessionFactory; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in ServletContext
resource [/WEB-INF/applicationContext.xml]: Invocation of init method
failed; nested exception is
org.hibernate.exception.GenericJDBCException: Unable to open JDBC
Connection for DDL execution
applicationContext.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:~/test" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.home</value>
</list>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
home-servlet.xml
<context:component-scan base-package="com.home">
<context:include-filter type="aspectj" expression="com.home.*" />
</context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/resources/**"
location="/WEB-INF/resources/" cache-period="31556926" />
<tx:annotation-driven />
web.xml
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/home-servlet.xml,
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
homeController.java
#Controller
#Configuration
public class homeController {
#Autowired
private ProductDao productDao;
#RequestMapping("/")
public String home() {
return "views/home";
}
#RequestMapping("/productList")
public String getProducts(Model model) {
List<Product> products = productDao.getAllProducts();
model.addAttribute("products", products);
return "views/productList";
}
#RequestMapping("/productList/viewProduct/{productId}")
public String viewProduct(#PathVariable String productId, Model model) throws IOException{
Product product = productDao.getProductById(productId);
model.addAttribute(product);
return "views/viewProduct";
}
}
ProductDaoImpl.java
#Repository
#Transactional
public class ProductDaoImpl implements ProductDao {
#Autowired
private SessionFactory sessionFactory;
public void addProduct(Product product) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(product);
session.flush();
}
public Product getProductById(String id) {
Session session = sessionFactory.getCurrentSession();
Product product = (Product) session.get(Product.class, id);
session.flush();
return product;
}
public List<Product> getAllProducts() {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Product");
List<Product> products = query.list();
session.flush();
return products;
}
public void deleteProduct (String id) {
Session session = sessionFactory.getCurrentSession();
session.delete(getProductById(id));
session.flush();
}
}
Product.java Code:
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String productId;
private String productName;
private String productCategory;
private String productDescription;
private double productPrice;
private String productCondition;
private String productStatus;
private int unitInStock;
private String productManufacturer;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
public String getProductCondition() {
return productCondition;
}
public void setProductCondition(String productCondition) {
this.productCondition = productCondition;
}
public String getProductStatus() {
return productStatus;
}
public void setProductStatus(String productStatus) {
this.productStatus = productStatus;
}
public int getUnitInStock() {
return unitInStock;
}
public void setUnitInStock(int unitInStock) {
this.unitInStock = unitInStock;
}
public String getProductManufacturer() {
return productManufacturer;
}
public void setProductManufacturer(String productManufacturer) {
this.productManufacturer = productManufacturer;
}
}
ProductDao.java Code:
public interface ProductDao {
void addProduct(Product product);
Product getProductById(String id);
List<Product> getAllProducts();
void deleteProduct(String id);
}
Project Structure or Directory Image:
Project Structure or Directory at my Eclipse Oxygen IDE
Finally, I have found my own problems when I use IntelliJ IDEA IDE. Problems are given bellow:
My problem have occurred at pom.xml file. Here, I have used hibernate-core latest version (5.4.0.Final) dependency which is not support import org.hibernate.Query; package and also not support Query query = session.createQuery("from Product"); and Product product = (Product) session.get(Product.class, id); codes at ProductDaoImpl.java class.
I have also used latest version of spring-webmvc, spring-core and spring-orm dependency at pom.xml file. For that it occurs version conflict.
Solution:
Forget Eclipse and avoid it. Please use IntelliJ IDEA. This is very user friendly IDE for Java Spring MVC framework and also show what wrong you do.
Create new project and used hibernate-core 4.0.1.Final version dependency at pom.xml file and also used 4.2.8.RELEASE version of own, spring-core and spring-orm dependencies.
Remove import org.hibernate.Query.query; package from ProductDaoImpl.java class and put import org.hibernate.Query package.
Thank you :)
ProductDao is not a bean..That's why. Repository, controller, service are all of type of bean. Make sure this is which type of bean.....Thank you.

HibernateException: saveOrUpdate is not valid without active transaction

Perhaps this question has been asked severally but am not able to find a solution to this. I am new to Spring and trying to working on a simple project to integrate Spring with Hibernate 4 using annotations. Whenever i click the user form to save to DB it throws this exception:
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction
What am I doing wrong? My code is below:
User.java
#Entity
#Table(name="SpringUsers")
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userId")
private int id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UsDAOImpl.java
#Repository
public class UserDAOImpl implements UserDAO{
#Autowired
private SessionFactory sessionFactory;
public UserDAOImpl(){}
public UserDAOImpl( SessionFactory sessionFactory){
this.sessionFactory= sessionFactory;
}
#Override
#Transactional
public List<User> list() {
List<User> listUser = sessionFactory.getCurrentSession()
.createCriteria(User.class).list();
return listUser;
}
#Override
#Transactional
public void saveOrUpdate(User user) {
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
#Override
#Transactional
public void delete(int id) {
User userToDelete = new User();
userToDelete.setId(id);
sessionFactory.getCurrentSession().delete(userToDelete);
}
#Override
#Transactional
public User get(int i) {
String hql = "from User where id=" + i;
Query query = sessionFactory.getCurrentSession().createQuery(hql);
List<User> listUser = (List<User>) query.list();
if (listUser != null && !listUser.isEmpty()) {
return listUser.get(0);
}
return null;
}
}
user-servlet.xml
<context:component-scan base-package="com.myspringapp.controller"/>
<mvc:annotation-driven/>
<context:annotation-config />
<!-- <tx:annotation-driven />-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:XE"/>
<property name="username" value="system"/>
<property name="password" value="henry"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.myspringapp.model.User</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<constructor-arg ref="sessionFactory"/>
</bean>
<bean id="userDao" class="com.myspringapp.dao.UserDAOImpl">
<constructor-arg ref="sessionFactory"/>
</bean>
<!-- <tx:annotation-driven transaction-manager="transactionManager"/>-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
Uncomment this line and it should work:
<tx:annotation-driven />

Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException:

I was trying to get data from a MySQL database using the Spring utility ResultSetExtractor, but I got the following exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'edao' defined in class path resource [applicationContext2.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'jdbcTemplate' of bean class [org.resultset.EmployeeDao]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1067)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at org.resultset.Test.main(Test.java:11)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'jdbcTemplate' of bean class [org.resultset.EmployeeDao]: Bean property 'jdbcTemplate' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1012)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:857)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1341)
... 13 more
Employee.java
public class Employee {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
public Employee()
{
}
}
EmployeeDao.java
public class EmployeeDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){
#Override
public List<Employee> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()){
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
}
Test.java
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployees();
for(Employee e:list)
System.out.println(e);
}
}
and applicationContext2.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="org.resultset.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
These all are java files I am using. It says the setter's return type doesn't match with the getter's, but I checked it, and it is correct there.
The problem is in
<bean id="edao" class="org.resultset.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
Try changing the name="jdbcTemplate" to name="template". Since you have given name as jdbcTemplate spring will search for a setter method with name setJdbcTemplate() in EmployeeDao class, but the acutal method you have is setTemplate()
Controller extends MethodNameResolver
public final void setMethodNameResolver(
MethodNameResolver methodNameResolver) {
this.methodNameResolver = methodNameResolver;
}
public final MethodNameResolver getMethodNameResolver() {
return this.methodNameResolver;
}
remove spring Annotation like #controller #AutoWired

hibernate entity to json

i use Hibernate 4 and Spring 3.
i have two entity.
Book entity
#Entity
#Table(name = "book")
public class Book implements Serializable {
public Book() {
}
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne()
#JoinColumn( name = "author_id" )
private Author author;
private String name;
private int pages;
#Version
#Column( name = "VERSION")
private int version;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
}
and Author entity
#Entity
#Table(name = "author")
public class Author implements Serializable {
public Author() {
}
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY)
private int id;
private String name;
#OneToMany( mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Book> books = new HashSet<Book>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public void addBook(Book book) {
book.setAuthor(this);
getBooks().add(book);
}
public void removeBook(Book book) {
getBooks().remove(book);
}
}
and JSON depend in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.1.2</version>
</dependency>
My Root-context is here -
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config/>
<context:component-scan base-package="org.jar.libs.dao" />
<context:component-scan base-package="org.jar.libs.service" />
<tx:annotation-driven transaction-manager="transactionManager" />
<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/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/hibernate"
p:username="root" p:password="root" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>org.jar.libs.domain.Book</value>
<value>org.jar.libs.domain.Author</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">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
...servlet-context.xml
<!-- 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="org.jar.libs.controller" />
Controller.
#Controller
#RequestMapping (value = "books/rest")
public class BookController {
#Autowired
private BookService bookService;
// logger
private static final Logger logger = LoggerFactory.getLogger(BookController.class);
#SuppressWarnings("unchecked")
#RequestMapping( method = RequestMethod.GET )
public #ResponseBody List<Book> getBook() {
List<Book> res = bookService.findAll();
return res;
}
}
findAll in my DAO :
public List<Book> findAll() {
Session session = sessionFactory.getCurrentSession();
List<Book> result = (List<Book>) session.createQuery("select c from Book c").list();
return result;
}
in debug i see that method return 2 records, but Spring can not convert result to JSON and return 406 HTTP error. What's wrong?
I attach image what i see in debug. - http://tinypic.com/view.php?pic=35kvi9i&s=6
Generally, when you call getter methods of entity classes(which returns relation object) out of transaction, then you get LazyInitializationExceptions.
That's what might be happening in your case if you are converting entity class objects(retrieved from query) to json out of transaction.
I had same issue, I converted my entity object retrieved by hibernate to json in controller. As controller was out of transaction(Transaction at service layer), while converting to json, getter methods of entity class objects are called and I got LazyInitializationException. Which obstructed object conversion to json, and response was not returned.
My solution, Try this :
#SuppressWarnings("unchecked")
#RequestMapping( method = RequestMethod.GET )
public #ResponseBody List<Book> getBook() {
List<Book> res = bookService.findAll();
for(Book book : res) {
book.getAuthor().setBooks(null);
}
return res;
}
As others have suggested,
I would really not advise you to try to JSON serialize (or actually perform any serialization) of hibernate entities.
You must remember that the fetched entities are actually "proxified" objects (Hibernate uses ASM, CGLIB and other "dynamic proxiy" frameworks).
As a result for example, collections get replaced with [PersistenceBags] which may be initialized "lazily" , and cause you hibernate exceptions 1.
But the problems do not stop there, you may see issues when trying to serialize an Hibernate custom type
I know this might sound you like writing "boillerplate" code but you might end up coding DTOs - data transfer objects which will take the entity returned from your DAL, and transform them to an object that can be serialized.
You can use a framework like dozer in order to ease development of serialization between an entity to a DTO.
Try using these two Jackson artifacts instead
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.9</version>
</dependency>
Also on your controller try by changing it to -
#SuppressWarnings("unchecked")
#RequestMapping( method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )
public #ResponseBody List<Book> getBook() {
Lastly, make sure your view is making a json request.

Java, Hibernate,Spring

I have 2 entities User and Status. I can load users list and can see its sql(log) in console
(select this_.id as id0_0_,
this_.cl_point_id as cl2_0_0_,
this_.date_ll as date3_0_0_,
this_.date_reg as date4_0_0_,
this_.name as name0_0_,
this_.passw_salt as passw6_0_0_,
this_.status_id as status7_0_0_,
this_.passw as passw0_0_, this_.login
as login0_0_ from users this_)
.
But when I load Status the list is empty and there is no sql(log) in console. I can't find where is the problem?
User.java
package tj.eskhata.pos.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="users")
public class User implements DomainObject {
#Id
private Long id;
#Column(name="name")
private String fullname;
#Column(name="cl_point_id")
private Long clPointId;
#Column(name="login")
private String wiaUsername;
#Column(name="passw")
private String wiaPassword;
#Column(name="status_id")
private Long statusId;
#Column(name="date_reg")
private Date dateReg;
#Column(name="date_ll")
private Date dateLl;
#Column(name="passw_salt")
private String passwSalt;
public User() {
}
public User(String username, String password, String fullname,
boolean isAdmin) {
this.id=Long.valueOf(1);
this.wiaUsername = username;
this.wiaPassword = password;
this.fullname = fullname;
}
public String getFullname() {
return fullname;
}
public String getWiaPassword() {
return wiaPassword;
}
public String getWiaUsername() {
return wiaUsername;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public void setWiaPassword(String password) {
this.wiaPassword = password;
}
public void setWiaUsername(String username) {
this.wiaUsername = username;
}
public Long getId() {
return id;
}
public Long getClPointId() {
return clPointId;
}
public Long getStatusId() {
return statusId;
}
public Date getDateReg() {
return dateReg;
}
public Date getDateLl() {
return dateReg;
}
public String getPasswSalt() {
return passwSalt;
}
public void getClPointId(Long clPointId_) {
this.clPointId=clPointId_;
}
public void setStatusId(Long statusId_) {
this.statusId=statusId_;
}
public void setDateReg(Date dateReg_) {
this.dateReg=dateReg_;
}
public void setDateLl(Date dateLl_) {
this.dateLl=dateLl_;
}
public void setPasswSalt(String passwSalt_) {
this.passwSalt=passwSalt_;
}
public boolean isAdmin() {
return false;
}
}
Status.java
package tj.eskhata.pos.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="status")
public class Status implements DomainObject {
public Status() {
}
public Status(Long id) {
this.id = id;
}
public Status(Long id, String code, String name, String fullName,
String color) {
this.id = id;
this.code = code;
this.name = name;
this.fullName = fullName;
this.color = color;
}
#Id
private Long id;
public void setId( Long id_) {
this.id=id_;
}
public Long getId() {
return this.id;
}
#Column(name = "code")
private String code;
public void setCode( String code_) {
this.code=code_;
}
public String getCode() {
return this.code;
}
#Column(name = "name")
private String name;
public void setName( String name_) {
this.name=name_;
}
public String getName() {
return this.name;
}
#Column(name = "full_name")
private String fullName;
public void setFullName( String fullName_) {
this.name=fullName_;
}
public String getFullName() {
return this.fullName;
}
#Column(name = "color")
private String color;
public void setColor( String color_) {
this.color=color_;
}
public String getColor() {
return this.color;
}
}
*
UserDaoImpl.java:
package tj.eskhata.pos.dao.hibernate;
import tj.eskhata.pos.dao.UserDao;
import tj.eskhata.pos.domain.User;
public class UserDaoImpl extends AbstractHibernateDaoImpl<User>
implements UserDao {
public UserDaoImpl() {
super(User.class);
}
}
StatusDaoImpl.java:
package tj.eskhata.pos.dao.hibernate;
import tj.eskhata.pos.dao.StatusDao;
import tj.eskhata.pos.domain.Status;
public class StatusDaoImpl extends AbstractHibernateDaoImpl<Status>
implements StatusDao {
public StatusDaoImpl() {
super(Status.class);
}
}
UserDao.java:
package tj.eskhata.pos.dao;
import tj.eskhata.pos.domain.User;
public interface UserDao extends Dao<User> {
}
StatusDao.java:
package tj.eskhata.pos.dao;
import tj.eskhata.pos.domain.Status;
public interface StatusDao extends Dao<Status> {
}
AbstractHibernateDaoImpl.java:
package tj.eskhata.pos.dao.hibernate;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import tj.eskhata.pos.dao.Dao;
import tj.eskhata.pos.domain.DomainObject;
public abstract class AbstractHibernateDaoImpl<T extends DomainObject>
implements Dao<T> {
private Class<T> domainClass;
private SessionFactory sf;
public AbstractHibernateDaoImpl(Class<T> domainClass) {
this.domainClass = domainClass;
}
public SessionFactory getSessionFactory() {
return sf;
}
public void setSessionFactory(SessionFactory sf) {
this.sf = sf;
}
public void delete(T object) {
getSession().delete(object);
}
#SuppressWarnings("unchecked")
public T load(long id) {
return (T) getSession().get(domainClass, id);
}
public void save(T object) {
getSession().saveOrUpdate(object);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
Criteria criteria = getSession().createCriteria(domainClass);
List<T> r=(List<T>) criteria.list();
return r;
}
public int countAll() {
Criteria criteria = getSession().createCriteria(domainClass);
criteria.setProjection(Projections.rowCount());
return (Integer) criteria.uniqueResult();
}
public Session getSession() {
// presumes a current session, which we have through the
// OpenSessionInViewFilter; doesn't work without that
return sf.getCurrentSession();
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jndi="http://www.springframework.org/schema/jndi"
xmlns:util="http://www.springframework.org/schema/util"
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-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/jndi
http://www.springframework.org/schema/jndi/spring-jndi.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:application.properties</value>
</property>
<property name="systemPropertiesModeName">
<value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="minPoolSize">
<value>${c3p0.minPoolSize}</value>
</property>
<property name="maxPoolSize">
<value>${c3p0.maxPoolSize}</value>
</property>
<property name="checkoutTimeout">
<value>20000</value>
</property>
<property name="maxIdleTime">
<value>${c3p0.maxIdleTime}</value>
</property>
<property name="idleConnectionTestPeriod">
<value>${c3p0.idleConnectionTestPeriod}</value>
</property>
<property name="automaticTestTable">
<value>${c3p0.automaticTestTable}</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>tj.eskhata.pos.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<bean id="wicketApplication"
class="tj.eskhata.pos.PosApplication">
</bean>
<bean id="UserDao"
class="tj.eskhata.pos.dao.hibernate.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="CountryDao"
class="tj.eskhata.pos.dao.hibernate.CountryDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="StatusDao"
class="tj.eskhata.pos.dao.hibernate.StatusDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="GenericDao"
class="tj.eskhata.pos.dao.hibernate.GenericDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="DiscountsService" class="tj.eskhata.pos.services.DiscountsServiceImpl">
<property name="userDao" ref="UserDao" />
<property name="countryDao" ref="CountryDao" />
<property name="statusDao" ref="StatusDao" />
<property name="genericDao" ref="GenericDao" />
</bean>
</beans>
DiscountService:
package tj.eskhata.pos.services;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import tj.eskhata.pos.domain.Country;
import tj.eskhata.pos.domain.Status;
import tj.eskhata.pos.domain.User;
public interface DiscountsService {
<T> T load(Class<T> type, long id);
List<User> findAllUsers();
void saveUser(User user);
void deleteUser(User user);
List<Country> findAllCountries();
void saveCountry(Country country);
void deleteCountry(Country country);
List<Status> findAllStatuses();
void saveStatus(Status status);
void deleteStatus(Status status);
}
package tj.eskhata.pos.services;
import java.util.List;
import tj.eskhata.pos.dao.CountryDao;
import tj.eskhata.pos.dao.GenericDao;
import tj.eskhata.pos.dao.StatusDao;
import tj.eskhata.pos.dao.UserDao;
import tj.eskhata.pos.domain.Country;
import tj.eskhata.pos.domain.Status;
import tj.eskhata.pos.domain.User;
public class DiscountsServiceImpl implements DiscountsService {
private UserDao userDao;
private CountryDao countryDao;
private StatusDao statusDao;
private GenericDao genericDao;
public DiscountsServiceImpl() {
}
public <T> T load(Class<T> type, long id) {
return genericDao.load(type, id);
}
public List<User> findAllUsers() {
return userDao.findAll();
}
public void saveUser(User user) {
userDao.save(user);
}
public void deleteUser(User user) {
userDao.delete(user);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public List<Country> findAllCountries() {
return countryDao.findAll();
}
public void saveCountry(Country country) {
countryDao.save(country);
}
public void deleteCountry(Country country) {
countryDao.delete(country);
}
public CountryDao getCountryDao() {
return countryDao;
}
public void setCountryDao(CountryDao countryDao) {
this.countryDao = countryDao;
}
public List<Status> findAllStatuses() {
return statusDao.findAll();
}
public void saveStatus(Status status) {
statusDao.save(status);
}
public void deleteStatus(Status status) {
statusDao.delete(status);
}
public StatusDao getStatusDao() {
return statusDao;
}
public void setStatusDao(StatusDao statusDao) {
this.statusDao = statusDao;
}
public GenericDao getGenericDao() {
return genericDao;
}
public void setGenericDao(GenericDao genericDao) {
this.genericDao = genericDao;
}
}
The Status entity looks fine (it has an #Entity annotation, it has a default no-arg constructor, it has an #Id), I can't spot anything obvious.
So I would:
double check the startup logs to check for any complaint.
use the Hibernate Console (if you are using Eclipse) or any equivalent to load the Status using raw HQL or Criteria.
write a unit test anyway.
Oh, by the way, this is unrelated but you shouldn't have such things in your User entity:
#Column(name="status_id")
private Long statusId;
These Long look like foreign keys. When using an ORM, you should have objects and associations between objects, not ids. Something like this:
#ManyToOne
private Status status;
Same remark for clPointId.
You are IMHO thinking "too relational" and "not enough object". I might be wrong but having foreign key attributes in an entity is a strong hint.
I have changed #Column(name="status_id") private Long statusId; to #ManyToOne private Status status; Now I receiving the ERROR: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: #OneToOne or #ManyToOne on tj.eskhata.pos.domain.User.status references an unknown entity: tj.eskhata.pos.domain.Status
This message clearly shows that something goes wrong with Status that isn't recognized as an Entity (and thus can't be referenced in an association, preventing the session factory from being instantiated). This is usually due to a configuration or mapping problem. So:
Do you declare entities somewhere (in hibernate.cfg.xml or in persistence.xml)? If yes, did you declare Status? If you are using classpath scanning, is Status scanned?
Double-check the mapping, check that the column names really exist (it's unclear if you are using an existing physical model).
Activate logging (Spring Logging, Hibernate Logging), this is helpful during development and will help to find the problem.

Categories

Resources