Spring JPA – Java and Spring Examples http://localhost/wordpress Wed, 26 Jun 2019 15:04:13 +0000 fr-FR hourly 1 https://wordpress.org/?v=5.0.4 Example Spring 4 JPA – Data Access Exception Translating http://localhost/wordpress/2019/06/26/example-spring-4-jpa-data-access-exception-translating/ Wed, 26 Jun 2019 15:01:27 +0000 http://localhost/wordpress/?p=648 This example presents the basic concept of translating data access exceptions in Spring.

The technologies used are :

    – Spring 4.3.18
    – H2 1.3
    – Lombok 1.18
    – JDK 1.80
    – Maven 3.3.9

You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :

mvn eclipse:eclipse

Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).

<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>javaspringexamples.springJPA</groupId>
	<artifactId>springJPAExceptionTranslating</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.175</version>
		</dependency>
	</dependencies>
</project>

package javaspringexamples.springJPA.ExceptionTranslating;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Configuration
public class Conf {

	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("org.h2.Driver");
		dataSource.setUrl("jdbc:h2:tcp://localhost/~/javaspringexamples");
		dataSource.setUsername("sa");
		dataSource.setPassword("");
		return dataSource;
	}

	private Map<String, ?> jpaProperties() {
		Map<String, String> jpaPropertiesMap = new HashMap<String, String>();
		jpaPropertiesMap.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
		jpaPropertiesMap.put("hibernate.hbm2ddl.auto", "update");
		return jpaPropertiesMap;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
		factoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
		factoryBean.setDataSource(dataSource());
		factoryBean.setPackagesToScan("javaspringexamples.springJPA.ExceptionTranslating");
		factoryBean.setJpaPropertyMap(jpaProperties());
		return factoryBean;
	}

	@Bean
	public PersonDAO personDao() {
		PersonDAOImpl dao = new PersonDAOImpl();
		return dao;
	}

	@Bean
	public static PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
		PersistenceExceptionTranslationPostProcessor bean = new PersistenceExceptionTranslationPostProcessor();
		return bean;
	}

}

package javaspringexamples.springJPA.ExceptionTranslating;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.dao.DataAccessException;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Main {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Conf.class);

		PersonDAO dao = (PersonDAO) applicationContext.getBean("personDao");
		// Creating person object
		Person person = new Person();
		person.setFirstName(null);
		person.setLastName("KOLOBANE");

		// Spring handles different types of data access exceptions thrown from the data
		// access layer, and translates them into
		// org.springframework.dao.DataAccessException.
		try {
			// Saving person
			dao.save(person);
		} catch (DataAccessException dae) {
			System.out.println("Exception translated by Spring and handled");
		}
	}
}
package javaspringexamples.springJPA.ExceptionTranslating;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Person {

	@Id
	@GeneratedValue
	private Long id;

	@Basic(optional=false)
	private String firstName;

	private String lastName;

	public Long getId() {
		return 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;
	}
}

package javaspringexamples.springJPA.ExceptionTranslating;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public interface PersonDAO {
	public void save(Person p);
}

package javaspringexamples.springJPA.ExceptionTranslating;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

import org.springframework.stereotype.Repository;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */

@Repository
public class PersonDAOImpl implements PersonDAO {

	@PersistenceUnit
	private EntityManagerFactory emf;

	public void save(Person p) {
		EntityManager em = emf.createEntityManager();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		em.persist(p);
		transaction.commit();
		em.close();
	}
}

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 JPA – @PersistenceUnit http://localhost/wordpress/2019/06/26/example-spring-4-jpa-persistenceunit/ Wed, 26 Jun 2019 14:54:33 +0000 http://localhost/wordpress/?p=645 This example presents the basic concept of using PersistenceUnit in Spring.

The technologies used are :

    – Spring 4.3.18
    – H2 1.3
    – Lombok 1.18
    – JDK 1.80
    – Maven 3.3.9

You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :

mvn eclipse:eclipse

Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).

<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>javaspringexamples.springJPA</groupId>
	<artifactId>springJPAPersistenceUnit</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.175</version>
		</dependency>
	</dependencies>
</project>

package javaspringexamples.springJPA.PersistenceUnit;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

@Configuration
public class Conf {

	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("org.h2.Driver");
		dataSource.setUrl("jdbc:h2:tcp://localhost/~/javaspringexamples");
		dataSource.setUsername("sa");
		dataSource.setPassword("");
		return dataSource;
	}

	private Map<String, ?> jpaProperties() {
		Map<String, String> jpaPropertiesMap = new HashMap<String, String>();
		jpaPropertiesMap.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
		jpaPropertiesMap.put("hibernate.hbm2ddl.auto", "update");
		return jpaPropertiesMap;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
		factoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
		factoryBean.setDataSource(dataSource());
		factoryBean.setPackagesToScan("javaspringexamples.springJPA.PersistenceUnit");
		factoryBean.setJpaPropertyMap(jpaProperties());
		return factoryBean;
	}

	@Bean
	public PersonDAO personDao() {
		PersonDAOImpl dao = new PersonDAOImpl();
		return dao;
	}

}

package javaspringexamples.springJPA.PersistenceUnit;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Main {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Conf.class);

		PersonDAO dao = (PersonDAO) applicationContext.getBean("personDao");
		// Creating person object
		Person person = new Person();
		person.setFirstName("Jabane");
		person.setLastName("KOLOBANE");
		// Saving person
		dao.save(person);
	}
}
package javaspringexamples.springJPA.PersistenceUnit;

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

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Person {

	@Id
	@GeneratedValue
	private Long id;

	private String firstName;

	private String lastName;

	public Long getId() {
		return 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;
	}
}

package javaspringexamples.springJPA.PersistenceUnit;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public interface PersonDAO {
	public void save(Person p);
}

package javaspringexamples.springJPA.PersistenceUnit;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */

public class PersonDAOImpl implements PersonDAO {

	@PersistenceUnit
	private EntityManagerFactory emf;

	public void save(Person p) {
		EntityManager em = emf.createEntityManager();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		em.persist(p);
		transaction.commit();
		em.close();
	}
}

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 JPA – @PersistenceContext http://localhost/wordpress/2019/06/26/example-spring-4-jpa-persistencecontext/ Wed, 26 Jun 2019 14:50:35 +0000 http://localhost/wordpress/?p=643 This example presents the basic concept of using PersistenceContext in Spring.

The technologies used are :

    – Spring 4.3.18
    – H2 1.3
    – Lombok 1.18
    – JDK 1.80
    – Maven 3.3.9

You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :

mvn eclipse:eclipse

Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).

<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>javaspringexamples.springJPA</groupId>
	<artifactId>springJPAPersistenceContext</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.175</version>
		</dependency>
	</dependencies>
</project>

package javaspringexamples.springJPA.PersistenceContext;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Configuration
@EnableTransactionManagement
public class Conf {

	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("org.h2.Driver");
		dataSource.setUrl("jdbc:h2:tcp://localhost/~/javaspringexamples");
		dataSource.setUsername("sa");
		dataSource.setPassword("");
		return dataSource;
	}

	private Map<String, ?> jpaProperties() {
		Map<String, String> jpaPropertiesMap = new HashMap<String, String>();
		jpaPropertiesMap.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
		jpaPropertiesMap.put("hibernate.hbm2ddl.auto", "update");
		return jpaPropertiesMap;
	}

	@Bean
	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
		LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
		factoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
		factoryBean.setDataSource(dataSource());
		factoryBean.setPackagesToScan("javaspringexamples.springJPA.PersistenceContext");
		factoryBean.setJpaPropertyMap(jpaProperties());
		return factoryBean;
	}

	@Bean
	public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		transactionManager.setEntityManagerFactory(entityManagerFactory);
		return transactionManager;
	}

	@Bean
	public PersonDAO personDao() {
		PersonDAOImpl dao = new PersonDAOImpl();
		return dao;
	}

}

package javaspringexamples.springJPA.PersistenceContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Main {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Conf.class);

		PersonDAO dao = (PersonDAO) applicationContext.getBean("personDao");
		// Creating person object
		Person person = new Person();
		person.setFirstName("Jabane");
		person.setLastName("KOLOBANE");
		// Saving person
		dao.save(person);
	}
}
package javaspringexamples.springJPA.PersistenceContext;

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

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Person {

	@Id
	@GeneratedValue
	private Long id;

	private String firstName;

	private String lastName;

	public Long getId() {
		return 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;
	}
}

package javaspringexamples.springJPA.PersistenceContext;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public interface PersonDAO {
	public void save(Person p);
}

package javaspringexamples.springJPA.PersistenceContext;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */

@Transactional
public class PersonDAOImpl implements PersonDAO {

	@PersistenceContext
	private EntityManager entityManager;

	public void save(Person p) {
		//EntityTransaction transaction = entityManager.getTransaction();
		//transaction.begin();
		entityManager.persist(p);
		//transaction.commit();
		entityManager.close();
	}
}

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 JPA – JPQL Examples http://localhost/wordpress/2019/06/26/example-spring-4-jpa-jpql-examples/ Wed, 26 Jun 2019 14:46:53 +0000 http://localhost/wordpress/?p=641 This example presents the basic concept of using JPQL in Spring.

The technologies used are :

    – Spring 4.3.18
    – H2 1.3
    – Lombok 1.18
    – JDK 1.80
    – Maven 3.3.9

You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :

mvn eclipse:eclipse

Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).

<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>javaspringexamples.springJPA</groupId>
	<artifactId>springJPAQL</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.175</version>
		</dependency>
	</dependencies>
</project>

package javaspringexamples.springJPA.JPAQL;

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

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Car {
	@Id
	@GeneratedValue
	private Long id;

	private String model;

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public Long getId() {
		return id;
	}
}
package javaspringexamples.springJPA.JPAQL;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Main {

	public static void main(String[] args) {
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test-jpa");
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();

		transaction.begin();
		// Creating entities
		Person person = new Person();
		person.setFirstName("Jabane");
		person.setLastName("KOLOBANE");
		Car car1 = new Car();
		car1.setModel("R4");
		Car car2 = new Car();
		car2.setModel("R6");
		// Add cars into person's collection
		person.getCars().add(car1);
		person.getCars().add(car2);
		// persisting entities
		entityManager.persist(person);

		// SELECT
		Query query = entityManager.createQuery("Select p from Person p");
		List<Person> l_p = query.getResultList();
		for (Person p : l_p)
			System.out.println(p);

		// UPDATE
		query = entityManager.createQuery("Update Person set firstName = ?");
		query.setParameter(1, "waaaaaaaaaaa");
		query.executeUpdate();

		transaction.commit();
		entityManager.close();
	}
}

package javaspringexamples.springJPA.JPAQL;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Person {

	@Id
	@GeneratedValue
	private Long id;

	private String firstName;

	private String lastName;

	@OneToMany(cascade = CascadeType.ALL)
	@JoinColumn(name = "person_id")
	private Set<Car> cars = new HashSet<Car>();

	public Long getId() {
		return 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 Set<Car> getCars() {
		return cars;
	}

	@Override
	public String toString() {
		StringBuffer str = new StringBuffer(firstName + " " + lastName + " : ");
		for (Car c : cars)
			str.append("'" + c.getModel() + "' ");
		return str.toString();
	}
}

<?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="test-jpa" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.connection.driver_class" value="org.h2.Driver" />
            <property name="hibernate.connection.url" value="jdbc:h2:tcp://localhost/~/javaspringexamples" />
            <property name="hibernate.connection.username" value="sa" />
            <property name="hibernate.connection.password" value="" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
            <!-- property name="hibernate.hbm2ddl.auto" value="update" /-->
        </properties>
    </persistence-unit>
</persistence>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>
Example Spring 4 JPA – JPA CRUD Examples http://localhost/wordpress/2019/06/26/example-spring-4-jpa-jpa-crud-examples/ Wed, 26 Jun 2019 14:38:03 +0000 http://localhost/wordpress/?p=632 This example presents the basic concept of using JPA CRUD in Spring.

The technologies used are :

    – Spring 4.3.18
    – H2 1.3
    – Lombok 1.18
    – JDK 1.8
    – Maven 3.3.9

You can convert this example to an Eclipse IDE project by going to folder where is the pom.xml is, and use the command :

mvn eclipse:eclipse

Inspired from « Beginning Spring » Mert Caliskan, Kenan Sevindik, Rod Johnson (Foreword by), Jürgen Höller (Foreword by).

<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>javaspringexamples.springJPA</groupId>
	<artifactId>CRUD</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.18.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.1.Final</version>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.175</version>
		</dependency>
	</dependencies>
</project>

package javaspringexamples.springJPA.CRUD;

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

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Car {
	@Id
	@GeneratedValue
	private Long id;

	private String model;

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public Long getId() {
		return id;
	}
}
package javaspringexamples.springJPA.CRUD;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Main {

	public static void main(String[] args) {
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test-jpa");
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();

		transaction.begin();
		// Creating entities
		Person person = new Person();
		person.setFirstName("Jabane");
		person.setLastName("KOLOBANE");
		Car car1 = new Car();
		car1.setModel("R4");
		Car car2 = new Car();
		car2.setModel("R6");
		// Add cars into person's collection
		person.getCars().add(car1);
		person.getCars().add(car2);
		// persisting entities
		entityManager.persist(person);
		System.out.println(person);
		//detaching cars
		long id = person.getId();
		person.getCars().clear();
		System.out.println(person);
		// Delete person
		entityManager.remove(person);
		// find displays null
		person = entityManager.find(Person.class, id);
		System.out.println("Find : " + person);
		// getReference throws javax.persistence.EntityNotFoundException
		person = entityManager.getReference(Person.class, id);
		System.out.println("getReference: " + person);

		transaction.commit();
		entityManager.close();
	}
}

package javaspringexamples.springJPA.CRUD;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

/**
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
@Entity
public class Person {

	@Id
	@GeneratedValue
	private Long id;

	private String firstName;

	private String lastName;

	@OneToMany(cascade = CascadeType.ALL)
	@JoinColumn(name = "person_id")
	private Set<Car> cars = new HashSet<Car>();

	public Long getId() {
		return 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 Set<Car> getCars() {
		return cars;
	}

	@Override
	public String toString() {
		StringBuffer str = new StringBuffer(firstName + " " + lastName + " : ");
		for (Car c : cars)
			str.append("'" + c.getModel() + "' ");
		return str.toString();
	}
}

<?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="test-jpa" transaction-type="RESOURCE_LOCAL">
        <properties>
            <property name="hibernate.connection.driver_class" value="org.h2.Driver" />
            <property name="hibernate.connection.url" value="jdbc:h2:tcp://localhost/~/javaspringexamples" />
            <property name="hibernate.connection.username" value="sa" />
            <property name="hibernate.connection.password" value="" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
            <!-- property name="hibernate.hbm2ddl.auto" value="update" /-->
        </properties>
    </persistence-unit>
</persistence>

Get the sources of the example from the following GitHub url

Or Download a .zip file

]]>