Spring Web App - Cannot run application after adding annotations of the database - java

I'm trying to connect a web app (using Spring MVC and Eclipse Java EE IDE) to a database (using MySQL).
I've configured the connection (at uni we are using Hibernate) like this (Location: Java resources > src/main/resources):
<?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"
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-4.2.xsd
http ://www.springframework.org/schema/context
http ://www.springframework.org/schema/context/spring-context-4.2.xsd
http ://www.springframework.org/schema/mvc
http ://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http ://www.springframework.org/schema/tx
http ://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- Properties -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.validator.apply_to_ddl">false</prop>
<prop key="hibernate.validator.autoregister_listeners">false</prop>
<!--<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>-->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<!-- Mappings -->
<property name="packagesToScan">
<list>
<value>ar.edu.grupoesfera.cursospring.model</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:// localhost:(port)/ my_database" />
<property name="username" value="root" />
<property name="password" value="root" />
<!-- <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:db_aplicacion" />
<property name="username" value="sa" />
<property name="password" value="" /> -->
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
(The commented parts are there because at first we were working in memory, but now we have to connect to the database).
I did the same for test-hibernateContext.xml in src/test/resources.
This is the pom.xml:
<project xmlns="http : / /maven.apache. org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http : / / maven.apache. org/POM/4.0.0 http ://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Project</groupId>
<artifactId>Project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>2.4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.6.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.19.0-GA</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.6</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
</project>
When I change all that configuration, the project runs perfectly fine... but after I add annotations in one of the classes of the project (Product), the app stops running.
Here is the Product.class:
package ar.edu.grupoesfera.cursospring.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.springframework.web.multipart.MultipartFile;
#Entity
#Table (name = "Product")
public class Product implements Comparable<Product>{
#Id
#Column (name = "Id_Product")
private Integer id;
#Column (name = "Nom_Product")
private String nameProduct;
#Column (name = "Desc_Product")
private String description;
#OneToOne
#JoinColumn(name = "idColor")
private Color color;
#OneToOne
#JoinColumn(name = "idSize")
private Size size;
#Column (name = "Price_Product")
private Float price;
#OneToOne
#JoinColumn(name = "idCategory")
private Category category;
#Column (name = "Img_Product")
private MultipartFile imgproduct;
#Column (name = "Name_Img_Product")
private String nameimg;
#Column (name = "New_Product")
private String newP;
public Integer getId() {
return id;
}
public Integer setId(Integer id) {
return this.id = id;
}
public String getNameProduct() {
return NameProduct;
}
public void setNameProduct(String nameProduct) {
this.nameProducto = nameProduct;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Size getSize() {
return size;
}
public void setTalle(Talle talle) {
this.talle = talle;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public MultipartFile getImgproduct() {
return imgproduct;
}
public void setImgproduct(MultipartFile imgproduct) {
this.imgproduct = imgproduct;
}
public String getNameimg() {
return nameimg;
}
public void setNameimg(String nameimg) {
this.nameimg = nameimg;
}
public String getNew() {
return new;
}
public void setNewP(String newP) {
this.newP = newP;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
#Override
public int compareTo(Product o) {
return this.id.compareTo(o.id);
}
}
Any idea if just adding these annotations is what may be causing that I can't run the app? (it gives error 404) I mean.. there has to be some way, because I obviously need them to continue with the database, but I've been researching and I have no idea what's going on.
Note: I still don't have anything in dao package.
Edit: This is the controller for that particular class (I have many) and that part of the project:
package ar.edu.grupoesfera.cursospring.controladores;
import javax.inject.Inject;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import ar.edu.grupoesfera.cursospring.modelo.Categoria;
import ar.edu.grupoesfera.cursospring.modelo.ColeccionCategoria;
import ar.edu.grupoesfera.cursospring.modelo.ColeccionColor;
//import ar.edu.grupoesfera.cursospring.modelo.ColeccionProducto;
import ar.edu.grupoesfera.cursospring.modelo.ColeccionTalle;
import ar.edu.grupoesfera.cursospring.modelo.Color;
import ar.edu.grupoesfera.cursospring.modelo.Producto;
//import ar.edu.grupoesfera.cursospring.modelo.Stock;
import ar.edu.grupoesfera.cursospring.modelo.Talle;
import ar.edu.grupoesfera.cursospring.modelo.ValidadorProducto;
import ar.edu.grupoesfera.cursospring.servicios.ProductoServicio;
import ar.edu.grupoesfera.cursospring.servicios.StockServicio;
#RestController
#MultipartConfig
public class ProductController extends HttpServlet{
private static final long serialVersionUID = 1L;
#Inject
private ProductService productService;
private StockService stockService;
//New product
#RequestMapping (value = "/newProductForm")
public ModelAndView newProductForm(#ModelAttribute("product")Product product){
CategoryCollection categorias = ColeccionCategoria.getInstance();
ColorCollection colores = ColeccionColor.getInstance();
SizeCollection talles = ColeccionTalle.getInstance();
ModelMap model = new ModelMap();
modelo.put("categorias", categorias.listCategory());
modelo.put("colores", colores.listColor());
modelo.put("talles", talles.listSize());
return new ModelAndView ("newProductForm", model);
}
#RequestMapping (value = "/newProductFormConfirm")
public ModelAndView newProductFormConfirm (#ModelAttribute("product")Product product, BindingResult result){
String info;
CategoryCollection categorias = ColeccionCategoria.getInstance();
ColorCollection colores = ColeccionColor.getInstance();
SizeCollection talles = ColeccionTalle.getInstance();
ModelMap model = new ModelMap();
modelo.put("categorias", categorias.listCategory());
modelo.put("colores", colores.listColor());
modelo.put("talles", talles.listSize());
ValidateProduct validateproduct = new ValidateProduct();
validateproduct.validate(product, result);
if (result.hasErrors()) {
return new ModelAndView ("newProductFormConfirm", model);
}
try{
productService.newProduct(product);
info="Success";
}catch(Exception e){
productService.saveExistingProduct(product);
info= e.getMessage();
}
String imgPath ="images/products"+"/"+product.getImgproduct().getOriginalFilename();
modelo.put("info", info);
modelo.put("imdPath", imgPath);
return new ModelAndView ("newProductFormConfirm", model);
}
//List of products
#RequestMapping (value = "/listProducts")
public ModelAndView listProducts(#ModelAttribute("product")Product product){
ModelMap model = new ModelMap();
modelo.put("productService", productService.listProducts());
return new ModelAndView ("listProducts", model);
}
//Getters and Setters for the services
}

Related

Spring and hibernate integration Could not open JPA

I am currently developing a java/jee app using spring as framework and hibernate as orm.I am using the generic dao design pattern.I want to add a courrier Object to the db but i don't know why i got this error.
this is my log
Exception in thread "main" org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode()Lorg/hibernate/FlushMode;
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
at biz.picosoft.daoImpl.CourrierDaoImpl$$EnhancerBySpringCGLIB$$61c46376.insert(<generated>)
at biz.picosoft.mains.TestHibernate.main(TestHibernate.java:26)
Caused by: java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode()Lorg/hibernate/FlushMode;
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.prepareFlushMode(HibernateJpaDialect.java:176)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:162)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 8 more
this is my context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="biz.picosoft.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"></property>
<property name="showSql" value="true"></property>
</bean>
</property>
</bean>
<context:component-scan base-package="biz.picosoft" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mailmanager" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="contactDaoImpl" class="biz.picosoft.daoImpl.ContacteDaoImpl" />
<bean id="SociétéDaoImpl" class="biz.picosoft.daoImpl.SociétéDaoImpl" />
<bean id="sociétéDaoImpl" class="biz.picosoft.daoImpl.SociétéDaoImpl" />
<bean id="courrierDaoImpl" class="biz.picosoft.daoImpl.CourrierDaoImpl"></bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven proxy-target-class="true" />
</beans>
this is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BackEndFinalVersion</groupId>
<artifactId>BackEndFinalVersion</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.alfresco.cmis.client/alfresco-opencmis-extension -->
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-ldap</artifactId>
<version>5.17.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
</project>
this is my generic daoImpl
package biz.picosoft.daoImpl;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import biz.picosoft.dao.GenericDao;
#Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
#PersistenceContext
private EntityManager em;
protected Class<T> daoType;
public GenericDaoImp() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public Class<T> getDaoType() {
return daoType;
}
public void setDaoType(Class<T> daoType) {
this.daoType = daoType;
}
public void insert(T t) {
// TODO Auto-generated method stub
em.persist(t);
}
public void update(T t) {
// TODO Auto-generated method stub
em.merge(t);
}
public void delete(T t) {
// TODO Auto-generated method stub
Object managed = em.merge(t);
em.remove(managed);
}
public T findById(Class<T> t, String id) {
// TODO Auto-generated method stub
return em.find(daoType, id);
}
public List<T> findAll() {
// TODO Auto-generated method stub
Query query = em.createQuery("SELECT e FROM " + daoType.getName() + " e");
return (List<T>) query.getResultList();
}
}
my entity
package biz.picosoft.entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Société implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idSociété")
int idSociété;
#Column(name = "nom")
String nom;
#Column(name = "email")
String email;
#Column(name = "télèphone")
String télèphone;
#Column(name = "adress")
String adress;
#OneToMany
private Collection<Contacte> contacts;
public Société(String nom, String email, String télèphone, String adress) {
super();
this.nom = nom;
this.email = email;
this.télèphone = télèphone;
this.adress = adress;
}
public Société() {
super();
}
public int getIdSociété() {
return idSociété;
}
public void setIdSociété(int idSociété) {
this.idSociété = idSociété;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTélèphone() {
return télèphone;
}
public void setTélèphone(String télèphone) {
this.télèphone = télèphone;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public Collection<Contacte> getContacts() {
return contacts;
}
public void setContacts(Collection<Contacte> contacts) {
this.contacts = contacts;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idSociété;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Société other = (Société) obj;
if (idSociété != other.idSociété)
return false;
return true;
}
}
my main
package biz.picosoft.mains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.picosoft.dao.ContacteDao;
import biz.picosoft.daoImpl.ContacteDaoImpl;
import biz.picosoft.daoImpl.SociétéDaoImpl;
import biz.picosoft.entity.Contacte;
import biz.picosoft.entity.Société;
public class TestDaoS {
public static void main(String[] args) {
// TODO Auto-generated method stub
Société société=new Société("pico", "pico#gmail.com", "74255546", "el ghazella");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
SociétéDaoImpl sociétéDao=(SociétéDaoImpl) context.getBean("sociétéDaoImpl");
//ContacteDaoImpl contacteDaoImpl = (ContacteDaoImpl) context.getBean("contactDaoImpl");
sociétéDao.insert(société);
Contacte contacte=new Contacte("imed", "imed#pico.biz", "7424554", "ghazella", société);
Contacte contacte2=new Contacte("med", "med#pico.biz", "7424554", "ghazella", société);
//contacteDaoImpl.insert(contacte);
//contacteDaoImpl.insert(contacte2);
System.out.println("list contacts"+sociétéDao.findAll().get(0).getContacts());
}
}
It's a common issue with Spring 4.2 and Hibernate 5.2 integration, because Spring 4.2 version supports only Hibernate versions up to 5.1.
There's even a Bug reported for this issue in the Spring community, you can check it :
Support for Hibernate ORM 5.2, which is claiming that:
Hibernate ORM 5.2 got released just in time for Spring Framework 4.3. Let's do everything we can to support it right away, in particular upgrading our spring-orm-hibernate5 build to 5.2 while retaining compatbility with 5.0 and 5.1.
For further details you can check the following posts too:
Integrate Hibernate 5.2 with Spring framework 4.x
HibernateTemplate is throwing java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode() -- Spring4.2.6, Hibernate5.2

org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]

I am making a hibernate small application in which i am getting the following exception
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]
I have read several posts but unable to find the solution.
can anyone tell me why the exception is coming. The code is as below:
UserDetails.java
package com.sdnext.hibernate.tutorial.dto;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
#Entity
#Table (name="USER_DETAIL")
public class UserDetails
{
#Id
#Column(name="USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
#Column(name="USER_NAME")
private String userName;
#ElementCollection
#JoinTable(name="USER_ADDRESS",
joinColumns=#JoinColumn(name="USER_ID"))
#GenericGenerator(strategy="hilo", name = "hilo-gen")
#CollectionId(columns = { #Column(name="ADDRESS_ID") }, generator = "hilo-gen", type = #Type(type="long"))
private Collection<Address> lisOfAddresses = new ArrayList<Address>();
public Collection<Address> getLisOfAddresses() {
return lisOfAddresses;
}
public void setLisOfAddresses(Collection<Address> lisOfAddresses) {
this.lisOfAddresses = lisOfAddresses;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString()
{
return "[User Name: "+userName+"\n Office Address: "+lisOfAddresses+"]";
}
}
HibernateTestDemo.java
package com.sdnext.hibernate.tutorial;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.sdnext.hibernate.tutorial.dto.Address;
import com.sdnext.hibernate.tutorial.dto.UserDetails;
public class HibernateTestDemo {
public static void main(String[] args)
{
UserDetails user = new UserDetails();
//user.setUserId(1);
user.setUserName("Dinesh Rajput");
Address address1 = new Address();
address1.setStreet("First Street");
address1.setCity("First City");
address1.setState("First State");
address1.setPincode("First Pin");
Address address2 = new Address();
address2.setStreet("Second Street");
address2.setCity("Second City");
address2.setState("Second State");
address2.setPincode("Second Pin");
user.getLisOfAddresses().add(address1);
user.getLisOfAddresses().add(address2);
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Address.java
package com.sdnext.hibernate.tutorial.dto;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable //for value object it is not is entity object. Value object means does not have real meaning for self individually.
public class Address
{
#Column(name="STREET_NAME")
private String street;
#Column(name="CITY_NAME")
private String city;
#Column(name="STATE_NAME")
private String state;
#Column(name="PIN_CODE")
private String pincode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String toString()
{
return " {Street: "+street+" City: "+city+" State: "+state+" Pincode: "+pincode+" }";
}
}
Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernateDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Show all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.sdnext.hibernate.tutorial.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
As per your entity structure you have
UserDetails which can have multiple Address
but Address entity doesn't have any link to UserDetails
Pls change
#ElementCollection
#JoinTable(name="USER_ADDRESS", joinColumns=#JoinColumn(name="USER_ID"))
#GenericGenerator(strategy="hilo", name = "hilo-gen")
#CollectionId(columns = { #Column(name="ADDRESS_ID") }, generator = "hilo-gen", type = #Type(type="long"))
private Collection<Address> lisOfAddresses = new ArrayList<Address>();
to
#OneToMany(mappedBy="userDetails")
Collection<Address> colAddress;
and in Address entity add
#ManyToOne
#JoinColumn(name="USER_DETAIL_ID")
public UserDetails userDetails;
In comment it says too long, so iam posting it here, the following is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.technicalkeeda</groupId>
<artifactId>HibernateExamples</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Spring and Hibernate Examples</name>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
<spring.security.version>4.2.1.RELEASE</spring.security.version>
<hibernate.version>4.3.9.Final</hibernate.version>
<servlet.api.version>3.1.0</servlet.api.version>
<jsp.api.version>2.2</jsp.api.version>
<jstl.version>1.2</jstl.version>
<jdk.version>1.8</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>mysql</groupId> -->
<!-- <artifactId>mysql-connector-java</artifactId> -->
<!-- <version>5.1.9</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.3</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.slf4j</groupId> -->
<!-- <artifactId>slf4j-api</artifactId> -->
<!-- <version>1.7.25</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JavaConfig need this library -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
</project>

Error:org.hibernate.hql.internal.ast.QuerySyntaxException: Website is not mapped

I am trying to create project with restful web services.I am getting an error
org.hibernate.hql.internal.ast.QuerySyntaxException: Website is not
mapped
.I have tried each solution to solve this error.Please review my code and let me know if there is any suggestion.Thank You
GifController:
package com.gif.code.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.gif.code.model.GifModel;
import com.gif.code.service.GifService;
#RestController
public class GifController {
#Autowired
GifService gifService;
#RequestMapping(value = "/getAllData", method = RequestMethod.GET, headers = "Accept=application/json")
public List<GifModel> getData() {
System.out.println("In Controller");
List<GifModel> listOfData = gifService.getAllData();
return listOfData;
}
#RequestMapping(value = "/getData/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public GifModel getDataById(#PathVariable int id) {
return gifService.getData(id);
}
#RequestMapping(value = "/addData", method = RequestMethod.POST, headers = "Accept=application/json")
public void addData(#RequestBody GifModel gifModel) {
gifService.addData(gifModel);
}
}
GifModel:
package com.gif.code.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="WEBSITE")
public class GifModel {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="title")
String title;
#Column(name="description")
String description;
public GifModel() {
super();
}
public GifModel(int i, String title,String description) {
super();
this.id = i;
this.title = title;
this.description=description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
GifService:
package com.gif.code.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.gif.code.dao.GifDao;
import com.gif.code.model.GifModel;
#Service("gifService")
public class GifService {
#Autowired
GifDao gifDao;
#Transactional
public List<GifModel> getAllData() {
System.out.println("In Service");
return gifDao.getAllData();
}
#Transactional
public GifModel getData(int id) {
return gifDao.getData(id);
}
#Transactional
public void addData(GifModel gifmodel) {
gifDao.addData(gifmodel);
}
}
GifDao:
package com.gif.code.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.gif.code.model.GifModel;
#Repository
public class GifDao {
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#SuppressWarnings("unchecked")
public List<GifModel> getAllData() {
System.out.println("In Dao");
Session session = this.sessionFactory.getCurrentSession();
List<GifModel> textList = session.createQuery("from Website").list();
return textList;
}
public GifModel getData(int id) {
Session session = this.sessionFactory.getCurrentSession();
GifModel gifmodel = (GifModel) session.load(GifModel.class, new Integer(id));
return gifmodel;
}
public GifModel addData(GifModel gifmodel) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(gifmodel);
return gifmodel;
}
}
Spring-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 />
<resources mapping="/resources/**" location="/resources/" />
<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/gifdata" />
<beans:property name="username" value="root" />
<beans:property name="password" value="Chirpn123" />
</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.gif.code.model.GifModel</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.gif.code" />
<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>
Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gif.code</groupId>
<artifactId>Gif</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Gif Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.0.RELEASE</version>
</dependency> -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<finalName>Gif</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.2.1.RELEASE</spring.version>
<security.version>4.0.3.RELEASE</security.version>
<jdk.version>1.7</jdk.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<org.aspectj-version>1.7.4</org.aspectj-version>
</properties>
</project>
HQL works with the class names not with table names!
So you have to write:
List<GifModel> textList = session.createQuery("from GifModel").list();

javax.persistence.OneToMany.orphanRemoval<>Z

I've searched everywhere but I didn't found a good answer.
I am developping a maven application using Hibernate + Spring + Mysql.
Here is my application-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:...">
<bean id='dataSource' class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/university"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<bean id='sessionFactory' class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.university.entities.Course</value>
<value>com.university.entities.Student</value>
<value>com.university.entities.Teacher</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
</props>
</property>
</bean>
<bean id='transactionManager' class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref='sessionFactory'/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base-package="com.university.dao"></context:component-scan>
</beans>
and Here is my pom.xml :
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.4.RELEASE</spring.version>
<hibernate.version>3.6.7.Final</hibernate.version>
<jsf.version>2.2.4</jsf.version>
<slf4j.version>1.7.1</slf4j.version>
<primefaces.version>4.0</primefaces.version>
</properties>
<dependencies>
<!-- Tests unitaires avec junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- antlr -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.5.1</version>
</dependency>
<!-- Package entities -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0-rev-1</version>
<scope>provided</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<scope>runtime</scope>
</dependency>
<!-- JSF dependencies -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Primefaces dependency -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>${primefaces.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!-- javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
But when I try to test a simple DAO as :
package com.university.dao.test;
import java.util.List;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:application-context.xml" })
public class StudentDAOTest extends TestCase {
private static Log LOG = LogFactory.getLog(StudentDAOTest.class);
#Autowired
private StudentDAO studentDAO;
#Test
public void testFindAll() {
List<Student> listStudent = studentDAO.findAll();
LOG.debug(listStudent);
assertNotNull(listStudent);
}
#Test
public void testCreateOrUpdate() {
Student newStudent = new Student("Abderrahmen ISSA", "07701607");
studentDAO.createOrUpdate(newStudent);
assertNotNull(newStudent.getId());
}
#Test
public void testFindById() {
Integer id = 2;
Student student = studentDAO.findById(id);
assertNotNull(student);
}
#Test
public void testRemove() {
Student userToRemove = new Student("User To Test Remove", "11111111");
studentDAO.createOrUpdate(userToRemove);
Integer id = userToRemove.getId();
studentDAO.remove(userToRemove);
Student student = studentDAO.findById(id);
assertNull(student);
}
}
The Student class is :
package com.university.entities;
// Generated 20 oct. 2013 20:53:03 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Student generated by hbm2java
*/
#Entity
#Table(name = "student", catalog = "university")
public class Student implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String mail;
private Date birthDate;
private String birthPlace;
private String cin;
private Integer mobile;
private Set<Course> courses = new HashSet<Course>(0);
public Student() {
}
public Student(String mail, String cin) {
this.mail = mail;
this.cin = cin;
}
public Student(String name, String mail, Date birthDate, String birthPlace,
String cin, Integer mobile, Set<Course> courses) {
this.name = name;
this.mail = mail;
this.birthDate = birthDate;
this.birthPlace = birthPlace;
this.cin = cin;
this.mobile = mobile;
this.courses = courses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name", length = 45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "mail", nullable = false, length = 45)
public String getMail() {
return this.mail;
}
public void setMail(String mail) {
this.mail = mail;
}
#Temporal(TemporalType.DATE)
#Column(name = "birthDate", length = 10)
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "birthPlace", length = 45)
public String getBirthPlace() {
return this.birthPlace;
}
public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace;
}
#Column(name = "cin", nullable = false, length = 45)
public String getCin() {
return this.cin;
}
public void setCin(String cin) {
this.cin = cin;
}
#Column(name = "mobile")
public Integer getMobile() {
return this.mobile;
}
public void setMobile(Integer mobile) {
this.mobile = mobile;
}
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "course_has_student", catalog = "university", joinColumns = { #JoinColumn(name = "Student_id", nullable = false, updatable = false) }, inverseJoinColumns = { #JoinColumn(name = "Course_id", nullable = false, updatable = false) })
public Set<Course> getCourses() {
return this.courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
#Override
public String toString() {
return "Student [name=" + name + ", mail=" + mail + ", cin=" + cin
+ "]";
}
}
The StudentDAOImpl :
package com.university.dao.impl;
import org.springframework.stereotype.Repository;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
#Repository("studentDAO")
public class StudentDAOImpl extends GenericDAOImpl<Student> implements
StudentDAO {
}
The GenericDAOImpl :
package com.university.dao.impl;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.university.dao.GenericDAO;
#Transactional
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
#Autowired
protected SessionFactory sessionFactory;
/**
* Unit.
*/
private final Class<T> entityBeanType;
/**
* Instantiates a new GenericServiceImpl.
*/
#SuppressWarnings("unchecked")
public GenericDAOImpl() {
this.entityBeanType = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected final Session getCurrentSession() {
if (sessionFactory == null) {
throw new IllegalStateException(
"Session Factory has not been set on DAO before usage");
}
return sessionFactory.getCurrentSession();
}
/**
* Gets the entity bean type.
*
* #return the entity bean type
*/
public final Class<T> getEntityBeanType() {
return entityBeanType;
}
public void createOrUpdate(T entity) {
getCurrentSession().saveOrUpdate(entity);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
return getCurrentSession().createQuery(
"from " + getEntityBeanType().getName()).list();
}
#SuppressWarnings("unchecked")
public T findById(Integer id) {
T entity = (T) getCurrentSession().get(getEntityBeanType(), id);
return entity;
}
public void remove(T entity) {
getCurrentSession().delete(entity);
}
}
I can run the DAOTest on eclipse well but with mvn test I get :
org.springframework.beans.factory.BeanCreationEception : Error
creating bean with name 'sessionFactory' defined in class path
resource [application-context.xml] : Invocation of init method failed;
nested exception is java.lang.NoSuchMethodError :
javax.persistence.OneToMany.orphanRemoval<>Z.
Help please !
You have a library conflict. Have you set this up as Hibernate project in Eclipse so that Eclipse added necessary JARs to the classpath? This would explain why it works in Eclipse but not in the Maven build.
Anyway, ensure the Hibernate library versions match e.g 4.1.8.Final and remove the javax.persistence-api dependency.
This all you should need in your POM regarding Hibernate. Everything else will be resolved transitively by Maven.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>

Spring apps failed , Autowire get null in main.class

i am using netbeans 7.2, postgres sql,jpa2,hibernate 4.2.
i just created a new maven simple java project(not webapp).
However i have done setup hibernate and jpa,but autowire "wpService" get null(not sure is it caused by hibernate configuration).
here is my project file(innovax.rar), if you would like to test it.
https://skydrive.live.com/#cid=837EF1FA9A4C06AE&id=837EF1FA9A4C06AE%21130
my main class
package sg.com.innovax.Twitter;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sg.com.innovax.Twitter.DBObject.service.impl.wall_postServiceImpl;
import sg.com.innovax.Twitter.DBObject.service.wall_postService;
import twitter4j.*;
public final class twitter {
public static void main(String[] args) throws TwitterException {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
test a = new test();
}
}
my test instance
import org.springframework.beans.factory.annotation.Autowired;
import sg.com.innovax.Twitter.DBObject.service.wall_postService;
/**
*
* #author Nimamakaho
*/
public class test {
#Autowired
private wall_postService wpService;
test(){
// wpService is null when i break point here
System.out.println("Asd");
}
}
my wall post object
package sg.com.innovax.Twitter.DBObject;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Formatter;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "wall_post")
#NamedQueries({
#NamedQuery(name="wall_post.findById", query="select wp from wall_post wp where wp.id = :id")
// #NamedQuery(name="wall_post.getByHashtagsRecords", query="select wp.*,case when wpa.id is null then false else true end as ack from (select wp from wall_post wp where wp.id in (:id) ) as wp LEFT JOIN wall_post_acknowledgement wpa on wp.id = wpa.wall_post_id")
})
public class wall_post {
#Id
#SequenceGenerator(name="wall_post_id_seq", sequenceName="wall_post_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="wall_post_id_seq")
#Basic(optional = false)
private int id;
private String title;
private String message;
private boolean enable_acknowledgement;
private boolean enable_comment;
private Timestamp created_time;
private Timestamp edited_time;
private Timestamp deleted_time;
private Timestamp last_updated;
public Timestamp getLast_updated() {
return last_updated;
}
public void setLast_updated(Timestamp last_updated) {
this.last_updated = last_updated;
}
private int user_id;
public boolean isEnable_comment() {
return enable_comment;
}
public void setEnable_comment(boolean enable_comment) {
this.enable_comment = enable_comment;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isEnable_acknowledgement() {
return enable_acknowledgement;
}
public void setEnable_acknowledgement(boolean enable_acknowledgement) {
this.enable_acknowledgement = enable_acknowledgement;
}
public Timestamp getCreated_time() {
return created_time;
}
public void setCreated_time(Timestamp created_time) {
this.created_time = created_time;
}
public Timestamp getEdited_time() {
return edited_time;
}
public void setEdited_time(Timestamp edited_time) {
this.edited_time = edited_time;
}
public Timestamp getDeleted_time() {
return deleted_time;
}
public void setDeleted_time(Timestamp deleted_time) {
this.deleted_time = deleted_time;
}
}
my wall post service
package sg.com.innovax.Twitter.DBObject.service;
import java.util.List;
import sg.com.innovax.Twitter.DBObject.*;
public interface wall_postService {
public wall_post findById(Integer id);
public boolean isAuthorizeToAccess(int wallPostID,int userid);
}
my wall post service impl
package sg.com.innovax.Twitter.DBObject.service.impl;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.cfg.Configuration;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import sg.com.innovax.Twitter.DBObject.*;
import sg.com.innovax.Twitter.DBObject.service.wall_postService;
#Service
#Repository
public class wall_postServiceImpl implements wall_postService {
private static final Logger logger = LoggerFactory.getLogger(wall_postServiceImpl.class);
#PersistenceContext
private EntityManager em;
private EntityManagerFactory emf;
#Override
public wall_post findById(Integer id) {
try{
if(id == null) return null;
TypedQuery<wall_post> query = em.createNamedQuery("wall_post.findById", wall_post.class);
query.setParameter("id", id);
return query.getSingleResult();
}catch(NoResultException ex)
{
return null;
}
catch(Exception ex)
{
logger.error("=================================================");
logger.error("findById()",ex);
return null;
}
}
public boolean isAuthorizeToAccess(int wallPostID,int userid) {
try
{
String sql =
" select wall_post_id from wall_post_authority where group_id in "+
" (select group_id from group_user where user_id = :userid group by group_id) "+
" and wall_post_id = :wallPostID group by wall_post_id ";
Query query = em.createNativeQuery(sql).setParameter("userid", userid).setParameter("wallPostID", wallPostID);
Object a = query.getSingleResult();
return true;
}catch(NoResultException ex)
{
return false;
}
catch(Exception ex)
{
logger.error("=================================================");
logger.error("isAuthorizeToAccess()",ex);
return false;
}
}
}
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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:postgresql://127.0.0.1:5432/testspring" />
<property name="username" value="postgres" />
<property name="password" value="admin" />
</bean>
<!-- Database
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="admin" />
</bean>
-->
<!-- Entity Manager -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
</bean>
</property>
<property name="packagesToScan" value="sg.com.innovax" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Jpa Repositories -->
<jpa:repositories base-package="sg.com.innovax.Twitter"></jpa:repositories>
</beans>
here is my pom file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sg.com.innovax</groupId>
<artifactId>innovax</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<org.springframework-version>3.2.3.RELEASE</org.springframework-version>
<org.springjpa-version>1.3.2.RELEASE</org.springjpa-version>
</properties>
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.9.Final</version>
</dependency>
<!-- Additional Analyzers: -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-analyzers</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!-- Infinispan integration: -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-infinispan</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.170</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springjpa-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.10</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
AFAIK you cannot autowire a static field. Try it as an instance member and see if that solves your problem.
try to create a setter method for ur private field , and place the autowire annotation on the method like this:
private wall_postService wpService;
#Autowired
public void setwpService(wall_postService wpService){
this.wpService = wpService ;
}
and now use the method in the test class ...

Categories