Spring Data JPA with Java configuration - vulabvulab

Posted on 01 October 2015 by VPhani

Spring Data JPA with Java configuration

STEP ONE: Create New Dynamic Web Project In Eclipse IDE

We are creating a web project as we ultimately want to build a REST web service also. REST web service will use the Spring Data JPA layer to work with the database.

You will need JDK 7 or JDK 8 installed on your machine. You can get JDK 8 here.

If you do not have eclipse IDE, you can download Eclipse IDE for Java Developers from Eclipse.org/downloads page.

You will need Java or JEE web server or application server on your machine. You can use either tomcat 8 or JBoss server. Please download tomcat 8 from here. You can either download the 64 bit zip or 32 bit zip file from under the heading Core. Please unzip Tomcat 8 zip to a folder called C:/tomcat-8

Start Eclipse IDE. Please create a Dynamic Web Project using the menu.

 

Dynamic Web Project

Configure the project above to use your tomcat-8 located on your machine. Click Finish to compete creating a Dynamic Web Project.

STEP TWO: Convert the Dynamic Web  Project to add Maven capability

Right click on your project in eclipse and click on Configure and choose the option of Convert to Maven Project.

ConvertToMavenProject

Your project will be added with a file called pom.xml using which you can specify all your third party libraries.

STEP THREE: Create a New Data Model using MySQL Work Bench

Please install MySQL database on your machine and star the database. You can install mysql from this location.

Also please download and install MySQL Work bench on your machine. You can also download the mysql workbench from this location.

Start your MySQL Workbench. Create a new connection to your database.

Add new schema name “tomproject”

  1. Create a table called tomuser with Customer Id , FirstName, LastName and ProfilePicture entity.
  2. mysql
  3. Create package com.vulab.domain in Project .
  4. Create Customer domain object manually or using Hibernate tool
  5. package com.vulab.domain;import static javax.persistence.GenerationType.IDENTITY;import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.UniqueConstraint;@Entity
    @Table(name = “tomuser”, catalog = “tomproject”, uniqueConstraints = { @UniqueConstraint(columnNames = “email”) })
    public class Customer implements java.io.Serializable {/**
    *
    */
    private static final long serialVersionUID = 1L;
    private int customerId;
    private String firstname;
    private String lastName;
    private String email;public Customer() {
    }@Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = “customer_id”, unique = true, nullable = false)
    public int getCustomerId() {
    return customerId;
    }public void setCustomerId(int customerId) {
    this.customerId = customerId;
    }@Column(name = “first_name”)
    public String getFirstname() {
    return firstname;
    }

    public void setFirstname(String firstname) {
    this.firstname = firstname;
    }

    @Column(name = “last_name”)
    public String getLastName() {
    return lastName;
    }

    public void setLastName(String lastName) {
    this.lastName = lastName;
    }

    @Column(name = “email”)
    public String getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    }

  6. Create a package com.vulab.config and create a ConfigCustomer class to configure
    1. The datasource bean.
    2.  The entity manager factory bean.
    3. The transaction manager bean.
    4. Enable annotation-driven transaction management.
    5.  Spring Data JPA.
  7. package com.vulab.config;import java.util.Properties;import javax.persistence.EntityManagerFactory;import org.apache.tomcat.jdbc.pool.DataSource;
    import org.apache.tomcat.jdbc.pool.PoolProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
    @ComponentScan(“com.vulab”)
    @EnableJpaRepositories(basePackages = { “com.vulab.repositories” })
    @EnableTransactionManagement
    public class ConfigCustomer {@Bean(destroyMethod = “close”)
    DataSource dataSource() {PoolProperties p = new PoolProperties();
    p.setUrl(“jdbc:mysql://localhost:3306/tomproject”);
    p.setDriverClassName(“com.mysql.jdbc.Driver”);
    p.setUsername(“root”);
    p.setPassword(“”);
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery(“SELECT 1”);
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(10);
    p.setInitialSize(10);
    p.setMaxWait(10000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMinIdle(10);
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setJdbcInterceptors(“org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;”
    + “org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer”);
    DataSource datasource = new org.apache.tomcat.jdbc.pool.DataSource();
    datasource.setPoolProperties(p);return datasource;
    }@Bean
    public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setJpaProperties(buildHibernateProperties());
    factory.setPackagesToScan(“com.vulab.domain”);
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();

    return factory.getObject();
    }

    protected Properties buildHibernateProperties() {
    Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty(“hibernate.dialect”, “org.hibernate.dialect.MySQL5InnoDBDialect”);
    hibernateProperties.setProperty(“hibernate.show_sql”, “true”);
    hibernateProperties.setProperty(“hibernate.use_sql_comments”, “false”);
    hibernateProperties.setProperty(“hibernate.format_sql”, “false”);
    hibernateProperties.setProperty(“hibernate.hbm2ddl.auto”, “update”);

    hibernateProperties.setProperty(“hibernate.generate_statistics”, “false”);

    hibernateProperties.setProperty(“javax.persistence.validation.mode”, “none”);

    // Audit History flags
    // hibernateProperties.setProperty(“org.hibernate.envers.store_data_at_delete”,
    // “true”);
    // hibernateProperties.setProperty(“org.hibernate.envers.global_with_modified_flag”,
    // “true”);

    return hibernateProperties;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
    }

    }

  8. Create a package com.vulab.repositories and create a CustomerRepository class that extends Spring data JPA interface.
  9. package com.vulab.repositories;import java.util.List;import org.springframework.data.jpa.repository.JpaRepository;import com.vulab.domain.Customer;public interface CustomerRepository extends JpaRepository<Customer, Integer>{public List<Customer> getCustomerByEmailAndFirstName(String email, String firstName);}
  10. Create a folder Test and write Junit test case to test.
  11. import javax.transaction.Transactional;import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.context.transaction.TransactionConfiguration;import com.vulab.config.ConfigCustomer;
    import com.vulab.domain.Customer;
    import com.vulab.repositories.CustomerRepository;@RunWith(SpringJUnit4ClassRunner.class)
    @Transactional
    @ContextConfiguration(classes = ConfigCustomer.class)
    @TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)
    public class Customerrepotestcase {
    @Autowired
    CustomerRepository customerRepository;@Test
    public void testSaveCustomer() {
    Customer customer = new Customer();
    customer.setEmail(“phany@vulab.com”);
    customer.setFirstname(“Phani”);
    customer.setLastName(“gv”);customerRepository.save(customer);
    org.junit.Assert.assertTrue(customer.getCustomerId() > 0);
    }}
  12. pom.xml configuration for adding all depedencies
  13. <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>CustomerProject</groupId>
    <artifactId>CustomerProject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies><dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>8.0.26</version>
    </dependency><!– Apache CXF Dependencies –>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>2.7.13</version>
    </dependency>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>2.7.13</version>
    </dependency>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http-jetty</artifactId>
    <version>2.7.13</version>
    </dependency>
    <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>2.7.13</version>
    </dependency>
    <!– Jackson The JSON Producer dependency –>
    <dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.0.1</version>
    </dependency>
    <!– Spring DATA JPA –>
    <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.9.0.RELEASE</version>
    </dependency><!– Hibernate Core dependency –>
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.11.Final</version>
    </dependency>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    </dependency><dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.3.11.Final</version>
    </dependency><dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>juli</artifactId>
    <version>6.0.26</version>
    </dependency>
    <!– Spring dependencies –>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.1.7.RELEASE</version>
    </dependency><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
    </dependency><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.7.RELEASE</version>
    </dependency>

    <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>dbcp</artifactId>
    <version>6.0.44</version>
    </dependency>

    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.36</version>
    </dependency>
    </dependencies>
    <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
    <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
    <warSourceDirectory>WebContent</warSourceDirectory>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
    </plugin>
    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
    <source>1.8</source>
    <target>1.8</target>
    </configuration>
    </plugin>
    </plugins>
    </build>
    </project>

0 Comments

Leave a Reply