Restful with Spring, Hibernate, Maven, Postgresql and Wildfly - Createcriteria

Asked

Viewed 195 times

2

I am doing a Restful project with the following frameworks and am going through a problem, I created a User class to relate to the database, then I created the userDao to carry out the CRUD methods and then created the Userdaoimpl to implement the Userdao interface, but I used the Createcriteria method, but I don’t want to use this method but the Entitymanager, does anyone know how I can make the exchange in my project? (I am using Postman to perform the insertion of the data in the postgresql database).

Project Photo

Foto do Projeto

User.Java

package com.restfulproject.crud.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="\"users\"")
public class User implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = -4986635240092422790L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String firstname;
private String lastname;
private String address;


public User() {
    super();
    // TODO Auto-generated constructor stub
}



public User(String firstname, String lastname, String address) {
    super();
    this.firstname = firstname;
    this.lastname = lastname;
    this.address = address;
}



public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

}

Userdao.Java

package com.restfulproject.crud.dao;

import java.util.List;

import com.restfulproject.crud.model.User;

public interface UserDao {

  public String addUSer(User user);

  public String updateUser(User user);

  public String deleteUser(User user);

  public List<User> getAllUsers();

}

Userdaoimpl.Java

    package com.restfulproject.crud.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.restfulproject.crud.model.User;

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private SessionFactory factory;

    @Override
    public String addUSer(User user) {
        getSession().save(user);
        return "Usuário adicionado com sucesso!";
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> getAllUsers() {
        return getSession().createCriteria(User.class).list();
    }

    @Override
    public String updateUser(User user) {
        getSession().update(user);
        return "Alterado com sucesso";
    }

    @Override
    public String deleteUser(User user) {
        getSession().delete(user);
        return "Deletado com sucesso";
    }

    private Session getSession() {
        Session session = null;
        try {
            session = factory.getCurrentSession();
        } catch(HibernateException ex) {
            session = factory.openSession();
        }
        return session;
    }
}

application-context.xml

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.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/test_db" />
        <property name="username" value="postgres" />
        <property name="password" value="123456" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.restfulproject.crud.model.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernet.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

springRest-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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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 http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <context:component-scan base-package="com.restfulproject.crud.*"></context:component-scan>
    <mvc:annotation-driven/>
    <tx:annotation-driven/>

</beans>

web xml.

    <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">
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
    <display-name>Spring Rest Application</display-name>
    <servlet>
        <servlet-name>springRest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>springRest</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

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.restfulproject.crud</groupId>
<artifactId>user-crud</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>user-crud Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.3.0.Final</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.4-1205-jdbc42</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>



</dependencies>
<build>
    <finalName>user-crud</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

1 answer

1


Try changing your application-context.xml file to use JPA implementation:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

       <bean id="myEmf"
         class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
           <property name="dataSource" ref="dataSource" />
           <property name="packagesToScan" value="seu.pacote.de.entidades.aqui" />
           <property name="jpaVendorAdapter">
               <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
           </property>
           <property name="jpaProperties">
              <props>
                 <prop key="hibernate.hbm2ddl.auto">update</prop>
                 <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                 <prop key="hibernet.show_sql">true</prop>
              </props>
           </property>
       </bean>

    <bean id="dataSource"
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.postgresql.Driver" />
      <property name="url" value="jdbc:postgresql://localhost:5432/test_db" />
      <property name="username" value="postgres" />
      <property name="password" value="123456" />
    </bean>

       <bean id="transactionManager"
         class="org.springframework.orm.jpa.JpaTransactionManager">
           <property name="entityManagerFactory" ref="myEmf" />
       </bean>
       <tx:annotation-driven />

       <bean id="persistenceExceptionTranslationPostProcessor" class=
         "org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    </beans>

And in your class Userdaoimpl.Java use Entitymanager itself.

@PersistenceContext
private EntityManager manager;

...

    @Override
    public String addUSer(User user) {
        manager.persist(user);
        return "Usuário adicionado com sucesso!";
    }

And add in your pom the dependency of Entity manager:

<dependency> 
  <groupId>org.hibernate</groupId> 
  <artifactId>hibernate-entitymanager</artifactId> 
  <version>4.3.6.Final</version> 
</dependency>
  • How do I add one more entity??

  • @A.Carlos this configuration here <property name="packagesToScan" value="br.com.nomedoprojeto.entidades" /> all classes within this package will be scanned by JPA. In this case just change the value attribute to according to your project

  • When I made this modification gave error saying that you cannot create the bean with that name

  • You can post a brief description of the error here. vlw

  • Context initialization failed: org.springframework.Beans.factory.Beancreationexception: Error Creating bean with name 'myEmf' defined in Servletcontext Resource [/WEB-INF/application-context.xml]: Cannot create inner bean 'org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#44ca202f' of type [org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter] while setting bean property 'jpaVendorAdapter'; nested Exception is org.springframework.Beans.factory.Beancreationexception: Error Creating bean with name 'org.springframework.Orm.jpa.vendor.Hibernatejpavendopter#44ca202f' defi

  • I believe the dependency of Hibernate Entity manager is missing. <dependency>&#xA; <groupId>org.hibernate</groupId>&#xA; <artifactId>hibernate-entitymanager</artifactId>&#xA; <version>4.3.6.Final</version>&#xA;</dependency>&#xA;&#xA;Adicione no seu pom.&#xA;

  • I’ve created a new contact class, but I’m having trouble connecting it to the bank

  • @A.Carlos Your entities need to stay within this package: com.restfulproject.crud.model and the property <property name="packagesToScan" ... must have value configured for the same package of its entities: value="com.restfulproject.crud.model" />

  • I put, but still not thinking and now the user class does not return any user

  • @A.Carlos So let’s take parts. Your initial question was to use Enitymanger and configure it in the project. If answered, please mark as completed and create a new question with this question.

  • Okay, thanks for the tip!

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.