Spring MVC - nested exception is java.lang.RuntimeException: org.postgresql.util.PSQLException: ERROR: relation "userid" does not exist - postgresql

I am making a simple spring MVC application that takes data from a view and sends it to a PostgreSQL database on my machine. I have been following tutorials and am not completely familiar with the bean configuration style of handling connection settings in the Data Access Objects. The error that returns when I attempt to post to the database is as follows:
HTTP Status 500 - Request processing failed; nested exception is java.lang.RuntimeException: org.postgresql.util.PSQLException: ERROR: relation "userid" does not exist
"userid" is my simple postgre table I'm using for testing.
My spring bean configuration file is this:
<?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.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="kittens" />
</bean>
This is the DAO handling the connection to the DB:
package com.ARSmvcTest.dao.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.ARSmvcTest.dao.arsDAO;
import com.ARSmvcTest.models.ARS;
public class JDBCarsDAO implements arsDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(ARS ars){
String sql = "INSERT INTO UserID " +
"(ID_, First_, Last_, Email_, Pwd_) VALUES (?, ?, ?, ?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, ars.getID_());
ps.setString(2, ars.getFirst_());
ps.setString(3, ars.getLast_());
ps.setString(5, ars.getPwd_());
ps.setString(4, ars.getEmail_());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
// FIND ARS BY ID WILL GO HERE EVENTUALLY
}
The spring bean is passing data to the connection successfully as evidenced by this screenshot below:
http://i.imgur.com/Hb7O5Qi.png (apologies, new user and can't embed images)
Despite the dataSource object receiving connection properties from my above spring bean, I notice that the ConnectionProperties field is still null.
Is this what is causing my exception on the Insert attempt?
Lastly I will include a screenshot of the Exception and stack being displayed in browser at the moment of failure:
http://i.imgur.com/prj1HtY.png (apologies, can't embed images)

this exception is directly triggered from the database(-driver).
It tells you that the table named "userid" is not existing.
Please check:
the table name on database and your insert-statement
if the table is read and writabled for the user you use for your connection; you need to have grated the correct right to be able to see and write to the table
I hope this will help you as this seems to be the typical error for this kind of exception.

Related

Liberty class loading issues or problem with hibernate (migrating tomcat app on liberty)?

i have to deploy a multi-module application in ear on Liberty Server 20 in my Eclipse. This application use hibernate as provider jpa2 and Derby client + driver derby-10.12.1.1.jar(as shared fileset). Persistence.xml is configured with non jta.
This is server.xml:
<enterpriseApplication id="rubrica-ear" location="rubrica-ear.ear" name="rubrica-ear"/>
<dataSource jndiName="jdbc/TestappDS" type="javax.sql.ConnectionPoolDataSource">
<properties.derby.client createDatabase="false" databaseName=".rubrica"></properties.derby.client>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared"></fileset>
</library>
</jdbcDriver>
</dataSource>
My .rubrica db location is in /usr/home.
Because I dont want to start a server derby on console but automatically, i do taht in a #WebListener class:
#WebListener
public class ReqListener implements ServletContextListener {
static final Logger log = LoggerFactory.getLogger(ReqListener.class);
PrintWriter pw = new PrintWriter(System.out);
private NetworkServerControl derbyserver;
#Override
public void contextInitialized(ServletContextEvent arg0) {
try {
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.rubrica";
// Set the db system directory and startup Server Derby for incoming connections.
System.setProperty("derby.system.home", systemDir);//il db viene salvato qui
derbyserver = new NetworkServerControl(InetAddress.getByName("localhost"), 1527);
derbyserver.start(pw);
log.info("Apache derby settings ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (derbyserver!=null){
...
}
}
When i deploy i get this error
[ERROR] An error occurred in the org.hibernate.ejb.HibernatePersistence persistence provider when attempting to create the entity manager factory of the testapp persistence unit container. The following error occurred: java.lang.NullPointerException
at org.hibernate.engine.jdbc.spi.TypeInfo.extractTypeInfo(TypeInfo.java:128)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:163)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:67)
at com.ibm.ws.jpa.management.JPAPUnitInfo.createEMFactory(JPAPUnitInfo.java:919)
at [internal classes]
When I debug on Liberty i see that Hibernate classes running before the #WebListener code (this is not the same thing in Tomcat), how can i resolve this issue? Something about class loading settings?
I try derby Embedded instead, but problem still araise again, in server.xml:
<properties.derby.embedded createDatabase="create" databaseName="C:/Users/myuser/.rubrica" shutdownDatabase="false"/>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared-libs"/>
</library>
</jdbcDriver>
Thanks
Roberto

MyBatis issue: Unrecognized jdbcType

While trying to convert my app from using MyBatis [it was iBatis before], I've been getting the following error, in spite of trying to make so many different kinds of changes to the code: What am I doing wrong? Any help would be really really really great!!!
Error message:
`Caused by: org.springframework.jdbc.UncategorizedSQLException: ### Error querying database. Cause: com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null
`
`### The error may exist in Path-to-XML-File.XML`
`### The error may involve namespace.resultMap-name`
`### The error occurred while executing a query`
`### SQL: {call name-of-stored-proc(?)}`
`### Cause: com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null`
`; uncategorized SQLException for SQL []; SQL state [null]; error code [-4228]; [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null; nested exception is com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null`
XML File: `
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Namespace-name">
<resultMap id="retrieveReports-results" type="Folder-structure-to-Java-file" autoMapping="true">
<result property="name" column="REPORT_NAME"/>
<result property="location" column="REPORT_DIRECTORY"/>
<result property="key" column="REPORT_KEY"/>
<result property="executable" column="EXECUTABLE"/>
<result property="commandLine" column="COMMAND_LINE"/>
<result property="commandLineFormat" column="COMMAND_LINE_FORMAT"/>
</resultMap>
<select id="retrieveReports" resultType="java.util.Map" statementType="CALLABLE">
{call prc_sel_reports(#{reports,jdbcType=CURSOR,javaType=java.sql.ResultSet,mode=OUT,resultMap=retrieveReports-results})}
</select>
</mapper>`
Java code:
try {
List < Report > reports = super.getSqlSession().selectList("retrieveReports");
if(log.isDebugEnabled()){
log.debug("Retrieved " + reports.size() + " reports, in method: retrieveReports()");
}
return reports;
// Attempt to catch different kinds of exceptions.
} catch (Exception e) {
throw new RuntimeException("Exception caught while trying to retrieve reports", e);
}
You have to specify a parameterType in the select statement, either map or custom class. An instance has to be passed on statement invocation.
resultType is not used, then irrelevant.
Procedure actually writes in a field of the "input" parameter passed to mybatis statement, and the statement does not return anything.
Mapper interface would be: void retrieveReports(Map<String, Object> params);
And your call:
Map<String, Object> params = new HashMap<String, Object>();
session.selectList("retrieveReports", params);
List<Report> reports = (List<Report>)params.get("reports");
Param may also be a custom type with property private List<Report> reports;.

Table/View does not exist in JavaEE web app deployed on Glassfish

I tried to deploy a JavaEE Web app with JPA persistence on a Glassfish server I installed on an Amazon EC2 instance. Everything worked fine for the deployment and for web pages rendering in my browser, but when I try to use persistence the result is the error "Table/View 'ATHLETE' does not exist'.
This is the first time I try to develop a web app with JPA and I'm trying to create a skeleton to use in the future for we app, but I think I'm missing a fundamental part. Also, using #GeneratedValue for the #Id I get a SEQUENCE table missing error. I'm afraid the two problems are related
The Athlete.java
package com.storassa.javaee.scuolesci;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
#Entity
#NamedQuery(name = "findAllAthletes", query = "SELECT b FROM Athlete b")
public class Athlete {
static int idRaw; // I use this to avoid the #GeneratedValue issue
#Id
int id;
String name, surname;
int birth;
public Athlete () {
idRaw++;
id = idRaw;
}
<getters and setters>
}
The AthleteEjb.java
package com.storassa.javaee.scuolesci;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Startup;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.annotation.sql.*;
#LocalBean
#Stateless
public class AthleteEJB {
#PersistenceContext(unitName="scuoleSciPU")
private EntityManager em;
public List<Athlete> findAthlete() {
Query query = em.createNamedQuery("findAllAthletes");
return query.getResultList();
}
public Athlete createAthlete(Athlete athlete) {
em.persist(athlete);
return athlete;
}
}
The persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="2.1">
<persistence-unit name="scuoleSciPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.storassa.javaee.scuolesci.Athlete</class>
<properties>
<property name="eclipselink.target-database" value="DERBY" />
<property name="eclipselink.jdbc.driver"
value="org.apache.derby.jdbc.ClientDriver" />
<property name="eclipselink.jdbc.url"
value="jdbc:derby://localhost:1527;create=true" />
<property name="eclipselink.jdbc.user" value="APP" />
<property name="eclipselink.jdbc.password" value="APP" />
<property name="eclipselink.ddl-generation" value=" drop-and-create-tables" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.deploy-on-startup" value="true" />
</properties>
</persistence-unit>
</persistence>
The error returned on the browser
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.ejb.EJBException: Transaction aborted
root cause
javax.faces.el.EvaluationException: javax.ejb.EJBException: Transaction aborted
root cause
javax.ejb.EJBException: Transaction aborted
root cause
javax.transaction.RollbackException: Transaction marked for rollback.
root cause
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
Error Code: -20001
Call: INSERT INTO ATHLETE (ID, BIRTH, NAME, SURNAME) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(com.storassa.javaee.scuolesci.Athlete#65fd5648)
root cause
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
Error Code: -20001
Call: INSERT INTO ATHLETE (ID, BIRTH, NAME, SURNAME) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(com.storassa.javaee.scuolesci.Athlete#65fd5648)
root cause
java.sql.SQLSyntaxErrorException: Table/View 'ATHLETE' does not exist.
root cause
org.apache.derby.client.am.SqlException: Table/View 'ATHLETE' does not exist.
I don't provide web-related resource/classes as I don't think they can be useful. In case let me know.
Should the table ATHLETE be created due to the #Entity annotation and the ?
I guess the problem is related to leading space in eclipselink.ddl-generation value. In other words try to replace:
<property name="eclipselink.ddl-generation" value=" drop-and-create-tables" />
with
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

JTA not rolling back when deleting cascade fails

Using: Glassfish 3.1.2, EclipseLink.
I have the following three-classes JPA model:
#Entity public class Customer implements Serializable {
#Id private Integer id;
#OneToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, orphanRemoval=true)
private Person person;
[...]
#Entity public class Person implements Serializable {
#Id private Integer id;
[...]
#Entity public class Request implements Serializable {
#Id private Integer id;
#ManyToOne private Person person;
I try to remove a customer with the following strategy (using CMT):
<persistence version="2.0" 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">
<persistence-unit name="MyPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.session" value="false"/>
<property name="eclipselink.logging.thread" value="false"/>
</properties>
</persistence-unit>
[...]
#PersistenceContext(unitName="MyPU")
private EntityManager entityManager;
#Resource private SessionContext context;
[...]
public void delete(Entity object) {
try{
object = this.getEntityManager().merge(object);
this.getEntityManager().remove(object);
} catch (Exception e){
this.context.setRollbackOnly();
}
}
When the Customer object is attached to a Person object that is attached to a Request, the delete cascade of Person fails causing the transaction to rollback, but the Customer is deleted from the database. I receive the following error:
INFO: [EL Fine]: 2012-12-28 10:53:38.1--Connection(27132168)--DELETE FROM CUSTOMER WHERE (ID = ?)
bind => [97]
INFO: [EL Fine]: 2012-12-28 10:53:38.125--Connection(27132168)--DELETE FROM PERSON WHERE (ID = ?)
bind => [111]
INFO: [EL Fine]: 2012-12-28 10:53:38.126--SELECT 1
WARNING: DTX5014: Caught exception in beforeCompletion() callback:
Local Exception Stack:
INFO: [EL Warning]: 2012-12-28 10:53:38.127--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERRO: atualização ou exclusão em tabela "person" viola restrição de chave estrangeira "fk_request_person_id" em "request"
Detalhe: Chave (id)=(111) ainda é referenciada pela tabela "request".
Error Code: 0
Call: DELETE FROM PERSON WHERE (ID = ?)
bind => [111]
Query: DeleteObjectQuery(111)
[...]
SEVERE: javax.ejb.EJBException: Transaction aborted
[...]
So, how can i cancel the customer removal when the cascade deletion fails?
There are two things that possible may go wrong here.
The transaction boundaries are not correctly specified
Maybe due to this, your application server does not issue the BEGIN statement correctly. This would explain that Postgres has a problem, while Oracle does not (it implicitly starts a transaction). Make sure your service methods wear the correct annotations. If everything is fine, maybe
There is a problem with your datasource.
Is it a JTA compatible datasource? Does it use the correct driver for Postgres? Please post your config so that we can check out.
I found an interesting link that may help you as well. It is about Postgres staying in autocommit mode (although when using Spring):
http://archives.postgresql.org/pgsql-jdbc/2007-07/msg00115.php

How to run servlets in eclipse

i am new to eclipse environment. I downloaded eclipse helios and tomcat 6. I configured them properly. Now my job is to create servlet for some sign in form. I have been given some existing servlet file from my company. I just need to modify it. Could anybody tell me how to run my existing servlet file? How to connect the file with my mysql table?
Steps to create java web application:
1.Create new Dynamic Web Project
2.Copy existing servlet file to src folder
3.Create web.xml file in WebContent/WEB-INF folder
4.Configure web.xml, for example:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.ru/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee http://java.sun.ru/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
replace test.HelloServlet by your servlet class, servlet name also may be replaced
5.Open Server view in Eclipse, add new Tomcat Server using context menu, publish the project and run server.
From your question, I'm guessing you need a way of connecting a servlet to a MySQL database. If that is the case, then below are the steps:
Use the MySQL jdbc driver for making the connection. You can download the jdbc driver for MySQL from here and then put the driver jar file into the classpath.
You need to create the table in MySQL database and then connect it through JDBC to show all the records present there. Below is the structure:
CREATE TABLE `servlet` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(256) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*Data for the table `servlet` */
insert into `servlet`(`id`,`name`) values (1,'sandeep'),(2,'amit'),(3,'anusmita'), (4,'vineet');
Create the servlet and connect to the database:
// *DataBase Connectivity from the Servlet.
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("Servlet JDBC");
out.println("");
out.println(" Servlet JDBC");
out.println("");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://192.168.10.59:3306/example","root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM servlet");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
I think you get the idea by now.