Unable ot get openJPA working with Tomcat 8 - java

I'm trying to get OpenJPA working with Tomcat 8 but have been unable, it throws the error:
org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the
data source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties
are available in the configuration:
"org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl#2655aabb".
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
...servlet stuff...
<resource-ref>
<description>Database</description>
<res-ref-name>jdbc/webservice</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
My context.xml (I verified this datasource works by doing a connection via InitialContext, etc in a servlet):
<?xml version="1.0" encoding="utf-8"?>
<Context>
<Resource name="jdbc/webservice" auth="Container"
type="javax.sql.DataSource"
maxActive="8"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"
validationQuery="SELECT 1"
username="dev" password="mypass"
url="jdbc:mysql://127.0.0.1:3306/mydb"
driverClassName="com.mysql.jdbc.Driver">
</Resource>
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>
My persistence.xml (I also tried every diff combo of the properties and data-source elements. I also tried "RESOURCE_LOCAL"):
<?xml version="1.0" encoding="UTF-8"?>
<persistence
version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="TestOpenJPAPersistence" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>java:comp/env/jdbc/webservice</jta-data-source>
<non-jta-data-source>java:comp/env/jdbc/webservice</non-jta-data-source>
<
<properties>
<!--
I tried leaving these out, leaving them in and all combinations.
I also tried it with the jdbc url, username, password in properties too.
-->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionFactoryProperties" value="MaxActive=10,MaxIdle=5,MinIdle=2,MaxWait=1800000"/>
<property name="openjpa.Log" value="org.apache.openjpa.log, DefaultLevel=DEBUG, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.DynamicEnhancementAgent" value="false" />
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
</properties>
</persistence-unit>
</persistence>
My pom.xml:
<?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>groupId</groupId>
<artifactId>TestWebSocket</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- Tell Maven what language version to use -->
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
<!-- Enables the annotations, etc needed -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<exclusions>
<exclusion>
<groupId>javax.exterprise</groupId>
<artifactId>cdi-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Our jersey libs -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25.1</version>
</dependency>
<!-- CDI to JAX-RS Binding -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi-ban-custom-hk2-binding -->
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>2.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.servlet/weld-servlet-core -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>3.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld/weld-core-impl -->
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core-impl</artifactId>
<version>3.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
</project>
My Servlet:
package com.testjpa;
import com.testpush.TestEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
#WebServlet("/jpa")
public class JPAServlet extends HttpServlet
{
#PersistenceUnit(unitName = "TestOpenJPAPersistence")
EntityManagerFactory persistenceFactory;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
EntityManager persistenceManager = null;
String result = "Not found";
try
{
//I need to do this as otherwise the factory is null
persistenceFactory = Persistence.createEntityManagerFactory( "TestOpenJPAPersistence" );
//This line throws the error
persistenceManager = persistenceFactory.createEntityManager();
User user = persistenceManager.find( User.class, 9 );
if ( user != null )
{
result = user.getName();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if ( persistenceManager != null )
{
persistenceManager.close();
}
}
resp.getWriter().println( result );
}
}

Looking at your source code, I found the problem : your persistence.xml is located in src/main/webapp/META-INF instead of src/main/resources/META-INF.
Move it to src/main/resources/META-INF and remove the javax.persistence.jdbc.driver property and it will work.

Related

While using OneToMany tags .. No Persistence provider for EntityManager - Hibernate JPA

Well i've benn looking for this problem wasting so much time, so i'm here.
import javax.persistence.*;
#Entity
#Table(name = "secretario")
public class Secretario {
#Id
#GeneratedValue
private long codigoS;
#Column
private String nombre;
#ManyToOne
#JoinColumn(name = "codigoE")
private Empleado e;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
#Entity
#Table
public class Empleado implements Serializable {
private static final long serialVersionUID = 1l;
#Id
#Column
#GeneratedValue
private long codigoE;
#Column
private String apellido;
#Column
private String nombre;
#OneToMany(mappedBy = "e")
private ArrayList<Secretario> secretario;
When i use te OneToMany and ManyToOne tags i got this exception and i dont why... or how ...
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named Persistencia
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at tests.TestEmpleados.main(TestEmpleados.java:22)
here is my persistence config
<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="Persistencia">
<!-- <description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>-->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- Representar clases -->
<class>model.Empleado</class>
<class>model.Secretario</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL8Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
And my maven config
<?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>org.example</groupId>
<artifactId>Hibernate</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
<!--<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.3.1.Final</version>
</dependency>-->
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Some way i fixed using the #Transient tag and my entities were correctly persisted, but when i tried to query them i got a null in the OneToMany relation bcz it tells hibernate not to do something with that attribute...
emf = Persistence.createEntityManagerFactory("Persistencia");
manager = emf.createEntityManager();
This is where the exception shows
#UPDATE
Somehow i figured out that #OneToMany only accepts Collection Type as List,set, Map, etc but not "ArrayList" and i just changed the data type and it work fine..
#Transient - tells hibernate not persist such fields, that's why you have null at this fields. Also that's why you don't get problem again.
#ManyToOne are Lazy by default, so you should get them inside transaction.
You can achive this to annotate method where you use this property with #Transactional if you use JPA. Or you can use methods beginTransaction(), endTransaction() from EntityManager.
As long as your entity will go from transactional scope error will occure again. So convert your entity to dto before gone from transactional scope.
Another solution you can annotate your fields as Eager, so they will be downloaded from database with parent entity.
But Eager - bad solution, don't use it if don't know what is it.
I will try to answer the question but certain things depends on your setup i.e using as Java SE or J2EE application.
For Java SE, make sure you have your persistence file inside META-INF/persistence.xml under resources folder, Please check this article or in docs
For J2EE application, you generally configure the JNDI name in your server's configuration and then use that JNDI name inside your persistence.xml.
Also, please check all your database credentials and check access to it manually and follow the stack trace, it will tell you complete story what is going wrong.

Error In Maven Spring 3 Dynamic Application

i am using maven, spring 3 for dynamic project. I am getting error at <bean name="/hello.cs" class="com.maven.controller.HelloController"/> as Multiple annotations found at this line:
- Class 'com.maven.controller.HelloController'
Project Structure
Web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.cs</url-pattern>
</servlet-mapping>
</web-app>
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="/hello.cs" class="com.maven.controller.HelloController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
index.jsp
<jsp:forward page="WEB-INF/jsp/home.jsp"></jsp:forward>
home.jsp
<form action="./hello.cs" method="post">
<div>
<div>
User Name:<input type="text" name="name"/>
</div>
<div>
Password: <input type="password" name="pass"/>
</div>
<div>
<input type="submit" value="Login"/>
</div>
<div>
<p style="color: red">${msg}</p>
</div>
</div>
</form>
HelloController
package com.maven.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.Controller;
public class HelloController extends AbstractController{
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String name = req.getParameter("name");
String pwd = req.getParameter("pass");
Map<String, String> m = new HashMap<String, String>();
if(name.equalsIgnoreCase("xyz") && pwd.equalsIgnoreCase("123")){
m.put("msg", "welcome mr. "+req.getParameter("name"));
return new ModelAndView("success", m);
} else {
m.put("msg", "Invalid");
return new ModelAndView("home");
}
}
}
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.javatpoint</groupId>
<artifactId>CubeGeneratorWeb</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>CubeGeneratorWeb 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>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>CubeGeneratorWeb</finalName>
</build>
</project>
Error:
EDIT: It says class 'com.maven.controller.HelloController' not found.
I see that you have put your com.maven.controller.HelloController.java file under src\main\resources folder.
It should be under src\main\java folder. So the hierarchy should be like
src
|-main
|-java
|-com
|-maven
|-controller
|-HelloController.java
The reason is the directory structure followed by maven detects java files only if it's placed under this hierarchy src\main\java, if you are using default configuration.
Can you right click on project and go to Properties > Java Build Path > Source and check whether src\main\java entry is there in the build path list or not? If not add it and try again.
After lots of struggle i got the answer, i had error in spring.xml file. check the solutions.
i need to add below code only in spring.xml file.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
previously i was using below code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
for above code i need to change pom.xml file, i mean need to add more dependency.
so this is my final spring.xml file for this question only.
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name="/hello.sa" class="com.maven.controller.HelloController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

No persistence provider for EntityManager for Hibernate in Maven

I am getting this error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named tarefas at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
My jars is okay, as you seem in the pom.xml
My main class:
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class GeraTabelas {
public static void main(String[] args)
{
EntityManagerFactory factory = Persistence.createEntityManagerFactory("tarefas");
factory.close();
}
}
pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.9.Final</version>
</dependency>
persistence.xml
<persistence-unit name="tarefas">
<!-- provedor/implementacao do JPA -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- entidade mapeada -->
<class>br.com.abc.models.Usuario</class>
<properties>
<property name="hibernate.connection.url" value= .... //The rest of properties...
</properties>
</persistence-unit>
It may be the position of the pom.xml file in the wrong location? I did this way because of others posts that said it was this way but this interrogation point appears in the folders and I am beginner in Maven to know what it is.
Thanks.

not getting model filled from jsp in spring mvc

Same error even adding #ModelAttributeI am not able to get the model class filled while clicking on button on jsp. In Database a new field is created but value are going null(Because model is not getting filled).
Please help me out on this.
Thanks in advance.
My Model class is:
package model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "conversion")
public class Conversion {
#Id
#GeneratedValue
private int conversionId;
#Column(name = "conversionFrom")
private String conversionFrom;
#Column(name = "conversionFromValue")
private int conversionFromValue;
#Column(name = "conversionTo")
private String conversionTo;
#Column(name = "conversionToValue")
private int conversionToValue;
#Column(name = "conversionDate")
private Date conversionDate;
public int getConversionId() {
return conversionId;
}
public void setConversionId(int conversionId) {
this.conversionId = conversionId;
}
public String getConversionFrom() {
return conversionFrom;
}
public void setConversionFrom(String conversionFrom) {
this.conversionFrom = conversionFrom;
}
public int getConversionFromValue() {
return conversionFromValue;
}
public void setConversionFromValue(int conversionFromValue) {
this.conversionFromValue = conversionFromValue;
}
public String getConversionTo() {
return conversionTo;
}
public void setConversionTo(String conversionTo) {
this.conversionTo = conversionTo;
}
public int getConversionToValue() {
return conversionToValue;
}
public void setConversionToValue(int conversionToValue) {
this.conversionToValue = conversionToValue;
}
public Date getConversionDate() {
return conversionDate;
}
public void setConversionDate(Date conversionDate) {
this.conversionDate = conversionDate;
}
}
My controller method is:
#RequestMapping("/saveConversion")
public ModelAndView saveConversion(HttpServletRequest request, HttpServletResponse response, Model model,
Conversion conversion) throws ServletException, IOException, ParseException {
System.out.println("In saveConversion");
Boolean boolean1 = serviceDao.setConversion(conversion);
if (boolean1) {
model.addAttribute("conversionSaved", "Conversion saved successfully!");
} else {
model.addAttribute("conversionSaved", "Conversion Not saved!");
}
return new ModelAndView("setConversion");
}
My Jsp is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#page import="model.Test"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lexis Nexis Admin Set Conversion Page</title>
<!--css and js starts-->
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="jQueryAssets/jquery_lib.js"></script>
<script>
function SaveConversion() {
var params = $("#Conversion_form").serialize();
alert(params);
$.ajax({
method : "POST",
url : "saveConversion",
data : {
'params' : params
},
success : function(result) {
alert(result);
$("#responseDiv").html(result);
messageDisplay();
return false;
}
})
}
function messageDisplay() {
alert("${conversionSaved}");
}
</script>
</head>
<body onload="clearData()">
<div class="mainpage">
<div class="add_admin_form">
<form id="Conversion_form" method="post" name="Conversion">
<div class="add_admin_form_label">
<spring:message code="CONVERSION_FROM" />
</div>
<div class="add_admin_form_field">
<select name="conversionFrom" id="conversionFrom" class="dropdown2">
<option value="USD"><spring:message code="USD" /></option>
<option value="INR"><spring:message code="INR" /></option>
</select> <input name="conversionFromValue" id="conversionFromValue"
type="text" class="textbox1" value="${conversion.conversionFromValue}" required />
</div>
<div class="add_admin_form_label">
<spring:message code="CONVERSION_TO" />
</div>
<div class="add_admin_form_field">
<select name="conversionTo" id="conversionTo" class="dropdown2">
<option value="INR"><spring:message code="INR" /></option>
<option value="USD"><spring:message code="USD" /></option>
</select> <input name="conversionToValue" id="conversionToValue" type="text"
class="textbox1" required />
</div>
<div class="add_admin_form_field">
<input type="button" value="" class="create"
onclick="SaveConversion()" />
</div>
</form>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
</body>
</html>
My hibernate.cfg.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated file - Do not edit! -->
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory>
<!-- User / Password -->
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- Database Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- for performance reasons changed to MyISAM from org.hibernate.dialect.MySQLInnoDBDialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/quotebuilder</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<!-- Database Scheme Auto Update -->
<property name="hbm2ddl.auto">update</property>
<!-- properties -->
<property name="show_sql">true</property>
<property name="use_outer_join">false</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- <property name="connection.provider_class ">org.hibernate.connection.C3P0ConnectionProvider</property> -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.generate_statistics">false</property>
<property name="hibernate.cache.use_structured_entries">false</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.timeout">100</property>
<!-- mapping files -->
<mapping class="model.User" />
<mapping class="model.Quotation" />
<mapping class="model.CustomerSize" />
<mapping class="model.CustomerSegment" />
<mapping class="model.Admin" />
<mapping class="model.Customer" />
<mapping class="model.CustomerTypeDiscount" />
<mapping class="model.EmployeeLevelDiscount" />
<mapping class="model.Product" />
<mapping class="model.ProductVolumeDiscount" />
<mapping class="model.TitleAuthorTag" />
<mapping class="model.TitleContentTag" />
<mapping class="model.Conversion" />
</session-factory>
</hibernate-configuration>
Dispatcher-servlet is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="login" class="controller.LoginController" />
<bean id="levelManagement" class="controller.LevelManagementController" />
<bean id="user" class="controller.UserController" />
<bean id="home" class="controller.HomeController" />
<bean id="report" class="controller.ReportController" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="WEB-INF/properties/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml is:
<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>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
pom.xml is:
<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.logiquebrain</groupId>
<artifactId>QuoteBuilderAdmin</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>QuoteBuilderAdmin 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-webmvc</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- Hibernate core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- optional -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-osgi</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-proxool</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-infinispan</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- Add on 03-12-2015 -->
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</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</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> <dependency>
<groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId>
<version>2.5.1</version> </dependency> -->
<!-- Add on 03-12-2015 -->
<!-- Add on 04-12-2015 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<!-- Add on 04-12-2015 -->
<!-- Add on 07-12-2015 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<!-- Add on 07-12-2015 -->
</dependencies>
<build>
<finalName>QuoteBuilderAdmin</finalName>
<!-- Add on 07-12-2015 -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<!-- Add on 07-12-2015 -->
</build>
</project>
do the changes as mentioned by #alan and also make following changes to your js function:
function SaveConversion() {
var params = $("#Conversion_form").serialize();
alert(params);
$.ajax({
method : "POST",
url : "saveConversion",
data : params, //this line is changed
success : function(result) {
alert(result);
$("#responseDiv").html(result);
messageDisplay();
return false;
}
})
}
the js function as per the question was sending only one parameter "param" which had value of serialized form value. After making above change it should be working. I have verified the same using network tab of the browser. You can see it for yourself if needed.
If you want to Spring to automatically bind the submitted parameters to a Conversion instance then you need to use the #ModelAttribute annotation in your method signature.
#RequestMapping("/saveConversion")
public ModelAndView saveConversion(#ModelAttribute Conversion conversion, Model model) throws ServletException, IOException, ParseException {
System.out.println("In saveConversion");
Boolean boolean1 = serviceDao.setConversion(conversion);
if (boolean1) {
model.addAttribute("conversionSaved", "Conversion saved successfully!");
} else {
model.addAttribute("conversionSaved", "Conversion Not saved!");
}
return new ModelAndView("setConversion");
}
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args
An #ModelAttribute on a method argument indicates the argument should
be retrieved from the model. If not present in the model, the argument
should be instantiated first and then added to the model. Once present
in the model, the argument’s fields should be populated from all
request parameters that have matching names. This is known as data
binding in Spring MVC, a very useful mechanism that saves you from
having to parse each form field individually.

Values are getting deleted from the database when the application is run again

I have a made a sample application in Spring + Hibernate + ZK framework.
In the Hibernate configuration file I have kept the property hbm2ddl.auto in "update" mode. Still Whenever I run the application again I dont get the values persisted earlier.
Following are several configuration files for reference:
BeanLocations.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- Auto scan the components -->
<context:component-scan
base-package="com.nagarro" />
</beans>
DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- <property name="hibernate.current_session_context_class" value = "${hibernate.current_session_context_class}" /> -->
</bean>
</beans>
Hibernate.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.nagarro.model.ItemAttribute</value>
<value>com.nagarro.model.ItemAttributeGroup</value>
</list>
</property>
</bean>
</beans>
Controller/ Viewmodel class
public class ItemAttributeRenderer {
/*
* The Logger reference variable used for Logging.
*/
static private final Logger LOG = LoggerFactory.getLogger(ItemAttributeRenderer.class);
#Autowired
private ItemAttributeService itemAttrService;
private List<ItemAttribute> itemList = new ArrayList<ItemAttribute>();
private void prepareAndSaveItemAttributeData(){
ItemAttribute item = null;
int counter;
for(int index = 0; index < 5; index++){
counter = index+1;
item = new ItemAttribute("Item "+counter, "Attirbute Value"+counter, "Qualifier Value"+counter);
itemAttrService.save(item);
}
}
/**
* #return the itemList
*/
public List<ItemAttribute> getItemList() {
ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring/config/BeanLocations.xml");
itemAttrService = (ItemAttributeService)appContext.getBean("itemAttrService");
prepareAndSaveItemAttributeData();
itemList = itemAttrService.getItemAttributeList();
return itemList;
}
#Command
public void save(){
for(ItemAttribute item : itemList){
itemAttrService.update(item);
}
}
/**
* #param itemList the itemList to set
*/
public void setItemList(List<ItemAttribute> itemList) {
this.itemList = itemList;
}
/**
* #return the itemAttrService
*/
public ItemAttributeService getItemAttrService() {
return itemAttrService;
}
/**
* #param itemAttrService the itemAttrService to set
*/
public void setItemAttrService(ItemAttributeService itemAttrService) {
this.itemAttrService = itemAttrService;
}
}
View file:
<?page title="Result"?>
<zk>
<custom-attributes center="${arg.center }" />
<window apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('com.nagarro.viewmodel.ItemAttributeRenderer')"
title="Result Window" border="normal">
<div>
<grid>
<rows>
<row>
<listbox model="#bind(vm.itemList)">
<listhead>
<listheader label="Item Name"
style="text-align:center;">
</listheader>
<listheader label="Attribute Value"
style="text-align:center;">
</listheader>
<listheader label="Qualifier Value"
style="text-align:center;">
</listheader>
</listhead>
<template name="model" var="item">
<listitem value="${item }">
<listcell label="#load(item.name)"
style="text-align:center;">
</listcell>
<listcell style="text-align:center;">
<textbox value="#bind(item.attributeValue)"
style="text-align:center;"/>
</listcell>
<listcell
label="#load(item.qualifierValue)"
style="text-align:center;">
</listcell>
</listitem>
</template>
</listbox>
</row>
</rows>
</grid>
</div>
<div style="text-align:right; padding:10px;">
<button label="Save" mold="trendy"
onClick="#command('save')">
</button>
</div>
</window>
</zk>
Service class
#Service("itemAttrService")
public class ItemAttributeServiceImpl implements ItemAttributeService{
#Autowired
ItemAttributeDao itemAttrDao;
public void setItemAttrDao(ItemAttributeDao itemAttrDao) {
this.itemAttrDao = itemAttrDao;
}
public void save(ItemAttribute item){
itemAttrDao.save(item);
}
public void update(ItemAttribute item){
itemAttrDao.update(item);
}
public void delete(ItemAttribute item){
itemAttrDao.delete(item);
}
public ItemAttribute findByItemAttributeName(String name){
return itemAttrDao.findByItemAttributeName(name);
}
public List<ItemAttribute> getItemAttributeList(){
return itemAttrDao.getItemAttributeList();
}
}
DAO class
#Repository("itemAttrDao")
public class ItemAttributeDaoImpl extends CustomHibernateDaoSupport implements ItemAttributeDao {
public void save(ItemAttribute itemAttribute) {
getHibernateTemplate().save(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void update(ItemAttribute itemAttribute) {
getHibernateTemplate().update(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void delete(ItemAttribute itemAttribute) {
getHibernateTemplate().delete(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public ItemAttribute findByItemAttributeName(String name) {
List list = getHibernateTemplate().find("from ItemAttribute where name=?",name);
if(list == null){
}else if(list.isEmpty()){
}
return (ItemAttribute)list.get(0);
}
public List<ItemAttribute> getItemAttributeList() {
List<ItemAttribute> itemList = getHibernateTemplate().find("from ItemAttribute ");
return itemList;
}
}
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.abc</groupId>
<artifactId>ZKSpringHibernateExample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringHibernateExample</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>java.net</id>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<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-tx</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</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- Hibernate library dependecy start -->
<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>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- Hibernate library dependecy end -->
<!-- ZK Dependency start -->
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>6.0.0</version>
</dependency>
<!-- ZK Dependency Ends -->
</dependencies>
</project>
My problem is When I run the application again all the data that was saved earlier vanishes even though I have set the hbm2ddl.auto property to update mode.
I have set my show_sql property as "true" to check the queries that are getting fired but there are no delete queries which are getting fired.
Is there any other important thing that I am missing here.
See comments and read Hibernate manual here
<property name="hbm2ddl.auto">update</property>
setting above property Drop and re-create the database schema on startup
consider below comments from hibernate manual.
Hibernate's automatic session management for persistence contexts is particularly useful in this context. The hbm2ddl.auto option turns on automatic generation of database schemas directly into the database. This can also be turned off by removing the configuration option, or redirected to a file with the help of the SchemaExport Ant task.
hbm2ddl.auto is for the validation of the database schema, which doesn't have any meaning here.
You have to commit your values, if not they are not permanently stored in the database.
I found the solution. there were a lot of messy project dependencies in my Tomcat so I deleted that instance of Tomcat and reconfigured it for my project. Then I cleaned my project and now everything is working fine as it should be. Thanks for taking time to post the answers.

Categories

Resources