JAVA-4 : added new module hibernate5-queries
This commit is contained in:
parent
9f8e1b51b3
commit
9017080633
|
@ -0,0 +1,10 @@
|
|||
## Hibernate 5
|
||||
|
||||
This module contains articles about Hibernate 5.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)
|
||||
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
|
||||
- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
|
||||
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
|
|
@ -0,0 +1,82 @@
|
|||
<?xml version="1.0"?>
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>hibernate5-queries</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>hibernate5-queries</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>persistence-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-spatial</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.opengeo</groupId>
|
||||
<artifactId>geodb</artifactId>
|
||||
<version>${geodb.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.vorburger.mariaDB4j</groupId>
|
||||
<artifactId>mariaDB4j</artifactId>
|
||||
<version>${mariaDB4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-testing</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk-jmh.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>geodb-repo</id>
|
||||
<name>GeoDB repository</name>
|
||||
<url>http://repo.boundlessgeo.com/main/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.3.7.Final</hibernate.version>
|
||||
<mysql.version>6.0.6</mysql.version>
|
||||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<geodb.version>0.9</geodb.version>
|
||||
<openjdk-jmh.version>1.21</openjdk-jmh.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.hibernate;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.customtypes.LocalDateStringType;
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
return makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry(properties);
|
||||
return makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
|
||||
metadataSources.addPackage("com.baeldung.hibernate.pojo");
|
||||
metadataSources.addAnnotatedClass(Student.class);
|
||||
metadataSources.addAnnotatedClass(DeptEmployee.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
|
||||
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.applyBasicType(LocalDateStringType.INSTANCE)
|
||||
.build();
|
||||
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
return configureServiceRegistry(getProperties());
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.hibernate;
|
||||
|
||||
public class UnsupportedTenancyException extends Exception {
|
||||
public UnsupportedTenancyException (String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,60 @@
|
|||
package com.baeldung.hibernate.criteriaquery;
|
||||
|
||||
import com.baeldung.hibernate.customtypes.LocalDateStringType;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private HibernateUtil() {
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = buildSessionFactory();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
try {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
|
||||
metadataSources.addAnnotatedClass(Student.class);
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.applyBasicType(LocalDateStringType.INSTANCE)
|
||||
.build();
|
||||
return metadata.getSessionFactoryBuilder().build();
|
||||
} catch (IOException ex) {
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties).build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("hibernate.properties");
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.hibernate.criteriaquery;
|
||||
|
||||
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 = "students")
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private int id;
|
||||
|
||||
@Column(name = "first_name")
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "last_name")
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "grad_year")
|
||||
private int gradYear;
|
||||
|
||||
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 int getGradYear() {
|
||||
return gradYear;
|
||||
}
|
||||
|
||||
public void setGradYear(int gradYear) {
|
||||
this.gradYear = gradYear;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.type.LocalDateType;
|
||||
import org.hibernate.type.descriptor.WrapperOptions;
|
||||
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
|
||||
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
|
||||
import org.hibernate.type.descriptor.java.MutabilityPlan;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
|
||||
|
||||
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
|
||||
|
||||
public LocalDateStringJavaDescriptor() {
|
||||
super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(LocalDate value) {
|
||||
return LocalDateType.FORMATTER.format(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate fromString(String string) {
|
||||
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
|
||||
|
||||
if (value == null)
|
||||
return null;
|
||||
|
||||
if (String.class.isAssignableFrom(type))
|
||||
return (X) LocalDateType.FORMATTER.format(value);
|
||||
|
||||
throw unknownUnwrap(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <X> LocalDate wrap(X value, WrapperOptions options) {
|
||||
if (value == null)
|
||||
return null;
|
||||
|
||||
if(String.class.isInstance(value))
|
||||
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
|
||||
|
||||
throw unknownWrap(value.getClass());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.dialect.Dialect;
|
||||
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
|
||||
import org.hibernate.type.DiscriminatorType;
|
||||
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
|
||||
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
|
||||
|
||||
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
|
||||
|
||||
public LocalDateStringType() {
|
||||
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "LocalDateString";
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate stringToObject(String xml) throws Exception {
|
||||
return fromString(xml);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
|
||||
return '\'' + toString(value) + '\'';
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.hibernate.entities;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class Department {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy="department")
|
||||
private List<DeptEmployee> employees;
|
||||
|
||||
public Department(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<DeptEmployee> getEmployees() {
|
||||
return employees;
|
||||
}
|
||||
|
||||
public void setEmployees(List<DeptEmployee> employees) {
|
||||
this.employees = employees;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package com.baeldung.hibernate.entities;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
|
||||
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
|
||||
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
|
||||
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
|
||||
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
|
||||
@org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) })
|
||||
@Entity
|
||||
public class DeptEmployee {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long id;
|
||||
|
||||
private String employeeNumber;
|
||||
|
||||
private String title;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToOne
|
||||
private Department department;
|
||||
|
||||
public DeptEmployee(String name, String employeeNumber, Department department) {
|
||||
this.name = name;
|
||||
this.employeeNumber = employeeNumber;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public DeptEmployee(String name, String employeeNumber, String title, Department department) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.employeeNumber = employeeNumber;
|
||||
this.title = title;
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmployeeNumber() {
|
||||
return employeeNumber;
|
||||
}
|
||||
|
||||
public void setEmployeeNumber(String employeeNumber) {
|
||||
this.employeeNumber = employeeNumber;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Department getDepartment() {
|
||||
return department;
|
||||
}
|
||||
|
||||
public void setDepartment(Department department) {
|
||||
this.department = department;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.hibernate.findall;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.hibernate.Session;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
|
||||
public class FindAll {
|
||||
|
||||
private Session session;
|
||||
|
||||
public FindAll(Session session) {
|
||||
super();
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
public List<Student> findAllWithJpql() {
|
||||
return session.createQuery("SELECT a FROM Student a", Student.class).getResultList();
|
||||
}
|
||||
|
||||
public List<Student> findAllWithCriteriaQuery() {
|
||||
CriteriaBuilder cb = session.getCriteriaBuilder();
|
||||
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
|
||||
Root<Student> rootEntry = cq.from(Student.class);
|
||||
CriteriaQuery<Student> all = cq.select(rootEntry);
|
||||
TypedQuery<Student> allQuery = session.createQuery(all);
|
||||
return allQuery.getResultList();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.hibernate.pojo;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE)
|
||||
private long studentId;
|
||||
|
||||
private String name;
|
||||
|
||||
private int age;
|
||||
|
||||
public Student() {
|
||||
}
|
||||
|
||||
public Student(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public long getStudentId() {
|
||||
return studentId;
|
||||
}
|
||||
|
||||
public void setStudentId(long studentId) {
|
||||
this.studentId = studentId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<persistence 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"
|
||||
version="2.0">
|
||||
<persistence-unit name="com.baeldung.movie_catalog">
|
||||
<description>Hibernate EntityManager Demo</description>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="update"/>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
|
||||
<property name="javax.persistence.jdbc.user" value="root"/>
|
||||
<property name="javax.persistence.jdbc.password" value="root"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
|
@ -0,0 +1,10 @@
|
|||
CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
@CODE
|
||||
void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException {
|
||||
CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'");
|
||||
updateStatement.execute();
|
||||
}
|
||||
$$;
|
|
@ -0,0 +1,13 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,98 @@
|
|||
package com.baeldung.hibernate;
|
||||
|
||||
import com.baeldung.hibernate.entities.Department;
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.hibernate.query.NativeQuery;
|
||||
import org.hibernate.query.Query;
|
||||
import org.junit.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class NamedQueryIntegrationTest {
|
||||
private static Session session;
|
||||
|
||||
private Transaction transaction;
|
||||
|
||||
private Long purchaseDeptId;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() throws IOException {
|
||||
session = HibernateUtil.getSessionFactory("hibernate-namedquery.properties").openSession();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
transaction = session.beginTransaction();
|
||||
session.createNativeQuery("delete from deptemployee").executeUpdate();
|
||||
session.createNativeQuery("delete from department").executeUpdate();
|
||||
Department salesDepartment = new Department("Sales");
|
||||
Department purchaseDepartment = new Department("Purchase");
|
||||
DeptEmployee employee1 = new DeptEmployee("John Wayne", "001", salesDepartment);
|
||||
DeptEmployee employee2 = new DeptEmployee("Sarah Vinton", "002", salesDepartment);
|
||||
DeptEmployee employee3 = new DeptEmployee("Lisa Carter", "003", salesDepartment);
|
||||
session.persist(salesDepartment);
|
||||
session.persist(purchaseDepartment);
|
||||
purchaseDeptId = purchaseDepartment.getId();
|
||||
session.persist(employee1);
|
||||
session.persist(employee2);
|
||||
session.persist(employee3);
|
||||
transaction.commit();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
if(transaction.isActive()) {
|
||||
transaction.rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNamedQueryIsCalledUsingCreateNamedQuery_ThenOk() {
|
||||
Query<DeptEmployee> query = session.createNamedQuery("DeptEmployee_FindByEmployeeNumber", DeptEmployee.class);
|
||||
query.setParameter("employeeNo", "001");
|
||||
DeptEmployee result = query.getSingleResult();
|
||||
Assert.assertNotNull(result);
|
||||
Assert.assertEquals("John Wayne", result.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNamedNativeQueryIsCalledUsingCreateNamedQuery_ThenOk() {
|
||||
Query<DeptEmployee> query = session.createNamedQuery("DeptEmployee_FindByEmployeeName", DeptEmployee.class);
|
||||
query.setParameter("name", "John Wayne");
|
||||
DeptEmployee result = query.getSingleResult();
|
||||
Assert.assertNotNull(result);
|
||||
Assert.assertEquals("001", result.getEmployeeNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNamedNativeQueryIsCalledUsingGetNamedNativeQuery_ThenOk() {
|
||||
@SuppressWarnings("rawtypes")
|
||||
NativeQuery query = session.getNamedNativeQuery("DeptEmployee_FindByEmployeeName");
|
||||
query.setParameter("name", "John Wayne");
|
||||
DeptEmployee result = (DeptEmployee) query.getSingleResult();
|
||||
Assert.assertNotNull(result);
|
||||
Assert.assertEquals("001", result.getEmployeeNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpdateQueryIsCalledWithCreateNamedQuery_ThenOk() {
|
||||
Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDepartment");
|
||||
spQuery.setParameter("employeeNo", "001");
|
||||
Department newDepartment = session.find(Department.class, purchaseDeptId);
|
||||
spQuery.setParameter("newDepartment", newDepartment);
|
||||
spQuery.executeUpdate();
|
||||
transaction.commit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNamedStoredProcedureIsCalledWithCreateNamedQuery_ThenOk() {
|
||||
Query spQuery = session.createNamedQuery("DeptEmployee_UpdateEmployeeDesignation");
|
||||
spQuery.setParameter("employeeNumber", "002");
|
||||
spQuery.setParameter("newDesignation", "Supervisor");
|
||||
spQuery.executeUpdate();
|
||||
transaction.commit();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
package com.baeldung.hibernate.criteriaquery;
|
||||
|
||||
import com.baeldung.hibernate.criteriaquery.HibernateUtil;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.query.Query;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
|
||||
public class TypeSafeCriteriaIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private Session session;
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeTests() throws IOException {
|
||||
sessionFactory = HibernateUtil.getSessionFactory();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
session = sessionFactory.openSession();
|
||||
session.beginTransaction();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStudentData_whenUsingTypeSafeCriteriaQuery_thenSearchAllStudentsOfAGradYear() {
|
||||
|
||||
prepareData();
|
||||
CriteriaBuilder cb = session.getCriteriaBuilder();
|
||||
CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
|
||||
|
||||
Root<Student> root = criteriaQuery.from(Student.class);
|
||||
criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965));
|
||||
|
||||
Query<Student> query = session.createQuery(criteriaQuery);
|
||||
List<Student> results = query.getResultList();
|
||||
|
||||
assertNotNull(results);
|
||||
assertEquals(1, results.size());
|
||||
|
||||
Student student = results.get(0);
|
||||
|
||||
assertEquals("Ken", student.getFirstName());
|
||||
assertEquals("Thompson", student.getLastName());
|
||||
assertEquals(1965, student.getGradYear());
|
||||
}
|
||||
|
||||
private void prepareData() {
|
||||
Student student1 = new Student();
|
||||
student1.setFirstName("Ken");
|
||||
student1.setLastName("Thompson");
|
||||
student1.setGradYear(1965);
|
||||
|
||||
session.save(student1);
|
||||
|
||||
Student student2 = new Student();
|
||||
student2.setFirstName("Dennis");
|
||||
student2.setLastName("Ritchie");
|
||||
student2.setGradYear(1963);
|
||||
|
||||
session.save(student2);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
session.close();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.baeldung.hibernate.findall;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
|
||||
public class FindAllUnitTest {
|
||||
|
||||
private Session session;
|
||||
private Transaction transaction;
|
||||
|
||||
private FindAll findAll;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
|
||||
session = HibernateUtil.getSessionFactory().openSession();
|
||||
transaction = session.beginTransaction();
|
||||
findAll = new FindAll(session);
|
||||
|
||||
session.createNativeQuery("delete from Student").executeUpdate();
|
||||
|
||||
Student student1 = new Student();
|
||||
session.persist(student1);
|
||||
|
||||
Student student2 = new Student();
|
||||
session.persist(student2);
|
||||
|
||||
Student student3 = new Student();
|
||||
session.persist(student3);
|
||||
|
||||
transaction.commit();
|
||||
transaction = session.beginTransaction();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
transaction.rollback();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCriteriaQuery_WhenFindAll_ThenGetAllPersons() {
|
||||
List<Student> list = findAll.findAllWithCriteriaQuery();
|
||||
assertEquals(3, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJpql_WhenFindAll_ThenGetAllPersons() {
|
||||
List<Student> list = findAll.findAllWithJpql();
|
||||
assertEquals(3, list.size());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
package com.baeldung.hibernate.queryplancache;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.jpa.QueryHints;
|
||||
import org.hibernate.query.Query;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Param;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.TearDown;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class QueryPlanCacheBenchmark {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(QueryPlanCacheBenchmark.class);
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class QueryPlanCacheBenchMarkState {
|
||||
@Param({"1", "2", "3"})
|
||||
public int planCacheSize;
|
||||
|
||||
public Session session;
|
||||
|
||||
@Setup
|
||||
public void stateSetup() throws IOException {
|
||||
LOGGER.info("State - Setup");
|
||||
session = initSession(planCacheSize);
|
||||
LOGGER.info("State - Setup Complete");
|
||||
}
|
||||
|
||||
private Session initSession(int planCacheSize) throws IOException {
|
||||
Properties properties = HibernateUtil.getProperties();
|
||||
properties.put("hibernate.query.plan_cache_max_size", planCacheSize);
|
||||
properties.put("hibernate.query.plan_parameter_metadata_max_size", planCacheSize);
|
||||
SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties);
|
||||
return sessionFactory.openSession();
|
||||
}
|
||||
|
||||
@TearDown
|
||||
public void tearDownState() {
|
||||
LOGGER.info("State - Teardown");
|
||||
SessionFactory sessionFactory = session.getSessionFactory();
|
||||
session.close();
|
||||
sessionFactory.close();
|
||||
LOGGER.info("State - Teardown complete");
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Fork(1)
|
||||
@Warmup(iterations = 2)
|
||||
@Measurement(iterations = 5)
|
||||
public void givenQueryPlanCacheSize_thenCompileQueries(QueryPlanCacheBenchMarkState state, Blackhole blackhole) {
|
||||
|
||||
Query query1 = findEmployeesByDepartmentNameQuery(state.session);
|
||||
Query query2 = findEmployeesByDesignationQuery(state.session);
|
||||
Query query3 = findDepartmentOfAnEmployeeQuery(state.session);
|
||||
|
||||
blackhole.consume(query1);
|
||||
blackhole.consume(query2);
|
||||
blackhole.consume(query3);
|
||||
|
||||
}
|
||||
|
||||
private Query findEmployeesByDepartmentNameQuery(Session session) {
|
||||
return session.createQuery("SELECT e FROM DeptEmployee e " +
|
||||
"JOIN e.department WHERE e.department.name = :deptName")
|
||||
.setMaxResults(30)
|
||||
.setHint(QueryHints.HINT_FETCH_SIZE, 30);
|
||||
}
|
||||
|
||||
private Query findEmployeesByDesignationQuery(Session session) {
|
||||
return session.createQuery("SELECT e FROM DeptEmployee e " +
|
||||
"WHERE e.title = :designation")
|
||||
.setHint(QueryHints.SPEC_HINT_TIMEOUT, 1000);
|
||||
}
|
||||
|
||||
private Query findDepartmentOfAnEmployeeQuery(Session session) {
|
||||
return session.createQuery("SELECT e.department FROM DeptEmployee e " +
|
||||
"JOIN e.department WHERE e.employeeNumber = :empId");
|
||||
|
||||
}
|
||||
|
||||
public static void main(String... args) throws IOException, RunnerException {
|
||||
//main-class to run the benchmark
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
hibernate.c3p0.min_size=5
|
||||
hibernate.c3p0.max_size=20
|
||||
hibernate.c3p0.acquire_increment=5
|
||||
hibernate.c3p0.timeout=1800
|
|
@ -0,0 +1,9 @@
|
|||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/main/resources/init_database.sql'
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
|
@ -0,0 +1,14 @@
|
|||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
hibernate.c3p0.min_size=5
|
||||
hibernate.c3p0.max_size=20
|
||||
hibernate.c3p0.acquire_increment=5
|
||||
hibernate.c3p0.timeout=1800
|
|
@ -0,0 +1,25 @@
|
|||
create sequence hibernate_sequence start with 1 increment by 1;
|
||||
|
||||
create table Football_Player (
|
||||
id bigint not null,
|
||||
name varchar(255),
|
||||
primary key (id)
|
||||
);
|
||||
|
||||
insert into
|
||||
Football_Player
|
||||
(name, id)
|
||||
values
|
||||
('Cristiano Ronaldo', next value for hibernate_sequence);
|
||||
|
||||
insert into
|
||||
Football_Player
|
||||
(name, id)
|
||||
values
|
||||
('Lionel Messi', next value for hibernate_sequence);
|
||||
|
||||
insert into
|
||||
Football_Player
|
||||
(name, id)
|
||||
values
|
||||
('Gigi Buffon', next value for hibernate_sequence);
|
Binary file not shown.
After Width: | Height: | Size: 1.1 KiB |
Loading…
Reference in New Issue