BAEL-2804 JPA Query Parameters Usage

This is the code behind JPA Query Parameters Usage tutorial. Within
these examples you can find the way to use named and positional query
parameters either using plain jpql or criteria queries.
This commit is contained in:
glopez 2019-06-13 22:53:57 -03:00
parent 7b0daba254
commit 11a41d5036
5 changed files with 251 additions and 0 deletions

View File

@ -19,6 +19,11 @@
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@ -47,6 +52,58 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<version>3.3.3</version>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<outputDirectory>target/metamodel</outputDirectory>
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>target/metamodel</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<hibernate.version>5.4.0.Final</hibernate.version>
<eclipselink.version>2.7.4-RC1</eclipselink.version>

View File

@ -0,0 +1,80 @@
package com.baeldung.jpa.queryparams;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employees")
public class Employee {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "employee_number", unique = true)
private String empNumber;
@Column(name = "employee_name")
private String name;
@Column(name = "employee_age")
private int age;
public Employee() {
super();
}
public Employee(Long id, String empNumber) {
super();
this.id = id;
this.empNumber = empNumber;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

View File

@ -224,4 +224,26 @@
value="products_jpa.sql" />
</properties>
</persistence-unit>
<persistence-unit name="jpa-h2-queryparams" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.queryparams.Employee</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
<property name="javax.persistence.sql-load-script-source"
value="employees2.sql" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1,90 @@
package com.baeldung.jpa.queryparams;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* JPAQueryParamsTest class tests.
*
* @author gmlopez.mackinnon@gmail.com
*/
public class JPAQueryParamsUnitTest {
private static EntityManager entityManager;
@BeforeClass
public static void setup() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-queryparams");
entityManager = factory.createEntityManager();
}
@Test
public void givenEmpNumber_whenUsingPositionalParameter_thenReturnExpectedEmployee() {
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber = ?0" , Employee.class);
String empNumber = "A123";
Employee employee = query.setParameter(0, empNumber).getSingleResult();
Assert.assertNotNull("Employee not found", employee);
}
@Test
public void givenEmpNumber_whenUsingNamedParameter_thenReturnExpectedEmployee() {
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber = :number" , Employee.class);
String empNumber = "A123";
Employee employee = query.setParameter("number", empNumber).getSingleResult();
Assert.assertNotNull("Employee not found", employee);
}
@Test
public void givenEmpNumber_whenUsingTwoNamedParameters_thenReturnExpectedEmployees() {
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.name = :name AND e.age = :empAge" , Employee.class);
String empName = "John Doe";
int empAge = 55;
List<Employee> employees = query
.setParameter("name", empName)
.setParameter("empAge", empAge)
.getResultList();
Assert.assertNotNull("Employees not found!", employees);
Assert.assertTrue("Employees not found!", !employees.isEmpty());
}
@Test
public void givenEmpNumber_whenUsingCriteriaQuery_thenReturnExpectedEmployee() {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> cQuery = cb.createQuery(Employee.class);
Root<Employee> c = cQuery.from(Employee.class);
ParameterExpression<String> paramEmpNumber = cb.parameter(String.class);
cQuery.select(c).where(cb.equal(c.get(Employee_.empNumber), paramEmpNumber));
TypedQuery<Employee> query = entityManager.createQuery(cQuery);
String empNumber = "A123";
query.setParameter(paramEmpNumber, empNumber);
Employee employee = query.getSingleResult();
Assert.assertNotNull("Employee not found!", employee);
}
@Test
public void givenEmpNumber_whenUsingLiteral_thenReturnExpectedEmployee() {
String empNumber = "A123";
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber = '" + empNumber + "'", Employee.class);
Employee employee = query.getSingleResult();
Assert.assertNotNull("Employee not found!", employee);
}
}

View File

@ -0,0 +1,2 @@
INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('111', 'John Doe', 55);
INSERT INTO employees (employee_number, employee_name, employee_age) VALUES ('A123', 'John Doe Junior', 25);