This error is killing me, i searched a lot of similar topics here, but none of them helped me!
So, i'm using spring MVC+hibernate. Please, just take a look, maybe you will find mistake which i missed!
Here is my files:
Clients
package app.model;
import javax.persistence.*;
#Entity
#Table(name = "clients")
public class Clients {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int client_id;
private String gender;
private String first_name;
private String last_name;
private String country;
private String city;
private String birthdate;
private String phone;
private String email;
private int orders;
private double total_income;
public Clients() {
}
public Clients(int client_id, String gender, String first_name,
String last_name, String country, String city, String birthdate,
String phone, String email, int orders, double total_income) {
super();
this.client_id = client_id;
this.gender = gender;
this.first_name = first_name;
this.last_name = last_name;
this.country = country;
this.city = city;
this.birthdate = birthdate;
this.phone = phone;
this.email = email;
this.orders = orders;
this.total_income = total_income;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public int getClient_id() {
return client_id;
}
public void setClient_id(int client_id) {
this.client_id = client_id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getOrders() {
return orders;
}
public void setOrders(int orders) {
this.orders = orders;
}
public double getTotal_income() {
return total_income;
}
public void setTotal_income(double total_income) {
this.total_income = total_income;
}
}
ClientsService
package app.service;
import java.text.ParseException;
import java.util.List;
import app.model.Clients;
public interface ClientsService {
public void addClient(Clients client);
public void updateClient(Clients client) throws ParseException;
public void deleteClient(Clients client) throws ParseException;
public Clients getClient(int client_id);
public List<Clients> getAllClients();
}
ClientsServiceImpl
package app.service.impl;
import java.text.ParseException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import app.dao.ClientsDao;
import app.model.Clients;
import app.service.ClientsService;
#Service
public class ClientsServiceImpl implements ClientsService {
#Autowired
private ClientsDao clientsDao;
public ClientsServiceImpl() {
}
public List<Clients> getAllClientsList() {
return clientsDao.getAllClients();
}
#Transactional
public void addClient(Clients client) {
clientsDao.addClient(client);
}
#Transactional
public void updateClient(Clients client) throws ParseException{
clientsDao.updateClient(client);
}
#Transactional
public void deleteClient(Clients client) throws ParseException{
clientsDao.deleteClient(client);
}
#Transactional
public Clients getClient(int client_id) {
return clientsDao.getClient(client_id);
}
#Transactional
public List<Clients> getAllClients() {
return clientsDao.getAllClients();
}
}
ClientsDao
package app.dao;
import java.text.ParseException;
import java.util.List;
import app.model.Clients;
public interface ClientsDao {
public void addClient(Clients client);
public void updateClient(Clients client) throws ParseException;
public void deleteClient(Clients client) throws ParseException;
public Clients getClient(int client_id);
public List<Clients> getAllClients();
}
ClientsDaoImpl
package app.dao.impl;
import java.text.ParseException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import app.model.Clients;
import app.dao.ClientsDao;
import app.logic.Similar;
#Repository
public class ClientsDaoImpl implements ClientsDao {
#Autowired
public SessionFactory session;
public ClientsDaoImpl() {
}
#Transactional
#SuppressWarnings("unchecked")
public List<Clients> getAllClients() {
return session.getCurrentSession().createQuery("from Clients").list();
}
#Transactional
public void addClient(Clients client) { // add new client
session.getCurrentSession().save(client);
}
#Transactional
public void updateClient(Clients client) throws ParseException { // update client
session.getCurrentSession().update(client);
}
#Transactional
public void deleteClient(Clients client) throws ParseException { // delete client if he\she doesnt have any orders
session.getCurrentSession().delete(client);
}
#Transactional
public Clients getClient(int client_id) {
return (Clients)session.getCurrentSession().get(Clients.class, client_id);
}
}
ClientsController
package app.controller;
import java.text.ParseException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 app.model.Clients;
import app.service.ClientsService;
#Controller
public class ClientsController {
#Autowired
public ClientsService clientsService;
public ClientsController(){
}
#RequestMapping("/index")
public String setupForm(Map<String, Object> map) {
Clients client = new Clients();
map.put("client", client);
map.put("clientsList", clientsService.getAllClients());
return "client";
}
#RequestMapping(value = "/client.do", method = RequestMethod.POST)
public String doActions(#ModelAttribute Clients client,
BindingResult result, #RequestParam String action,
Map<String, Object> map) throws ParseException {
Clients clientResult = new Clients();
switch (action.toLowerCase()) {
case "add":
clientsService.addClient(client);
clientResult = client;
break;
case "edit":
clientsService.updateClient(client);
clientResult = client;
break;
case "delete":
clientsService.deleteClient(client);
clientResult = new Clients();
break;
case "search":
Clients searchedClient = clientsService.getClient(client.getClient_id());
clientResult = searchedClient != null ? searchedClient : new Clients();
break;
}
map.put("client", clientResult);
map.put("clientsList", clientsService.getAllClients());
return "client";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>ProjectMVC</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/projectdb
jdbc.username=root
jdbc.password=root
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="app.*">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<context:spring-configured />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<tx:annotation-driven />
<aop:config proxy-target-class="true"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Project</groupId>
<artifactId>Project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Hibernate resources -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>20030825.183949</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- Log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/main/test</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/webapp</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
upd: forgot hibernate.cfg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="app.model.Clients" />
</session-factory>
</hibernate-configuration>
Possibly try this solution from here: Getting a org.springframework.beans.factory.BeanCreationException with my first Maven, Spring Project
just add:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${your-spring-version}</version>
</dependency>
I think your missing the repository name in your ClientsDaoImpl .
#Repository("clientsDAO")
public class ClientsDaoImpl implements ClientsDao.....
Related
I am trying to fix below error:
Error creating bean with name 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping'
but still getting following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.web.servlet.handler.AbstractHandlerMapping.obtainApplicationContext()Lorg/springframework/context/ApplicationContext;
Below is my setup:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.javatpoint"/>
<import resource="classpath:IOC.xml"/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Bai Tap</display-name>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
IOC.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:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.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-4.3.xsd">
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName"
value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/BaiTap" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.javatpoint.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
Employee.java
package com.javatpoint;
public class Employee {
private int id;
private String name;
private float salary;
public Employee(int id, String name, float salary) {
super();
this.id = id;
this.name = name;
this.salary = 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;
}
}
EmployeeDao.java
package com.javatpoint;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e) {
String query = "insert into employee(id,name,salary) values(" + e.getId() +"," + e.getName() + "," + e.getSalary() +")";
return jdbcTemplate.update(query);
}
public int updateEmployee(Employee e) {
String query = "update employee set name = "+e.getName()+",salary="+e.getSalary()+"where id="+e.getId()+"";
return jdbcTemplate.update(query);
}
public int deleteEmployee(Employee e) {
String query = "delete from employee where id = "+e.getId()+"";
return jdbcTemplate.update(query);
}
}
Test.java
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class Test {
#RequestMapping("/")
#ResponseBody
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
EmployeeDao dao = (EmployeeDao) context.getBean("edao");
int status = dao.saveEmployee(new Employee(102,"Amit",3500));
System.out.println(status);
}
}
porm.xml http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.javatpoint
BaiTap
0.0.1-SNAPSHOT
war
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjrt -->
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
</dependencies>
</project>
your code
#Controller
public class Test {
#RequestMapping("/")
#ResponseBody
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
EmployeeDao dao = (EmployeeDao) context.getBean("edao");
int status = dao.saveEmployee(new Employee(102,"Amit",3500));
System.out.println(status);
}
}
return type is void, it means the method return nothing. Therefore, it cannot return #ResponseBody in same time.
main method is reserved for entry point of Java Class, you must change method's name.
How have you constructed your project?
The java.lang.NoSuchMethodError means that this method does not exist at runtime.
This method would have been invoked from inside a library but it was unable to find that method.
If it is a non Spring Boot project, can you please check if you have included spring-core and spring-context in your setup.
As you have applicationContext.xml which imports IOC.xml you should change your
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
to
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
EDIT
You need to restructure your controller class also
package com.javatpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("IOC.xml");
EmployeeDao dao = (EmployeeDao) context.getBean("edao");
int status = dao.saveEmployee(new Employee(102,"Amit",3500));
System.out.println(status);
}
}
And finally run your this class.
Hi I try to add data to oraclexe database with spring mvc and hibernate by dao design pattern but it make this error
"org.springframework.web.util.NestedServletException"
how can solve this problem ?
This program just worked with springMVC whithout hibernate but when I try to add hibernate it doesn't work and give me the error I don't know how can connect springMVC with hibernate
this is my pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
and class Resource.java
package com.spring.mvc.model;
import javax.persistence.*;
#Entity
#Table(name = "RESOURCSE")
public class Resource {
#Id
#GeneratedValue
#Column(name = "ID",unique = true,length = 10)
private int id;
#Column(name = "NAME", length = 25)
private String name;
#Column(name = "TYPE", length = 30)
private String type;
#Column(name = "unitOfMesure", length = 25)
private String unitOfMesure;
#Column(name = "notes", length = 25)
private String notes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Resource(String name, String type, String unitOfMesure, String notes) {
this.name = name;
this.type = type;
this.unitOfMesure = unitOfMesure;
this.notes = notes;
}
public String getUnitOfMesure() {
return unitOfMesure;
}
public void setUnitOfMesure(String unitOfMesure) {
this.unitOfMesure = unitOfMesure;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Resource() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Resource{" +
"id=" + id +
", name='" + name + '\'' +
", type='" + type + '\'' +
", unitOfMesure='" + unitOfMesure + '\'' +
", notes='" + notes + '\'' +
'}';
}
}
and ResourceDaoImpl
package com.spring.mvc.dao;
import com.spring.mvc.model.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository
#Transactional
public class ResourceDaoImpl implements ResourceDao {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addResource(Resource resource) {
try (Session session = this.sessionFactory.getCurrentSession()) {
session.persist(resource);
}
}
#Override
public void updateResource(Resource resource) {
Session session = this.sessionFactory.getCurrentSession();
session.update(resource);
}
#Override
public List<Resource> listResource() {
Session session = this.sessionFactory.getCurrentSession();
List list_resources = session.createQuery("from Resource ").list();
return list_resources;
}
#Override
public Resource getResourceById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Resource resourceId = session.load(Resource.class, id);
return resourceId;
}
#Override
public void removeResource(int id) {
Session session = this.sessionFactory.getCurrentSession();
Resource resourceId = session.load(Resource.class, id);
if (resourceId != null){
session.delete(resourceId);
}
}
}
and ResourceServiceImpl
package com.spring.mvc.service;
import com.spring.mvc.dao.ResourceDao;
import com.spring.mvc.model.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class ResourceServiceImpl implements ResourceService {
private ResourceDao resourceDao;
public ResourceDao getResourceDao() {
return resourceDao;
}
public void setResourceDao(ResourceDao resourceDao) {
this.resourceDao = resourceDao;
}
#Override
public void addResource(Resource resource) {
this.resourceDao.addResource(resource);
}
#Override
public void updateResource(Resource resource) {
this.resourceDao.updateResource(resource);
}
#Override
public List<Resource> listResource() {
return this.resourceDao.listResource();
}
#Override
public Resource getResourceById(int id) {
return this.resourceDao.getResourceById(id);
}
#Override
public void removeResource(int id) {
this.resourceDao.removeResource(id);
}
}
and ResourceController
package com.spring.mvc.controller;
import com.spring.mvc.model.Resource;
import com.spring.mvc.service.ResourceService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
#Controller
#RequestMapping("/resource")
public class ResourceController {
private ResourceService resourceService;
public void setResourceService(ResourceService resourceService) {
this.resourceService = resourceService;
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Model model){
return "resource_add";
}
#ModelAttribute("resource")
public Resource resource(){
return new Resource();
}
#ModelAttribute("typeOptions")
public List<String> getTypes(){
return new LinkedList<>(Arrays.asList(new String[]{
"English","France","Italy"
}));
}
#ModelAttribute("radioOptions")
public List<String> getRadios(){
return new LinkedList<>(Arrays.asList(new String[]{
"Hour","Piece","Tones"
}));
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute Resource resource){
this.resourceService.addResource(resource);
System.out.println(resource);
return "resource_add";
}
}
and this is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/xsd/hibernate-configuration">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
<mapping class="com.spring.mvc.model.Resource"></mapping>
</session-factory>
</hibernate-configuration>
First do not put #Transactional in front of DAO classes, put it only above the Services
classes.it won't be an error but it is a good practice
Edit
you did not add the hibernate in your spring-mvc, that's why #Autowired was not worked. you need to add hibernate config inside the spring like this (this is an example code, and change your appropriate values)
<!-- Add support for component scanning -->
<context:component-scan base-package="net.javaguides.springmvc" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven />
<!-- Define Spring MVC view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC" />
<property name="user" value="user" />
<property name="password" value="password" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="net.javaguides.springmvc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
/********************************************************************/
in this method
#Override
public void updateResource(Resource resource) {
Session session = this.sessionFactory.getCurrentSession();
session.update(resource);
}
use beginTransaction and commit, like this
#Override
public void updateResource(Resource resource) {
Session session = this.sessionFactory.getCurrentSession();
session.beginTransaction();
session.update(resource);
session.getTransaction().commit();
}
and I am not sure you initialize the sessionFactory here
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
you can simply initialize using #Autowired annotation. like that,
#Autowired
protected SessionFactory sessionFactory;
Controller
package com.hellokoding.hello.web;
import com.hellokoding.hello.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.hellokoding.hello.dao.*;
#Controller
public class HelloController {
#Autowired
StudentDAO studentDao;
#RequestMapping("/")
public String index() {
return "input";
}
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(#RequestParam(value = "name", required = false, defaultValue = "World") String name,
Model model) {
model.addAttribute("name", name);
return "hello";
}
#RequestMapping(value = "/studentRegister", params = {"save"})
public String saveSeedstarter(final Student student, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "input";
}
model.addAttribute("student", student);
studentDao.saveStudent(student);
return "result";
}
#ModelAttribute("student")
public Student getStudent(){
return new Student();
}
/*
* #RequestMapping(value = "/studentRegister", method = RequestMethod.POST)
* public String index(#RequestParam(value="save") Student student, Model
* model) { model.addAttribute("student", student); return "hello"; }
*/
}
Hsql db in
The url is jdbc:hsqldb:mem:mydb
I dunno where the db files will be??. If i open in database manager then i cannot see the student database. Help me to fix this
I have the form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Thyme Seed Starter Manager</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>Add new student</h2>
<form action="#" th:action="#{/studentRegister}"
th:object="${student}" method="post">
<input type="text" th:field="*{firstName}"/>
<input type="text" th:field="*{lastName}"/>
<input type="submit" name="save" value="save"/>
</form>
</body>
</html>
Web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Hello Spring MVC</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<import resource="appconfig-mvc.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.hellokoding.hello.*"/>
<context:property-placeholder location="classpath:application.properties"/>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</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>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="packagesToScan" value="com.hellokoding.hello.pojo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
</beans>
I need to submit the form i have added the it to student model attribute in controller. I need to insert this data into student db of HSQL. How to proceed with modifications in spring xml.
I have included a persistence.xml under resources/META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="manager" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.hellokoding.hello</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:mydb"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
configuration.properties
jdbc.driver.className=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:mydb
jdbc.username=sa
jdbc.password=
jdbc.hibernate.dialect=org.hibernate.dialect.HSQLDialect
DAO interface
package com.hellokoding.hello.dao;
import java.util.List;
import com.hellokoding.hello.pojo.Student;
public interface StudentDAO {
public void saveStudent(Student student);
public List<Student> getAllStudents(Student student);
public Student getStudentById(String studentId);
public void deleteStudent(Student student);
}
DAO implementation
package com.hellokoding.hello.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.hellokoding.hello.pojo.Student;
//This will make easier to autowired
#Repository("StudentDAO")
#Transactional
public class StudentDAOImpl implements StudentDAO {
private HibernateTemplate hibernateTemplate;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Transactional(readOnly = false)
public void saveStudent(Student student) {
System.out.println("Inside");
hibernateTemplate.saveOrUpdate(student);
}
#Transactional(readOnly = false)
public void deleteStudent(Student student) {
hibernateTemplate.delete(student);
}
#SuppressWarnings("unchecked")
public List<Student> getAllStudents(Student student) {
return (List<Student>) hibernateTemplate.find("from " + Student.class.getName());
}
public Student getStudentById(String studentId) {
return hibernateTemplate.get(Student.class, studentId);
}
}
I have tried with hibernate and i was trying to insert into the db.
Student Bean
package com.hellokoding.hello.pojo;
import javax.persistence.*;
import java.io.Serializable;
//import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "student_table")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
public static long getSerialversionuid() {
return serialVersionUID;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "first_name", nullable = false)
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", nullable = false)
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Student(){
}
public Student(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
The id is also not generating and its not inserting the HSQL db table called student_table
Pom.xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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.hellokoding</groupId>
<artifactId>hello</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Hello Spring MVC</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.8</jdk.version>
<spring.version>4.1.6.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<junit.version>3.8.1</junit.version>
<logback.version>1.1.3</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.5.Final</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.8.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<!-- embedded Jetty server, for testing -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
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();
Hi I have started to use Spring and JPA for the first time, I've tried many tutorials and questions here at stack overflow.But no success so I hope some one can give me a clear way out of this problem. I'm developing a toy application to get confident with the technology before I start the real project, I'm using Java, Spring, Hibernate, JPA and MySQL on a Maven-non web module project using java annotations as much as possible and as little xml as possible, I've found many web base application full of xml files but was unable to understand how to correct my project. The only thing I am able to understand is that I need to declare a persistence unit somehow telling the entity manager what to do, but there is no META-INF folder in my project (should create one?) AND most persistance.xml files I've found declare little more than what I have in my jpa-handler-conf.xml which seems to otherwise work fine.
So here are the project components:
The Beans:
package hp.esercizi.beans;
imports omitted...
#Component
#Entity
#Table(name = "AUTORE")
public class Autore {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "NOME", length = 20)
private String nome;
#Column(name = "COGNOME", length = 20)
private String cognome;
#OneToMany(targetEntity=Autore.class, mappedBy="amici")
private List<Autore> amici;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Autore> getAmici() {
return amici;
}
public void setAmici(List<Autore> amici) {
this.amici = amici;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
}
package hp.esercizi.beans;
imports omitted...
#Component
#Entity
#Table(name = "MESSAGGIO")
public class Messaggio {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "TESTO", nullable = false, length = 200)
private String testo;
#ManyToOne
#JoinColumn(name="AUTORE_ID")
private Autore autore;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public Autore getAutore() {
return autore;
}
public void setAutore(Autore autore) {
this.autore = autore;
}
}
The DAOs:
package hp.esercizi.dao;
imports omitted...
public interface AutoreDAO {
public EntityManager getEntityManager();
public void setEntityManager(EntityManager entityManager);
public void insert(Autore autore);
public List<Autore> selectAll();
public Autore findAutoreByID(Long id);
}
package hp.esercizi.dao;
imports omitted...
#Repository("AutoreDAO")
#Transactional
public class AutoreDAOJPA2Impl implements AutoreDAO {
private static final String SELECT_QUERY = "select a from autore a";
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void insert(Autore autore) {
entityManager.persist(autore);
}
public List<Autore> selectAll() {
Query query = (Query) entityManager.createQuery(SELECT_QUERY);
List<Autore> autori = (List<Autore>) query.getResultList();
return autori;
}
public Autore findAutoreByID(Long id) {
return entityManager.find(Autore.class, id);
}
}
package hp.esercizi.dao;
imports omitted...
public interface MessaggioDAO {
public EntityManager getEntityManager();
public void setEntityManager(EntityManager entityManager);
public void insert(Messaggio messaggio);
public List<Messaggio> selectAll();
}
package hp.esercizi.dao;
imports omitted...
#Repository("MessaggioDAO")
#Transactional
public class MessaggioDAOJPA2Impl implements MessaggioDAO {
private static final String SELECT_QUERY = "select m from messaggio m";
#PersistenceContext
private EntityManager entityManager;
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void insert(Messaggio messaggio) {
entityManager.persist(messaggio);
}
public List<Messaggio> selectAll() {
Query query = (Query) entityManager.createQuery(SELECT_QUERY);
List<Messaggio> messaggi = (List<Messaggio>) query.getResultList();
return messaggi;
}
}
Entity Manager and Data Source configuration XML (jpa-handler-conf.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:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="vendorAdaptor" />
<property name="packagesToScan" value="hp.esercizi" />
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="abstractVendorAdaptor" abstract="true">
<!-- <property name="generateDdl" value="${db.generate}" /> -->
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
</bean>
<bean id="vendorAdaptor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
parent="abstractVendorAdaptor">
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/DB_SpringContext" />
<property name="username" value="root" />
<property name="password" value="Lavoro01" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
</beans>
The context configuration:
package hp.esercizi.utility;
imports omitted...
#ComponentScan("hp.esercizi.beans")
public class BeansConfig {
}
package hp.esercizi.utility;
imports omitted...
#Configuration
#ComponentScan("hp.esercizi.dao")
public class DataSourceConfig {
}
package hp.esercizi.utility;
imports omitted...
#Configuration
#Import({BeansConfig.class , DataSourceConfig.class})
#ImportResource("jpa-handler-conf.xml")
public class SpringConfig {
}
The Main:
package hp.esercizi.main;
imports omitted...
public class Main {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
EntityManagerFactory emfactory = Persistence.createEntityManagerFactory("AutoreDAO");
EntityManager entitymanager = emfactory.createEntityManager( );
entitymanager.getTransaction( ).begin( );
Messaggio msg = (Messaggio) context.getBean("messaggio");
entitymanager.merge(msg);
Autore aut = (Autore) context.getBean("autore");
entitymanager.merge(aut);
msg.setTesto("Ciao Mondo!!!");
aut.setNome("Mario");
aut.setCognome("Rossi");
System.out.println(msg.getTesto());
System.out.println(msg.getAutore().getNome() + " " + msg.getAutore().getCognome());
entitymanager.persist(msg);
entitymanager.getTransaction().commit();
Messaggio msg2 = entitymanager.find(Messaggio.class, 1);
ObjectMapper mapper = new ObjectMapper();
try {
System.out.println(mapper.writeValueAsString(msg2));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
entitymanager.close( );
emfactory.close( );
}
}
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>esercizi</groupId>
<artifactId>SpringContext</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</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>5.0.0.CR2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.0.CR2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
</project>