Get result via PostgreSQL procedure using Hibernate - database

I am trying to get a value from a postgres database using a plpgsql function editor's note: OP had plsql but I am not able to retrieve the data.
I get the following exception:
Exception in thread "main" java.lang.UnsupportedOperationException:
org.hibernate.dialect.PostgreSQLDialect does not support resultsets
via stored procedures
My hibernate configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://192.168.1.100:54321/localDB</property>
<!-- <property name="hibernate.connection.url">jdbc:postgresql://192.168.1.100:54321/scprj</property>-->
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">dbserver</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My hibernate mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="callFunctionPack.DateBean" table="userlogin">
<id column="userid" name="userid">
<generator class="increment"/>
</id>
<property column="username" name="username" type="string"/>
<property column="password" name="password" type="string"/>
</class>
<sql-query name="getlogin" callable="true" comment="Call the getlogindata procedure">>
<return class="callFunctionPack.DateBean">
<return-property name="username" column="username"/>
<return-property name="password" column="password"/>
</return>
{ call getlogin(:userid) }
</sql-query>
</hibernate-mapping>
My main class function to the procedure:
public class Call {
public static void main(String... args) {
//select();
show();
}
public static void show() {
Query nQuery = getSession().getNamedQuery("getlogin").setParameter("userid", 1);
List results = nQuery.list();
for (Iterator it = results.iterator(); it.hasNext();) {
DateBean dateBean = (DateBean)it.next();
System.out.println(dateBean.getUsername());
System.out.println(dateBean.getPassword());
}
}
public static Session getSession() {
Session session = new Configuration().configure().buildSessionFactory().openSession();
return session;
}
}
My bean class:
public class DateBean {
private String date;
private int userid;
private String username;
private String password;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
My plpgsql function:
CREATE OR REPLACE FUNCTION getlogindata(numeric)
RETURNS refcursor AS
$BODY$
DECLARE
p_userid ALIAS FOR $1;
sql_stmt VARCHAR;
p_condition VARCHAR;
v_boolean BOOLEAN := false;
email_tracking_cursor REFCURSOR;
BEGIN
sql_stmt := 'SELECT USERNAME, PASSWORD FROM USERLOGIN WHERE USERID =' || p_userid;
raise notice '%',sql_stmt;
OPEN email_tracking_cursor FOR EXECUTE sql_stmt;
RETURN email_tracking_cursor;
END; $BODY$
LANGUAGE plpgsql VOLATILE;
ALTER FUNCTION getlogindata(numeric) OWNER TO postgres;

Your plpgsql function does not return a "value", but a cursor. This function does what you seem to want:
CREATE OR REPLACE FUNCTION getlogindata(numeric, OUT username text, OUT password text)
RETURNS record AS
$BODY$
SELECT u.username, u.password FROM userlogin u WHERE u.userid = $1;
$BODY$
LANGUAGE sql STABLE;
You could also use plain SQL for this simple query:
SELECT username, password FROM userlogin WHERE userid = $my_userid;

I don't know Hibernate very well, but you can change the function to be defined as "RETURNS TABLE" and then you can do a select * from getlogindata(42);.
Maybe Hibernate can work with that solution.

Related

JPA NamedQuery not found

I'm trying to get a list of persons using JPA. Every time I run the code, I get "java.lang.IllegalArgumentException: NamedQuery of name: Persoon.getAllePersonen not found."
I tried changing the table name, replaced Persoon.getAllePersonen by getAllePersonen,.... I just can't seem to figure out what's causing the error
Persoon
#Entity
#Table(name = "Persoon")
#NamedQueries({
#NamedQuery(name = "Persoon.getAllePersonen",
query = "SELECT p FROM Persoon p"),
#NamedQuery(name = "Persoon.findByName",
query = "SELECT p FROM Persoon p WHERE p.achternaam = :persoonNaam OR p.voornaam = :persoonNaam")
})
public class Persoon implements Serializable {
PersoonDao
public List<Persoon> getAlleLeden(){
TypedQuery<Persoon> queryP = em.createNamedQuery("Persoon.getAllePersonen", Persoon.class);
try{ return queryP.getResultList();
} catch (NoResultException e){
throw new EntityNotFoundException("Cannot find leden");
}
}
EDIT:
Generic Superclass DAO
public class GenericDaoJpa<T>{
private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("TaijitanPU");
protected static final EntityManager em = emf.createEntityManager();
Persistence.xml
<?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="TaijitanPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>domein.Persoon</class>
<class>domein.Graad</class>
<class>domein.Locatie</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost\sqlexpress:1433;databaseName=Taijitan;integratedSecurity=true;"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
You have to do an abstract class Generic class and override the entityManager of the parent class for each child. Check below. I used EJB Stateless for the childs.
-> PARENT DAO
public abstract class AbstractDAO<T> {
...
protected abstract EntityManager getEntityManager();
-> CHILD DAO
#PersistenceContext(unitName = "yourPersistenceUnitName")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}

An existing connection was forcibly closed by the remote host (com.microsoft.sqlserver.jdbc.SQLServerException) Exception

i am trying to save record in my sql server database using spring when i try to run the application i am getting org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: An existing connection was forcibly closed by the remote host ClientConnectionId:1a7dc54d-3764-44ff-ab47-8793b826b093
Employee.java
package com;
public class Employee {
private int id;
private String name;
private int 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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public Employee() {
}
public Employee(int id, String name, int salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
}
EmployeeDao.java
package com;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate=jdbcTemplate;
}
public int saveEmployee(Employee e){
String query="insert into employee 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);
}
}
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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDataSource"/>
<property name="url" value="jdbc:sqlserver://localhost:5432;databaseName=qm"/>
<property name="username" value="postgres"/>
<property name="password" value="mypass"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
and my App Test is
Test.java
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
int status=dao.saveEmployee(new Employee(102,"Amit",35));
System.out.println(status);
}
}

Objectify multiple filters doesn´t work

ow can I filter using multiple attributes? (simulating an "AND"
operation)
I have tried:
ofy().load().type(Produit.class).filter("idListe in",collectionProduits.getIdListes()).filter("supprime !=",true).list();
This is my entity:
#Entity
public class Produit implements Serializable{
private static final long serialVersionUID = xxxxxxxxxxxxxx;
#Id
private Long id;
#Index
private Long idliste;
#Index
private Boolean supprime;
public Produit() {
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getIdliste() {
return idliste;
}
public void setIdliste(Long idliste) {
this.idliste = idliste;
}
public Boolean getSupprime() {
return supprime;
}
public void setSupprime(Boolean supprime) {
this.supprime = supprime;
}
I have this critical error:
Uncaught exception from servlet java.io.IOException:
com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException:
no matching index found. The suggested index for this query is:
<datastore-index kind="Produit" ancestor="false" source="manual">
<property name="idliste" direction="asc"/>
<property name="supprime" direction="asc"/>
</datastore-index>
(through reference chain:
com.listecourses.model.CollectionProduits["produits"]) at
com.google.api.server.spi.response.ServletResponseResultWriter.writeValueAsString(ServletResponseResultWriter.java:187)
at
com.google.api.server.spi.response.ServletResponseResultWriter.write(ServletResponseResultWriter.java:74)
at
....
After seeing this error, I changed my datastore-indexes.xml to this:
<?xml version="1.0" encoding="utf-8"?>
<datastore-indexes autoGenerate="false">
<datastore-index kind="Produit" ancestor="false" source="manual">
<property name="idliste" direction="asc"/>
<property name="supprime" direction="asc"/>
</datastore-index>
</datastore-indexes>
I re-deployed after creating this file. I waited a little bit of time for the index to generate. And I have the same error on log of appengine.
more, I have this error log on eclipse:
No projects found for [C:\workspace\example-AppEngine\war\datastore-indexes.xml]

JPA not generating tables from entities

Here is some entity:
#Entity
public class Forest {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public Forest() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
I want to insert some element in table forest:
public class Main {
private static EntityManagerFactory emf =
Persistence.createEntityManagerFactory("server");
public static void main(String[] args) {
EntityManager em = emf.createEntityManager();
EntityTransaction trx = em.getTransaction();
Forest forest = new Forest();
trx.begin();
em.persist(forest);
trx.commit();
}
}
Thrown exception:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Table 'server.forest' doesn't exist
Caused by: org.hibernate.exception.SQLGrammarException: Table 'server.forest' doesn't exist
My persistence.xml file with settings:
<?xml version="1.0" encoding="UTF-8"?>
<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="server">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/server"/>
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
When I removed #GeneratedValue(strategy = GenerationType.AUTO) and set id for forest:
forest.setID(1), there was no exception and table has been generated. So, auto-generating of id is not working and I don't know why.
According configuration there is org.hibernate.dialect.HSQLDialect used with MySQL database. Using MySQL dialect instead of one of HSQL likely helps. Likely InnoDB is used - if so, then MySQL5InnoDBDialect is way to go.

mandatory request param in cxf

I developed a web service with CXF and It work fine.
I have a service with two input parameters and both of them should be mandatory.
but when I call my service just the first parameter is mandatory.
please let me know what should I do?
my SEI
#WebService(
endpointInterface = "com.myCompany.product.webService",
targetNamespace = "http://product.myCompany.com",
portName = "product",
serviceName = "ProductService")
#DataBinding(org.apache.cxf.aegis.databinding.AegisDatabinding.class)
public interface ProductService {
#WebMethod(operationName = "authentication")
#WebResult(name = "authenticationResponseParam")
public AuthenticationResponseParam authentication(#WebParam(name = "user", header = true) String user,
#WebParam(name = "authenticationRequestParam") AuthenticationRequestParam authenticationRequestParam);
}
and my AuthenticationResponseParam class
#XmlAccessorType(XmlAccessType.FIELD
)
#XmlType(name = "authenticationRequestParam", propOrder = {
"account", "password"
})
public class AuthenticationRequestParam implements Serializable {
#XmlElement(name = "account", required = true)
private BigDecimal account;
#XmlElement(name = "password", required = true)
private String password;
public BigDecimal getAccount() {
return account;
}
public void setAccount(BigDecimal account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "AuthenticationRequestParam{" +
"account=" + account +
", password='" + password + '\'' +
'}';
}
}
and my CXF 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:jaxws="http://cxf.apache.org/jaxws"
xmlns:cxf="http://cxf.apache.org/core"
xmlns:soap="http://cxf.apache.org/bindings/soap"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://cxf.apache.org/bindings/soap
http://cxf.apache.org/schemas/configuration/soap.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<cxf:bus>
<cxf:features>
<cxf:logging/>
</cxf:features>
</cxf:bus>
<!--Data binding-->
<bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding" scope="prototype"/>
<bean id="jaxws-and-aegis-service-factory"
class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean"
scope="prototype">
<property name="dataBinding" ref="aegisBean"/>
</bean>
<jaxws:endpoint id="telBank" implementor="#myService" address="/telBank">
<jaxws:binding>
<soap:soapBinding mtomEnabled="false" version="1.2"/>
</jaxws:binding>
</jaxws:endpoint>
<bean id="myService" class="com.myCompany.product.webService.impl.ProductServiceImpl"/>
</beans>
thank you
Hey guys
I added a new service in my web service
public BigDecimal sample(#WebParam(name = "sam1") BigDecimal a1,#WebParam(name = "sam2") BigDecimal a2);
and none of both parameters are mandatory
what should I do?please help me
I found what my problem.
I use org.apache.cxf.aegis.databinding.AegisDatabinding az data binder and it just recognize primitive type az mandatory.when I commend that my input param become mandatory.
what kind of data binder should I use?
If you want to use AegisDatabinding class as data binder,set this property it bean definition.
<bean id="aegisBean" class="org.apache.cxf.aegis.databinding.AegisDatabinding" scope="prototype">
<property name="configuration">
<bean class="org.apache.cxf.aegis.type.TypeCreationOptions">
<property name="defaultMinOccurs" value="1"/>
<property name="defaultNillable" value="false"/>
</bean>
</property>
</bean>

Resources