JAVA-4 : Split hibernate5 module to smaller parts

This commit is contained in:
sampadawagde 2020-03-11 18:18:27 +05:30
parent 25d015b3df
commit a5ae83d28a
89 changed files with 0 additions and 5755 deletions

View File

@ -4,38 +4,13 @@ This module contains articles about Hibernate 5.
### Relevant articles:
- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping)
- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers)
- [Hibernate Mapping Date and Time](http://www.baeldung.com/hibernate-date-time)
- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance)
- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy)
- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial)
- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor)
- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters)
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking)
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
- [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method)
- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types)
- [Criteria API An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions)
- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby)
- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api)
- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)
- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager)
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one)
- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks)
- [[Next -->]](/hibernate5-2)

View File

@ -12,25 +12,13 @@ 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.customtypes.OfficeEmployee;
import com.baeldung.hibernate.entities.DeptEmployee;
import com.baeldung.hibernate.joincolumn.Email;
import com.baeldung.hibernate.joincolumn.Office;
import com.baeldung.hibernate.joincolumn.OfficeAddress;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
import com.baeldung.hibernate.pessimisticlocking.Individual;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.Person;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
@ -88,7 +76,6 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(MyEmployee.class);
metadataSources.addAnnotatedClass(MyProduct.class);
metadataSources.addAnnotatedClass(Pen.class);
metadataSources.addAnnotatedClass(Person.class);
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
@ -96,26 +83,11 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
metadataSources.addAnnotatedClass(Individual.class);
metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
metadataSources.addAnnotatedClass(DeptEmployee.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
metadataSources.addAnnotatedClass(OfficeEmployee.class);
metadataSources.addAnnotatedClass(Post.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class);
metadataSources.addAnnotatedClass(Email.class);
metadataSources.addAnnotatedClass(Office.class);
metadataSources.addAnnotatedClass(OfficeAddress.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder()

View File

@ -1,61 +0,0 @@
package com.baeldung.hibernate.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import com.baeldung.hibernate.pojo.PersonName;
@Converter
public class PersonNameConverter implements AttributeConverter<PersonName, String> {
private static final String SEPARATOR = ", ";
@Override
public String convertToDatabaseColumn(PersonName personName) {
if (personName == null) {
return null;
}
StringBuilder sb = new StringBuilder();
if (personName.getSurname() != null && !personName.getSurname()
.isEmpty()) {
sb.append(personName.getSurname());
sb.append(SEPARATOR);
}
if (personName.getName() != null && !personName.getName()
.isEmpty()) {
sb.append(personName.getName());
}
return sb.toString();
}
@Override
public PersonName convertToEntityAttribute(String dbPersonName) {
if (dbPersonName == null || dbPersonName.isEmpty()) {
return null;
}
String[] pieces = dbPersonName.split(SEPARATOR);
if (pieces == null || pieces.length == 0) {
return null;
}
PersonName personName = new PersonName();
String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null;
if (dbPersonName.contains(SEPARATOR)) {
personName.setSurname(firstPiece);
if (pieces.length >= 2 && pieces[1] != null && !pieces[1].isEmpty()) {
personName.setName(pieces[1]);
}
} else {
personName.setName(firstPiece);
}
return personName;
}
}

View File

@ -1,60 +0,0 @@
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;
}
}

View File

@ -1,58 +0,0 @@
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;
}
}

View File

@ -1,69 +0,0 @@
package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public class Address {
private String addressLine1;
private String addressLine2;
private String city;
private String country;
private int zipCode;
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
public int getZipCode() {
return zipCode;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Address address = (Address) o;
return zipCode == address.zipCode &&
Objects.equals(addressLine1, address.addressLine1) &&
Objects.equals(addressLine2, address.addressLine2) &&
Objects.equals(city, address.city) &&
Objects.equals(country, address.country);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city, country, zipCode);
}
}

View File

@ -1,169 +0,0 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class AddressType implements CompositeUserType {
@Override
public String[] getPropertyNames() {
return new String[]{"addressLine1", "addressLine2",
"city", "country", "zipcode"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
return empAdd.getAddressLine1();
case 1:
return empAdd.getAddressLine2();
case 2:
return empAdd.getCity();
case 3:
return empAdd.getCountry();
case 4:
return Integer.valueOf(empAdd.getZipCode());
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
empAdd.setAddressLine1((String) value);
case 1:
empAdd.setAddressLine2((String) value);
case 2:
empAdd.setCity((String) value);
case 3:
empAdd.setCountry((String) value);
case 4:
empAdd.setZipCode((Integer) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
return Address.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
Address empAdd = new Address();
empAdd.setAddressLine1(rs.getString(names[0]));
if (rs.wasNull())
return null;
empAdd.setAddressLine2(rs.getString(names[1]));
empAdd.setCity(rs.getString(names[2]));
empAdd.setCountry(rs.getString(names[3]));
empAdd.setZipCode(rs.getInt(names[4]));
return empAdd;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Address empAdd = (Address) value;
st.setString(index, empAdd.getAddressLine1());
st.setString(index + 1, empAdd.getAddressLine2());
st.setString(index + 2, empAdd.getCity());
st.setString(index + 3, empAdd.getCountry());
st.setInt(index + 4, empAdd.getZipCode());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (Objects.isNull(value))
return null;
Address oldEmpAdd = (Address) value;
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
newEmpAdd.setCity(oldEmpAdd.getCity());
newEmpAdd.setCountry(oldEmpAdd.getCountry());
newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
return newEmpAdd;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
}
}

View File

@ -1,51 +0,0 @@
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());
}
}

View File

@ -1,34 +0,0 @@
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) + '\'';
}
}

View File

@ -1,88 +0,0 @@
package com.baeldung.hibernate.customtypes;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDate;
@TypeDef(name = "PhoneNumber",
typeClass = PhoneNumberType.class,
defaultForType = PhoneNumber.class)
@Entity
@Table(name = "OfficeEmployee")
public class OfficeEmployee {
@Id
@GeneratedValue
private long id;
@Column
@Type(type = "LocalDateString")
private LocalDate dateOfJoining;
@Columns(columns = {@Column(name = "country_code"),
@Column(name = "city_code"),
@Column(name = "number")})
private PhoneNumber employeeNumber;
@Columns(columns = {@Column(name = "address_line_1"),
@Column(name = "address_line_2"),
@Column(name = "city"), @Column(name = "country"),
@Column(name = "zip_code")})
@Type(type = "com.baeldung.hibernate.customtypes.AddressType")
private Address empAddress;
@Type(type = "com.baeldung.hibernate.customtypes.SalaryType",
parameters = {@Parameter(name = "currency", value = "USD")})
@Columns(columns = {@Column(name = "amount"),
@Column(name = "currency")})
private Salary salary;
public Salary getSalary() {
return salary;
}
public void setSalary(Salary salary) {
this.salary = salary;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public LocalDate getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(LocalDate dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
public PhoneNumber getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(PhoneNumber employeeNumber) {
this.employeeNumber = employeeNumber;
}
public Address getEmpAddress() {
return empAddress;
}
public void setEmpAddress(Address empAddress) {
this.empAddress = empAddress;
}
}

View File

@ -1,43 +0,0 @@
package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public final class PhoneNumber {
private final int countryCode;
private final int cityCode;
private final int number;
public PhoneNumber(int countryCode, int cityCode, int number) {
this.countryCode = countryCode;
this.cityCode = cityCode;
this.number = number;
}
public int getCountryCode() {
return countryCode;
}
public int getCityCode() {
return cityCode;
}
public int getNumber() {
return number;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PhoneNumber that = (PhoneNumber) o;
return countryCode == that.countryCode &&
cityCode == that.cityCode &&
number == that.number;
}
@Override
public int hashCode() {
return Objects.hash(countryCode, cityCode, number);
}
}

View File

@ -1,98 +0,0 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class PhoneNumberType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
}
@Override
public Class returnedClass() {
return PhoneNumber.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
int countryCode = rs.getInt(names[0]);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
return employeeNumber;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (Objects.isNull(value))
return null;
PhoneNumber empNumber = (PhoneNumber) value;
PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
return newEmpNumber;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}

View File

@ -1,39 +0,0 @@
package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public class Salary {
private Long amount;
private String currency;
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Salary salary = (Salary) o;
return Objects.equals(amount, salary.amount) &&
Objects.equals(currency, salary.currency);
}
@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
}

View File

@ -1,15 +0,0 @@
package com.baeldung.hibernate.customtypes;
public class SalaryCurrencyConvertor {
public static Long convert(Long amount, String oldCurr, String newCurr){
if (newCurr.equalsIgnoreCase(oldCurr))
return amount;
return convertTo();
}
private static Long convertTo() {
return 10L;
}
}

View File

@ -1,161 +0,0 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.DynamicParameterizedType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
import java.util.Properties;
public class SalaryType implements CompositeUserType, DynamicParameterizedType {
private String localCurrency;
@Override
public String[] getPropertyNames() {
return new String[]{"amount", "currency"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
return salary.getAmount();
case 1:
return salary.getCurrency();
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
salary.setAmount((Long) value);
case 1:
salary.setCurrency((String) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
return Salary.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
Salary salary = new Salary();
salary.setAmount(rs.getLong(names[0]));
if (rs.wasNull())
return null;
salary.setCurrency(rs.getString(names[1]));
return salary;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.BIGINT);
else {
Salary salary = (Salary) value;
st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
salary.getCurrency(), localCurrency));
st.setString(index + 1, salary.getCurrency());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (Objects.isNull(value))
return null;
Salary oldSal = (Salary) value;
Salary newSal = new Salary();
newSal.setAmount(oldSal.getAmount());
newSal.setCurrency(oldSal.getCurrency());
return newSal;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
}
@Override
public void setParameterValues(Properties parameters) {
this.localCurrency = parameters.getProperty("currency");
}
}

View File

@ -1,16 +0,0 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
@Entity
public class EntityWithNoId {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}

View File

@ -1,63 +0,0 @@
package com.baeldung.hibernate.exception;
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;
public class HibernateUtil {
private static SessionFactory sessionFactory;
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;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
}
private static SessionFactory makeSessionFactory(
ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Product.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
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(StringUtils.defaultString(PROPERTY_FILE_NAME,
"hibernate-exception.properties"));
try (FileInputStream inputStream = new FileInputStream(
propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -1,40 +0,0 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Product {
private int id;
private String name;
private String description;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,35 +0,0 @@
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();
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Email {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String address;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employee_id")
private OfficialEmployee employee;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public OfficialEmployee getEmployee() {
return employee;
}
public void setEmployee(OfficialEmployee employee) {
this.employee = employee;
}
}

View File

@ -1,41 +0,0 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
@Entity
public class Office {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
private OfficeAddress address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public OfficeAddress getAddress() {
return address;
}
public void setAddress(OfficeAddress address) {
this.address = address;
}
}

View File

@ -1,34 +0,0 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class OfficeAddress {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "ZIP")
private String zipCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}

View File

@ -1,36 +0,0 @@
package com.baeldung.hibernate.joincolumn;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class OfficialEmployee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
private List<Email> emails;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Email> getEmails() {
return emails;
}
public void setEmails(List<Email> emails) {
this.emails = emails;
}
}

View File

@ -1,34 +0,0 @@
package com.baeldung.hibernate.jpabootstrap.application;
import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
import com.baeldung.hibernate.jpabootstrap.entities.User;
import javax.persistence.EntityManager;
public class Application {
public static void main(String[] args) {
EntityManager entityManager = getJpaEntityManager();
User user = entityManager.find(User.class, 1);
System.out.println(user);
entityManager.getTransaction().begin();
user.setName("John");
user.setEmail("john@domain.com");
entityManager.merge(user);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
entityManager.persist(new User("Monica", "monica@domain.com"));
entityManager.getTransaction().commit();
// additional CRUD operations
}
private static class EntityManagerHolder {
private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(
new Class[]{User.class}).getEntityManager();
}
public static EntityManager getJpaEntityManager() {
return EntityManagerHolder.ENTITY_MANAGER;
}
}

View File

@ -1,131 +0,0 @@
package com.baeldung.hibernate.jpabootstrap.config;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.jpa.HibernatePersistenceProvider;
public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
public static final String JPA_VERSION = "2.1";
private final String persistenceUnitName;
private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
private final List<String> managedClassNames;
private final List<String> mappingFileNames = new ArrayList<>();
private final Properties properties;
private DataSource jtaDataSource;
private DataSource nonjtaDataSource;
private final List<ClassTransformer> transformers = new ArrayList<>();
public HibernatePersistenceUnitInfo(String persistenceUnitName, List<String> managedClassNames, Properties properties) {
this.persistenceUnitName = persistenceUnitName;
this.managedClassNames = managedClassNames;
this.properties = properties;
}
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) {
this.jtaDataSource = jtaDataSource;
this.nonjtaDataSource = null;
transactionType = PersistenceUnitTransactionType.JTA;
return this;
}
@Override
public DataSource getJtaDataSource() {
return jtaDataSource;
}
public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonjtaDataSource = nonJtaDataSource;
this.jtaDataSource = null;
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
return this;
}
@Override
public DataSource getNonJtaDataSource() {
return nonjtaDataSource;
}
@Override
public List<String> getMappingFileNames() {
return mappingFileNames;
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
transformers.add(transformer);
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
}

View File

@ -1,69 +0,0 @@
package com.baeldung.hibernate.jpabootstrap.config;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitInfo;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
public class JpaEntityManagerFactory {
private final String DB_URL = "jdbc:mysql://databaseurl";
private final String DB_USER_NAME = "username";
private final String DB_PASSWORD = "password";
private final Class[] entityClasses;
public JpaEntityManagerFactory(Class[] entityClasses) {
this.entityClasses = entityClasses;
}
public EntityManager getEntityManager() {
return getEntityManagerFactory().createEntityManager();
}
protected EntityManagerFactory getEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<>();
return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
.build();
}
protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) {
return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties());
}
protected List<String> getEntityClassNames() {
return Arrays.asList(getEntities())
.stream()
.map(Class::getName)
.collect(Collectors.toList());
}
protected Properties getProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings", false);
properties.put("hibernate.connection.datasource", getMysqlDataSource());
return properties;
}
protected Class[] getEntities() {
return entityClasses;
}
protected DataSource getMysqlDataSource() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(DB_URL);
mysqlDataSource.setUser(DB_USER_NAME);
mysqlDataSource.setPassword(DB_PASSWORD);
return mysqlDataSource;
}
}

View File

@ -1,45 +0,0 @@
package com.baeldung.hibernate.jpabootstrap.entities;
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 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
public User(){}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}

View File

@ -1,15 +0,0 @@
package com.baeldung.hibernate.jpacriteriabuilder.service;
import java.util.List;
import com.baeldung.hibernate.entities.DeptEmployee;
public interface EmployeeSearchService {
List<DeptEmployee> filterbyTitleUsingCriteriaBuilder(List<String> titles);
List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles);
List<DeptEmployee> searchByDepartmentQuery(String query);
}

View File

@ -1,77 +0,0 @@
package com.baeldung.hibernate.jpacriteriabuilder.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.entities.DeptEmployee;
public class EmployeeSearchServiceImpl implements EmployeeSearchService {
private EntityManager entityManager;
private CriteriaBuilder criteriaBuilder;
public EmployeeSearchServiceImpl(EntityManager entityManager) {
this.entityManager = entityManager;
this.criteriaBuilder = entityManager.getCriteriaBuilder();
}
@Override
public List<DeptEmployee> filterbyTitleUsingCriteriaBuilder(List<String> titles) {
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
In<String> inClause = criteriaBuilder.in(root.get("title"));
for (String title : titles) {
inClause.value(title);
}
criteriaQuery.select(root)
.where(inClause);
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
@Override
public List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles) {
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
criteriaQuery.select(root)
.where(root.get("title")
.in(titles));
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
@Override
public List<DeptEmployee> searchByDepartmentQuery(String searchKey) {
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
Root<DeptEmployee> emp = criteriaQuery.from(DeptEmployee.class);
Subquery<Department> subquery = criteriaQuery.subquery(Department.class);
Root<Department> dept = subquery.from(Department.class);
subquery.select(dept)
.distinct(true)
.where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey)
.append("%")
.toString()));
criteriaQuery.select(emp)
.where(criteriaBuilder.in(emp.get("department"))
.value(subquery));
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
private <T> CriteriaQuery<T> createCriteriaQuery(Class<T> klass) {
return criteriaBuilder.createQuery(klass);
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.hibernate.lob;
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.lob.model.User;
public class HibernateSessionUtil {
private static SessionFactory sessionFactory;
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;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(User.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
.build();
}
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(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.hibernate.lob.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User {
@Id
private String id;
@Column(name = "name", columnDefinition="VARCHAR(128)")
private String name;
@Lob
@Column(name = "photo", columnDefinition="BLOB")
private byte[] photo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
}

View File

@ -1,63 +0,0 @@
package com.baeldung.hibernate.onetoone;
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(Strategy strategy) {
return buildSessionFactory(strategy);
}
private static SessionFactory buildSessionFactory(Strategy strategy) {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class<?> entityClass : strategy.getEntityClasses()) {
metadataSources.addAnnotatedClass(entityClass);
}
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;
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.hibernate.onetoone;
import java.util.Arrays;
import java.util.List;
public enum Strategy {
//See that the classes belongs to different packages
FOREIGN_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.foreignkeybased.User.class,
com.baeldung.hibernate.onetoone.foreignkeybased.Address.class)),
SHARED_PRIMARY_KEY(Arrays.asList(com.baeldung.hibernate.onetoone.sharedkeybased.User.class,
com.baeldung.hibernate.onetoone.sharedkeybased.Address.class)),
JOIN_TABLE_BASED(Arrays.asList(com.baeldung.hibernate.onetoone.jointablebased.Employee.class,
com.baeldung.hibernate.onetoone.jointablebased.WorkStation.class));
private List<Class<?>> entityClasses;
Strategy(List<Class<?>> entityClasses) {
this.entityClasses = entityClasses;
}
public List<Class<?>> getEntityClasses() {
return entityClasses;
}
}

View File

@ -1,60 +0,0 @@
package com.baeldung.hibernate.onetoone.foreignkeybased;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "street")
private String street;
@Column(name = "city")
private String city;
@OneToOne(mappedBy = "address")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -1,51 +0,0 @@
package com.baeldung.hibernate.onetoone.foreignkeybased;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "username")
private String userName;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

View File

@ -1,53 +0,0 @@
package com.baeldung.hibernate.onetoone.jointablebased;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "ename")
private String name;
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name = "emp_workstation", joinColumns = {@JoinColumn(name = "employee_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "workstation_id", referencedColumnName = "id")})
private WorkStation workStation;
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 WorkStation getWorkStation() {
return workStation;
}
public void setWorkStation(WorkStation workStation) {
this.workStation = workStation;
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.hibernate.onetoone.jointablebased;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "workstation")
public class WorkStation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "workstation_number")
private Integer workstationNumber;
@Column(name = "floor")
private String floor;
@OneToOne(mappedBy = "workStation")
private Employee employee;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getWorkstationNumber() {
return workstationNumber;
}
public void setWorkstationNumber(Integer workstationNumber) {
this.workstationNumber = workstationNumber;
}
public String getFloor() {
return floor;
}
public void setFloor(String floor) {
this.floor = floor;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}

View File

@ -1,60 +0,0 @@
package com.baeldung.hibernate.onetoone.sharedkeybased;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "address")
public class Address {
@Id
@Column(name = "id")
private Long id;
@Column(name = "street")
private String street;
@Column(name = "city")
private String city;
@OneToOne
@MapsId
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -1,50 +0,0 @@
package com.baeldung.hibernate.onetoone.sharedkeybased;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "username")
private String userName;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Address address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.hibernate.optimisticlocking;
import javax.persistence.*;
@Entity
public class OptimisticLockingCourse {
@Id
private Long id;
private String name;
@ManyToOne
@JoinTable(name = "optimistic_student_course")
private OptimisticLockingStudent student;
public OptimisticLockingCourse(Long id, String name) {
this.id = id;
this.name = name;
}
public OptimisticLockingCourse() {
}
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 OptimisticLockingStudent getStudent() {
return student;
}
public void setStudent(OptimisticLockingStudent student) {
this.student = student;
}
}

View File

@ -1,70 +0,0 @@
package com.baeldung.hibernate.optimisticlocking;
import javax.persistence.*;
import java.util.List;
@Entity
public class OptimisticLockingStudent {
@Id
private Long id;
private String name;
private String lastName;
@Version
private Integer version;
@OneToMany(mappedBy = "student")
private List<OptimisticLockingCourse> courses;
public OptimisticLockingStudent(Long id, String name, String lastName, List<OptimisticLockingCourse> courses) {
this.id = id;
this.name = name;
this.lastName = lastName;
this.courses = courses;
}
public OptimisticLockingStudent() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<OptimisticLockingCourse> getCourses() {
return courses;
}
public void setCourses(List<OptimisticLockingCourse> courses) {
this.courses = courses;
}
}

View File

@ -1,34 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String country;
private String city;
public Address(String country, String city) {
this.country = country;
this.city = city;
}
public Address() {
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -1,58 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.*;
import java.util.List;
@Entity
public class Customer {
@Id
private Long customerId;
private String name;
private String lastName;
@ElementCollection
@CollectionTable(name = "customer_address")
private List<Address> addressList;
public Customer() {
}
public Customer(Long customerId, String name, String lastName, List<Address> addressList) {
this.customerId = customerId;
this.name = name;
this.lastName = lastName;
this.addressList = addressList;
}
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> addressList) {
this.addressList = addressList;
}
}

View File

@ -1,49 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Individual {
@Id
private Long id;
private String name;
private String lastName;
public Individual(Long id, String name, String lastName) {
this.id = id;
this.name = name;
this.lastName = lastName;
}
public Individual() {
}
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 String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.*;
@Entity
public class PessimisticLockingCourse {
@Id
private Long courseId;
private String name;
@ManyToOne
@JoinTable(name = "student_course")
private PessimisticLockingStudent student;
public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) {
this.courseId = courseId;
this.name = name;
this.student = student;
}
public PessimisticLockingCourse() {
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PessimisticLockingStudent getStudent() {
return student;
}
public void setStudent(PessimisticLockingStudent students) {
this.student = students;
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.Entity;
import java.math.BigDecimal;
@Entity
public class PessimisticLockingEmployee extends Individual {
private BigDecimal salary;
public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) {
super(id, name, lastName);
this.salary = salary;
}
public PessimisticLockingEmployee() {
super();
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal average) {
this.salary = average;
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import javax.persistence.*;
import java.util.List;
@Entity
public class PessimisticLockingStudent {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "student")
private List<PessimisticLockingCourse> courses;
public PessimisticLockingStudent(Long id, String name) {
this.id = id;
this.name = name;
}
public PessimisticLockingStudent() {
}
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<PessimisticLockingCourse> getCourses() {
return courses;
}
public void setCourses(List<PessimisticLockingCourse> courses) {
this.courses = courses;
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import com.baeldung.hibernate.converters.PersonNameConverter;
@Entity(name = "PersonTable")
public class Person {
@Id
@GeneratedValue
private Long id;
@Convert(converter = PersonNameConverter.class)
private PersonName personName;
public PersonName getPersonName() {
return personName;
}
public void setPersonName(PersonName personName) {
this.personName = personName;
}
public Long getId() {
return id;
}
}

View File

@ -1,29 +0,0 @@
package com.baeldung.hibernate.transaction;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
public class PostService {
private Session session;
public PostService(Session session) {
this.session = session;
}
public void updatePost(String title, String body, int id) {
Transaction txn = session.beginTransaction();
Query updateQuery = session.createQuery("UPDATE Post p SET p.title = ?1, p.body = ?2 WHERE p.id = ?3");
updateQuery.setParameter(1, title);
updateQuery.setParameter(2, body);
updateQuery.setParameter(3, id);
updateQuery.executeUpdate();
txn.commit();
}
}

View File

@ -1,78 +0,0 @@
package com.baeldung.hibernate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import com.baeldung.hibernate.entities.DeptEmployee;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.hibernate.transform.Transformers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.pojo.Result;
public class CustomClassIntegrationTest {
private Session session;
private Transaction transaction;
@BeforeEach
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from department").executeUpdate();
Department department = new Department("Sales");
DeptEmployee employee = new DeptEmployee("John Smith", "001", department);
session.persist(department);
session.persist(employee);
transaction.commit();
transaction = session.beginTransaction();
}
@Test
public void whenAllManagersAreSelected_ThenObjectGraphIsReturned() {
Query<DeptEmployee> query = session.createQuery("from com.baeldung.hibernate.entities.DeptEmployee");
List<DeptEmployee> deptEmployees = query.list();
DeptEmployee deptEmployee = deptEmployees.get(0);
assertEquals("John Smith", deptEmployee.getName());
assertEquals("Sales", deptEmployee.getDepartment().getName());
}
@Test
public void whenIndividualPropertiesAreSelected_ThenObjectArrayIsReturned() {
Query query = session.createQuery("select m.name, m.department.name from com.baeldung.hibernate.entities.DeptEmployee m");
List managers = query.list();
Object[] manager = (Object[]) managers.get(0);
assertEquals("John Smith", manager[0]);
assertEquals("Sales", manager[1]);
}
@Test
public void whenResultConstructorInSelect_ThenListOfResultIsReturned() {
Query<Result> query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) "
+ "from DeptEmployee m");
List<Result> results = query.list();
Result result = results.get(0);
assertEquals("John Smith", result.getEmployeeName());
assertEquals("Sales", result.getDepartmentName());
}
@Test
public void whenResultTransformerOnQuery_ThenListOfResultIsReturned() {
Query query = session.createQuery("select m.name as employeeName, m.department.name as departmentName "
+ "from com.baeldung.hibernate.entities.DeptEmployee m");
query.setResultTransformer(Transformers.aliasToBean(Result.class));
List<Result> results = query.list();
Result result = results.get(0);
assertEquals("John Smith", result.getEmployeeName());
assertEquals("Sales", result.getDepartmentName());
}
}

View File

@ -1,160 +0,0 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DynamicMappingIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from phone").executeUpdate();
session.createNativeQuery("delete from employee").executeUpdate();
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() {
Employee employee = new Employee(10_000L, 25);
assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L);
session.save(employee);
session.flush();
session.clear();
employee = session.get(Employee.class, employee.getId());
assertThat(employee.getTax()).isEqualTo(2_500L);
}
@Test
public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
Employee employee = new Employee();
session.save(employee);
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNotNull();
employee.setDeleted(true);
session.flush();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNotNull();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNull();
}
@Test
public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");
employee.getPhones().add(phone1);
employee.getPhones().add(phone2);
session.save(phone1);
session.save(phone2);
session.save(employee);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(2);
employee.getPhones().iterator().next().setDeleted(true);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(1);
List<Phone> fullPhoneList = session.createQuery("from Phone").getResultList();
assertThat(fullPhoneList).hasSize(2);
}
@Test
public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException {
session.save(new Employee(10_000, 25));
session.save(new Employee(12_000, 25));
session.save(new Employee(15_000, 25));
session.flush();
session.clear();
session.enableFilter("incomeLevelFilter")
.setParameter("incomeLimit", 11_000);
List<Employee> employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(2);
Employee employee = session.get(Employee.class, 1);
assertThat(employee.getGrossIncome()).isEqualTo(10_000);
session.disableFilter("incomeLevelFilter");
employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(3);
}
@Test
public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() {
Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");
employee.getPhones().add(phone1);
employee.getPhones().add(phone2);
EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee);
EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1);
EntityDescription phone2Description = new EntityDescription("Work phone", phone1);
session.save(phone1);
session.save(phone2);
session.save(employee);
session.save(employeeDescription);
session.save(phone1Description);
session.save(phone2Description);
session.flush();
session.clear();
List<EntityDescription> descriptions = session.createQuery("from EntityDescription").getResultList();
assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue();
assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue();
assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue();
}
}

View File

@ -1,161 +0,0 @@
package com.baeldung.hibernate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.util.GeometricShapeFactory;
import geodb.GeoDB;
public class HibernateSpatialIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void shouldConvertWktToGeometry() throws ParseException {
Geometry geometry = wktToGeometry("POINT (2 5)");
assertEquals("Point", geometry.getGeometryType());
assertTrue(geometry instanceof Point);
}
@Test
public void shouldInsertAndSelectPoints() throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry("POINT (1 1)"));
session.persist(entity);
PointEntity fromDb = session.find(PointEntity.class, entity.getId());
assertEquals("POINT (1 1)", fromDb.getPoint().toString());
}
@Test
public void shouldSelectDisjointPoints() throws ParseException {
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Point point = (Point) wktToGeometry("POINT (3 4)");
Query query = session.createQuery("select p from PointEntity p "
+ "where disjoint(p.point, :point) = true", PointEntity.class);
query.setParameter("point", point);
assertEquals("POINT (1 2)", ((PointEntity) query.getResultList().get(0)).getPoint().toString());
assertEquals("POINT (5 6)", ((PointEntity) query.getResultList().get(1)).getPoint().toString());
}
@Test
public void shouldSelectAllPointsWithinPolygon() throws ParseException {
insertPoint("POINT (1 1)");
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Query query = session.createQuery("select p from PointEntity p where within(p.point, :area) = true",
PointEntity.class);
query.setParameter("area", wktToGeometry("POLYGON((0 0, 0 5, 5 5, 5 0, 0 0))"));
assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString()))
.containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)");
}
@Test
public void shouldSelectAllPointsWithinRadius() throws ParseException {
insertPoint("POINT (1 1)");
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true",
PointEntity.class);
query.setParameter("circle", createCircle(0.0, 0.0, 5));
assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString()))
.containsOnly("POINT (1 1)", "POINT (1 2)");
}
@Test
public void shouldSelectAdjacentPolygons() throws ParseException {
insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))");
insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))");
insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))");
Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true",
PolygonEntity.class);
query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))"));
assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString()))
.containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))");
}
private void insertPoint(String point) throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry(point));
session.persist(entity);
}
private void insertPolygon(String polygon) throws ParseException {
PolygonEntity entity = new PolygonEntity();
entity.setPolygon((Polygon) wktToGeometry(polygon));
session.persist(entity);
}
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
Geometry geom = null;
geom = fromText.read(wellKnownText);
return geom;
}
private static Geometry createCircle(double x, double y, double radius) {
GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
shapeFactory.setNumPoints(32);
shapeFactory.setCentre(new Coordinate(x, y));
shapeFactory.setSize(radius * 2);
return shapeFactory.createCircle();
}
public static Properties getProperties(String propertyFile) throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(propertyFile);
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -1,89 +0,0 @@
package com.baeldung.hibernate;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Pet;
public class InheritanceMappingIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenSubclasses_whenQuerySingleTableSuperclass_thenOk() {
Book book = new Book(1, "1984", "George Orwell");
session.save(book);
Pen pen = new Pen(2, "my pen", "blue");
session.save(pen);
assertThat(session.createQuery("from MyProduct")
.getResultList()
.size()).isEqualTo(2);
}
@Test
public void givenSubclasses_whenQueryMappedSuperclass_thenOk() {
MyEmployee emp = new MyEmployee(1, "john", "baeldung");
session.save(emp);
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Person")
.getResultList()
.size()).isEqualTo(1);
}
@Test
public void givenSubclasses_whenQueryJoinedTableSuperclass_thenOk() {
Pet pet = new Pet(1, "dog", "lassie");
session.save(pet);
assertThat(session.createQuery("from Animal")
.getResultList()
.size()).isEqualTo(1);
}
@Test
public void givenSubclasses_whenQueryTablePerClassSuperclass_thenOk() {
Car car = new Car(1, "audi", "xyz");
session.save(car);
assertThat(session.createQuery("from Vehicle")
.getResultList()
.size()).isEqualTo(1);
}
@Test
public void givenSubclasses_whenQueryNonMappedInterface_thenOk() {
Bag bag = new Bag(1, "large");
session.save(bag);
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item")
.getResultList()
.size()).isEqualTo(0);
}
}

View File

@ -1,98 +0,0 @@
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();
}
}

View File

@ -1,128 +0,0 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.TemporalValues;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.TimeZone;
import static org.assertj.core.api.Assertions.assertThat;
public class TemporalValuesUnitTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory().withOptions()
.jdbcTimeZone(TimeZone.getTimeZone("UTC"))
.openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from temporalvalues").executeUpdate();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenEntity_whenMappingSqlTypes_thenTemporalIsSelectedAutomatically() {
TemporalValues temporalValues = new TemporalValues();
temporalValues.setSqlDate(java.sql.Date.valueOf("2017-11-15"));
temporalValues.setSqlTime(java.sql.Time.valueOf("15:30:14"));
temporalValues.setSqlTimestamp(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
session.save(temporalValues);
session.flush();
session.clear();
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
assertThat(temporalValues.getSqlDate()).isEqualTo(java.sql.Date.valueOf("2017-11-15"));
assertThat(temporalValues.getSqlTime()).isEqualTo(java.sql.Time.valueOf("15:30:14"));
assertThat(temporalValues.getSqlTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
}
@Test
public void givenEntity_whenMappingUtilDateType_thenTemporalIsSpecifiedExplicitly() throws Exception {
TemporalValues temporalValues = new TemporalValues();
temporalValues.setUtilDate(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
temporalValues.setUtilTime(new SimpleDateFormat("HH:mm:ss").parse("15:30:14"));
temporalValues.setUtilTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.332"));
session.save(temporalValues);
session.flush();
session.clear();
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
assertThat(temporalValues.getUtilDate()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
assertThat(temporalValues.getUtilTime()).isEqualTo(new SimpleDateFormat("HH:mm:ss").parse("15:30:14"));
assertThat(temporalValues.getUtilTimestamp()).isEqualTo(java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
}
@Test
public void givenEntity_whenMappingCalendarType_thenTemporalIsSpecifiedExplicitly() throws Exception {
TemporalValues temporalValues = new TemporalValues();
Calendar calendarDate = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendarDate.set(Calendar.YEAR, 2017);
calendarDate.set(Calendar.MONTH, 10);
calendarDate.set(Calendar.DAY_OF_MONTH, 15);
temporalValues.setCalendarDate(calendarDate);
Calendar calendarTimestamp = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendarTimestamp.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322"));
temporalValues.setCalendarTimestamp(calendarTimestamp);
session.save(temporalValues);
session.flush();
session.clear();
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
assertThat(temporalValues.getCalendarDate().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd").parse("2017-11-15"));
assertThat(temporalValues.getCalendarTimestamp().getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2017-11-15 15:30:14.322"));
}
@Test
public void givenEntity_whenMappingJavaTimeTypes_thenTemporalIsSelectedAutomatically() {
TemporalValues temporalValues = new TemporalValues();
temporalValues.setLocalDate(LocalDate.parse("2017-11-15"));
temporalValues.setLocalTime(LocalTime.parse("15:30:18"));
temporalValues.setOffsetTime(OffsetTime.parse("08:22:12+01:00"));
System.out.println("********"+OffsetTime.parse("08:22:12+01:00").toString());
temporalValues.setInstant(Instant.parse("2017-11-15T08:22:12Z"));
temporalValues.setLocalDateTime(LocalDateTime.parse("2017-11-15T08:22:12"));
temporalValues.setOffsetDateTime(OffsetDateTime.parse("2017-11-15T08:22:12+01:00"));
temporalValues.setZonedDateTime(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]"));
session.save(temporalValues);
session.flush();
session.clear();
temporalValues = session.get(TemporalValues.class, temporalValues.getId());
assertThat(temporalValues.getLocalDate()).isEqualTo(LocalDate.parse("2017-11-15"));
assertThat(temporalValues.getLocalTime()).isEqualTo(LocalTime.parse("15:30:18"));
//assertThat(temporalValues.getOffsetTime()).isEqualTo(OffsetTime.parse("08:22:12+01:00"));
assertThat(temporalValues.getInstant()).isEqualTo(Instant.parse("2017-11-15T08:22:12Z"));
assertThat(temporalValues.getLocalDateTime()).isEqualTo(LocalDateTime.parse("2017-11-15T08:22:12"));
//assertThat(temporalValues.getOffsetDateTime()).isEqualTo(OffsetDateTime.parse("2017-11-15T08:22:12+01:00"));
assertThat(temporalValues.getZonedDateTime()).isEqualTo(ZonedDateTime.parse("2017-11-15T08:22:12+01:00[Europe/Paris]"));
}
}

View File

@ -1,87 +0,0 @@
package com.baeldung.hibernate.aggregatefunctions;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.pojo.Student;
public class AggregateFunctionsIntegrationTest {
private static Session session;
private static Transaction transaction;
@BeforeClass
public static final void setup() throws HibernateException, IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
transaction = session.beginTransaction();
Student jonas = new Student("Jonas", 22);
session.save(jonas);
Student sally = new Student("Sally", 20);
session.save(sally);
Student simon = new Student("Simon", 25);
session.save(simon);
Student raven = new Student("Raven", 21);
session.save(raven);
Student sam = new Student("Sam", 23);
session.save(sam);
}
@AfterClass
public static final void teardown() {
if (session != null) {
transaction.rollback();
session.close();
}
}
@Test
public void whenMaxAge_ThenReturnValue() {
int maxAge = (int) session.createQuery("SELECT MAX(age) from Student")
.getSingleResult();
assertThat(maxAge).isEqualTo(25);
}
@Test
public void whenMinAge_ThenReturnValue() {
int minAge = (int) session.createQuery("SELECT MIN(age) from Student")
.getSingleResult();
assertThat(minAge).isEqualTo(20);
}
@Test
public void whenAverageAge_ThenReturnValue() {
Double avgAge = (Double) session.createQuery("SELECT AVG(age) from Student")
.getSingleResult();
assertThat(avgAge).isEqualTo(22.2);
}
@Test
public void whenCountAll_ThenReturnValue() {
Long totalStudents = (Long) session.createQuery("SELECT COUNT(*) from Student")
.getSingleResult();
assertThat(totalStudents).isEqualTo(5);
}
@Test
public void whenSumOfAllAges_ThenReturnValue() {
Long sumOfAllAges = (Long) session.createQuery("SELECT SUM(age) from Student")
.getSingleResult();
assertThat(sumOfAllAges).isEqualTo(111);
}
}

View File

@ -1,200 +0,0 @@
package com.baeldung.hibernate.converter;
import java.io.IOException;
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.Person;
import com.baeldung.hibernate.pojo.PersonName;
import static org.junit.Assert.assertEquals;
public class PersonNameConverterUnitTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from personTable")
.executeUpdate();
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenPersonName_WhenSaving_ThenNameAndSurnameConcat() {
final String name = "name";
final String surname = "surname";
PersonName personName = new PersonName();
personName.setName(name);
personName.setSurname(surname);
Person person = new Person();
person.setPersonName(personName);
Long id = (Long) session.save(person);
session.flush();
session.clear();
String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id")
.setParameter("id", id)
.getSingleResult();
assertEquals(surname + ", " + name, dbPersonName);
Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(dbPerson.getPersonName()
.getName(), name);
assertEquals(dbPerson.getPersonName()
.getSurname(), surname);
}
@Test
public void givenPersonNameNull_WhenSaving_ThenNullStored() {
final String name = null;
final String surname = null;
PersonName personName = new PersonName();
personName.setName(name);
personName.setSurname(surname);
Person person = new Person();
person.setPersonName(personName);
Long id = (Long) session.save(person);
session.flush();
session.clear();
String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id")
.setParameter("id", id)
.getSingleResult();
assertEquals("", dbPersonName);
Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(dbPerson.getPersonName(), null);
}
@Test
public void givenPersonNameWithoutName_WhenSaving_ThenNotNameStored() {
final String name = null;
final String surname = "surname";
PersonName personName = new PersonName();
personName.setName(name);
personName.setSurname(surname);
Person person = new Person();
person.setPersonName(personName);
Long id = (Long) session.save(person);
session.flush();
session.clear();
String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id")
.setParameter("id", id)
.getSingleResult();
assertEquals("surname, ", dbPersonName);
Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(dbPerson.getPersonName()
.getName(), name);
assertEquals(dbPerson.getPersonName()
.getSurname(), surname);
}
@Test
public void givenPersonNameWithoutSurName_WhenSaving_ThenNotSurNameStored() {
final String name = "name";
final String surname = null;
PersonName personName = new PersonName();
personName.setName(name);
personName.setSurname(surname);
Person person = new Person();
person.setPersonName(personName);
Long id = (Long) session.save(person);
session.flush();
session.clear();
String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id")
.setParameter("id", id)
.getSingleResult();
assertEquals("name", dbPersonName);
Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(dbPerson.getPersonName()
.getName(), name);
assertEquals(dbPerson.getPersonName()
.getSurname(), surname);
}
@Test
public void givenPersonNameEmptyFields_WhenSaving_ThenFielsNotStored() {
final String name = "";
final String surname = "";
PersonName personName = new PersonName();
personName.setName(name);
personName.setSurname(surname);
Person person = new Person();
person.setPersonName(personName);
Long id = (Long) session.save(person);
session.flush();
session.clear();
String dbPersonName = (String) session.createNativeQuery("select p.personName from PersonTable p where p.id = :id")
.setParameter("id", id)
.getSingleResult();
assertEquals("", dbPersonName);
Person dbPerson = session.createNativeQuery("select * from PersonTable p where p.id = :id", Person.class)
.setParameter("id", id)
.getSingleResult();
assertEquals(dbPerson.getPersonName(), null);
}
}

View File

@ -1,89 +0,0 @@
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();
}
}

View File

@ -1,90 +0,0 @@
package com.baeldung.hibernate.customtypes;
import com.baeldung.hibernate.HibernateUtil;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.time.LocalDate;
import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate;
public class HibernateCustomTypesManualTest {
@Test
public void givenEmployee_whenSavedWithCustomTypes_thenEntityIsSaved() throws IOException {
final OfficeEmployee e = new OfficeEmployee();
e.setDateOfJoining(LocalDate.now());
PhoneNumber number = new PhoneNumber(1, 222, 8781902);
e.setEmployeeNumber(number);
Address empAdd = new Address();
empAdd.setAddressLine1("Street");
empAdd.setAddressLine2("Area");
empAdd.setCity("City");
empAdd.setCountry("Country");
empAdd.setZipCode(100);
e.setEmpAddress(empAdd);
Salary empSalary = new Salary();
empSalary.setAmount(1000L);
empSalary.setCurrency("USD");
e.setSalary(empSalary);
doInHibernate(this::sessionFactory, session -> {
session.save(e);
boolean contains = session.contains(e);
Assert.assertTrue(contains);
});
}
@Test
public void givenEmployee_whenCustomTypeInQuery_thenReturnEntity() throws IOException {
final OfficeEmployee e = new OfficeEmployee();
e.setDateOfJoining(LocalDate.now());
PhoneNumber number = new PhoneNumber(1, 222, 8781902);
e.setEmployeeNumber(number);
Address empAdd = new Address();
empAdd.setAddressLine1("Street");
empAdd.setAddressLine2("Area");
empAdd.setCity("City");
empAdd.setCountry("Country");
empAdd.setZipCode(100);
e.setEmpAddress(empAdd);
Salary empSalary = new Salary();
empSalary.setAmount(1000L);
empSalary.setCurrency("USD");
e.setSalary(empSalary);
doInHibernate(this::sessionFactory, session -> {
session.save(e);
Query query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode");
query.setParameter("pinCode",100);
int size = query.list().size();
Assert.assertEquals(1, size);
});
}
private SessionFactory sessionFactory() {
try {
return HibernateUtil.getSessionFactory("hibernate-customtypes.properties");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -1,425 +0,0 @@
package com.baeldung.hibernate.exception;
import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import org.hibernate.AnnotationException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PropertyValueException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.query.NativeQuery;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateExceptionUnitTest {
private static final Logger logger = LoggerFactory
.getLogger(HibernateExceptionUnitTest.class);
private SessionFactory sessionFactory;
@Before
public void setUp() throws IOException {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Rule
public ExpectedException thrown = ExpectedException.none();
private Configuration getConfiguration() {
Configuration cfg = new Configuration();
cfg.setProperty(AvailableSettings.DIALECT,
"org.hibernate.dialect.H2Dialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
cfg.setProperty(AvailableSettings.DRIVER, "org.h2.Driver");
cfg.setProperty(AvailableSettings.URL,
"jdbc:h2:mem:myexceptiondb2;DB_CLOSE_DELAY=-1");
cfg.setProperty(AvailableSettings.USER, "sa");
cfg.setProperty(AvailableSettings.PASS, "");
return cfg;
}
@Test
public void whenQueryExecutedWithUnmappedEntity_thenMappingException() {
thrown.expectCause(isA(MappingException.class));
thrown.expectMessage("Unknown entity: java.lang.String");
Session session = sessionFactory.openSession();
NativeQuery<String> query = session
.createNativeQuery("select name from PRODUCT", String.class);
query.getResultList();
}
@Test
@SuppressWarnings("rawtypes")
public void whenQueryExecuted_thenOK() {
Session session = sessionFactory.openSession();
NativeQuery query = session
.createNativeQuery("select name from PRODUCT");
List results = query.getResultList();
assertNotNull(results);
}
@Test
public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
thrown.expect(AnnotationException.class);
thrown.expectMessage("No identifier specified for entity");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(EntityWithNoId.class);
cfg.buildSessionFactory();
}
@Test
public void givenMissingTable_whenSchemaValidated_thenSchemaManagementException() {
thrown.expect(SchemaManagementException.class);
thrown.expectMessage("Schema-validation: missing table");
Configuration cfg = getConfiguration();
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "validate");
cfg.addAnnotatedClass(Product.class);
cfg.buildSessionFactory();
}
@Test
public void whenWrongDialectSpecified_thenCommandAcceptanceException() {
thrown.expect(SchemaManagementException.class);
thrown.expectCause(isA(CommandAcceptanceException.class));
thrown.expectMessage("Halting on error : Error executing DDL");
Configuration cfg = getConfiguration();
cfg.setProperty(AvailableSettings.DIALECT,
"org.hibernate.dialect.MySQLDialect");
cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update");
// This does not work due to hibernate bug
// cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true");
cfg.getProperties()
.put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true);
cfg.addAnnotatedClass(Product.class);
cfg.buildSessionFactory();
}
@Test
public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown
.expectMessage("SQLGrammarException: could not prepare statement");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(Product.class);
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product = new Product();
product.setId(1);
product.setName("Product 1");
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
closeSessionFactoryQuietly(sessionFactory);
}
}
@Test
public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown
.expectMessage("SQLGrammarException: could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery(
"select * from NON_EXISTING_TABLE", Product.class);
query.getResultList();
}
@Test
public void whenDuplicateIdSaved_thenConstraintViolationException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(ConstraintViolationException.class));
thrown.expectMessage(
"ConstraintViolationException: could not execute statement");
Session session = null;
Transaction transaction = null;
for (int i = 1; i <= 2; i++) {
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product = new Product();
product.setId(1);
product.setName("Product " + i);
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
}
@Test
public void givenNotNullPropertyNotSet_whenEntityIdSaved_thenPropertyValueException() {
thrown.expect(isA(PropertyValueException.class));
thrown.expectMessage(
"not-null property references a null or transient value");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product = new Product();
product.setId(1);
session.save(product);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class));
thrown.expectMessage(
"org.hibernate.exception.DataException: could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery(
"select * from PRODUCT where id='wrongTypeId'", Product.class);
query.getResultList();
}
@Test
public void givenSessionContainingAnId_whenIdAssociatedAgain_thenNonUniqueObjectException() {
thrown.expect(isA(NonUniqueObjectException.class));
thrown.expectMessage(
"A different object with the same identifier value was already associated with the session");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(1);
product1.setName("Product 1");
session.save(product1);
Product product2 = new Product();
product2.setId(1);
product2.setName("Product 2");
session.save(product2);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void whenDeletingADeletedObject_thenOptimisticLockException() {
thrown.expect(isA(OptimisticLockException.class));
thrown.expectMessage(
"Batch update returned unexpected row count from update");
thrown.expectCause(isA(StaleStateException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(12);
product1.setName("Product 12");
session.save(product1);
transaction.commit();
session.close();
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product2 = session.get(Product.class, 12);
session.createNativeQuery("delete from Product where id=12")
.executeUpdate();
// We need to refresh to fix the error.
// session.refresh(product2);
session.delete(product2);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void whenUpdatingNonExistingObject_thenStaleStateException() {
thrown.expect(isA(OptimisticLockException.class));
thrown
.expectMessage("Row was updated or deleted by another transaction");
thrown.expectCause(isA(StaleObjectStateException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(15);
product1.setName("Product1");
session.update(product1);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test
public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() {
thrown.expect(isA(TransactionException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(15);
product1.setName("Product1");
session.save(product1);
transaction.setRollbackOnly();
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
private void rollbackTransactionQuietly(Transaction transaction) {
if (transaction != null && transaction.isActive()) {
try {
transaction.rollback();
} catch (Exception e) {
logger.error("Exception while rolling back transaction", e);
}
}
}
private void closeSessionQuietly(Session session) {
if (session != null) {
try {
session.close();
} catch (Exception e) {
logger.error("Exception while closing session", e);
}
}
}
private void closeSessionFactoryQuietly(SessionFactory sessionFactory) {
if (sessionFactory != null) {
try {
sessionFactory.close();
} catch (Exception e) {
logger.error("Exception while closing sessionFactory", e);
}
}
}
@Test
public void givenExistingEntity_whenIdUpdated_thenHibernateException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(HibernateException.class));
thrown.expectMessage(
"identifier of an instance of com.baeldung.hibernate.exception.Product was altered");
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(222);
product1.setName("Product 222");
session.save(product1);
transaction.commit();
closeSessionQuietly(session);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product2 = session.get(Product.class, 222);
product2.setId(333);
session.save(product2);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
}

View File

@ -1,63 +0,0 @@
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());
}
}

View File

@ -1,57 +0,0 @@
package com.baeldung.hibernate.joincolumn;
import com.baeldung.hibernate.HibernateUtil;
import java.io.IOException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JoinColumnIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenOfficeEntity_setAddress_shouldPersist() {
Office office = new Office();
OfficeAddress address = new OfficeAddress();
address.setZipCode("11-111");
office.setAddress(address);
session.save(office);
session.flush();
session.clear();
}
@Test
public void givenEmployeeEntity_setEmails_shouldPersist() {
OfficialEmployee employee = new OfficialEmployee();
Email email = new Email();
email.setAddress("example@email.com");
email.setEmployee(employee);
session.save(employee);
session.flush();
session.clear();
}
}

View File

@ -1,121 +0,0 @@
package com.baeldung.hibernate.jpacriteriabuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.entities.DeptEmployee;
import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchService;
import com.baeldung.hibernate.jpacriteriabuilder.service.EmployeeSearchServiceImpl;
public class EmployeeSearchServiceIntegrationTest {
private EntityManager entityManager;
private EmployeeSearchService searchService;
private Session session;
@Before
public final void setup() throws HibernateException, IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
entityManager = session.getEntityManagerFactory()
.createEntityManager();
searchService = new EmployeeSearchServiceImpl(entityManager);
entityManager.getTransaction()
.begin();
Department department = new Department("Pre Sales");
DeptEmployee employee = new DeptEmployee("John Smith", "001", "Manager", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("Ian Evans", "002", "Associate", department);
entityManager.persist(department);
entityManager.persist(employee);
department = new Department("Copporate Sales");
employee = new DeptEmployee("Robert Carter", "003", "Manager", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("John Carter", "004", "Senior Manager", department);
entityManager.persist(employee);
employee = new DeptEmployee("David Guetta", "009", "Associate", department);
entityManager.persist(department);
entityManager.persist(employee);
department = new Department("Post Sales");
employee = new DeptEmployee("Robert Jonas", "005", "Director", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("John Ferros", "006", "Junior Associate", department);
entityManager.persist(department);
entityManager.persist(employee);
department = new Department("Client Support");
employee = new DeptEmployee("Robert Mcclements", "007", "Director", department);
entityManager.persist(department);
entityManager.persist(employee);
employee = new DeptEmployee("Peter Parker", "008", "Manager", department);
entityManager.persist(department);
entityManager.persist(employee);
}
@After
public final void teardown() {
entityManager.getTransaction()
.rollback();
entityManager.close();
}
@Test
public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() {
List<String> titles = new ArrayList<String>() {
{
add("Manager");
add("Senior Manager");
add("Director");
}
};
List<DeptEmployee> result = searchService.filterbyTitleUsingCriteriaBuilder(titles);
assertEquals("Number of Employees does not match with expected.", 6, result.size());
assertThat(result.stream()
.map(DeptEmployee::getTitle)
.distinct()
.collect(Collectors.toList()), containsInAnyOrder(titles.toArray()));
}
@Test
public final void givenCriteriaQuery_whenSearchedUsingExpressionWithListofAuthors_thenResultIsFilteredByAuthorNames() {
List<String> titles = new ArrayList<String>() {
{
add("Manager");
add("Senior Manager");
add("Director");
}
};
List<DeptEmployee> result = searchService.filterbyTitleUsingExpression(titles);
assertEquals("Number of Employees does not match with expected.", 6, result.size());
assertThat(result.stream()
.map(DeptEmployee::getTitle)
.distinct()
.collect(Collectors.toList()), containsInAnyOrder(titles.toArray()));
}
@Test
public final void givenCriteriaQuery_whenSearchedDepartmentLike_thenResultIsFilteredByDepartment() {
List<DeptEmployee> result = searchService.searchByDepartmentQuery("Sales");
assertEquals("Number of Employees does not match with expected.", 7, result.size());
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.hibernate.lob;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.apache.commons.io.IOUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.lob.model.User;
public class LobUnitTest {
private Session session;
@Before
public void init(){
try {
session = HibernateSessionUtil.getSessionFactory("hibernate.properties")
.openSession();
} catch (HibernateException | IOException e) {
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
}
}
@After
public void close(){
if(session != null) session.close();
}
@Test
public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){
User user = new User();
try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) {
// Get Image file from the resource
if(inputStream == null) fail("Unable to get resources");
user.setId("1");
user.setName("User");
user.setPhoto(IOUtils.toByteArray(inputStream));
session.persist(user);
} catch (IOException e) {
fail("Unable to read input stream");
}
User result = session.find(User.class, "1");
assertNotNull("Query result is null", result);
assertEquals("User's name is invalid", user.getName(), result.getName() );
assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) );
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung.hibernate.multitenancy;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity(name = "Car")
@Table(name = "Car")
public class Car implements Serializable {
private static final long serialVersionUID = 1015320564683423342L;
private String brand;
@Id
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}

View File

@ -1,104 +0,0 @@
package com.baeldung.hibernate.multitenancy;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.service.ServiceRegistry;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import com.baeldung.hibernate.multitenancy.database.TenantIdNames;
public abstract class MultitenancyIntegrationTest {
public abstract String getPropertyFile();
@Mock
private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;
private SessionFactory sessionFactory;
@Before
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
Mockito.when(currentTenantIdentifierResolver.validateExistingCurrentSessions())
.thenReturn(false);
Properties properties = getHibernateProperties();
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
sessionFactory = buildSessionFactory(properties);
initTenant(TenantIdNames.MYDB1);
initTenant(TenantIdNames.MYDB2);
}
protected void initTenant(String tenantId) {
whenCurrentTenantIs(tenantId);
createCarTable();
}
protected void whenCurrentTenantIs(String tenantId) {
Mockito.when(currentTenantIdentifierResolver.resolveCurrentTenantIdentifier())
.thenReturn(tenantId);
}
protected void whenAddCar(String brand) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Car car = new Car();
car.setBrand(brand);
session.save(car);
tx.commit();
}
protected void thenCarFound(String brand) {
Session session = sessionFactory.openSession();
assertNotNull(session.get(Car.class, brand));
}
protected void thenCarNotFound(String brand) {
Session session = sessionFactory.openSession();
assertNull(session.get(Car.class, brand));
}
@SuppressWarnings("deprecation")
private void createCarTable() {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.createSQLQuery("drop table Car if exists")
.executeUpdate();
session.createSQLQuery("create table Car (brand varchar(255) primary key)")
.executeUpdate();
tx.commit();
}
private Properties getHibernateProperties() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(getPropertyFile()));
return properties;
}
private static SessionFactory buildSessionFactory(Properties properties) {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties)
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Car.class);
return metadataSources.buildMetadata()
.buildSessionFactory();
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.hibernate.multitenancy.database;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest;
public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyIntegrationTest {
@Override
public String getPropertyFile() {
return "/hibernate-database-multitenancy.properties";
}
@Test
public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException {
whenCurrentTenantIs(TenantIdNames.MYDB1);
whenAddCar("myCar");
thenCarFound("myCar");
whenCurrentTenantIs(TenantIdNames.MYDB2);
thenCarNotFound("myCar");
}
}

View File

@ -1,42 +0,0 @@
package com.baeldung.hibernate.multitenancy.database;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
@SuppressWarnings("serial")
public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
private final Map<String, ConnectionProvider> connectionProviderMap = new HashMap<>();
public MapMultiTenantConnectionProvider() throws IOException {
initConnectionProviderForTenant(TenantIdNames.MYDB1);
initConnectionProviderForTenant(TenantIdNames.MYDB2);
}
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return connectionProviderMap.values()
.iterator()
.next();
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
return connectionProviderMap.get(tenantIdentifier);
}
private void initConnectionProviderForTenant(String tenantId) throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId)));
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
this.connectionProviderMap.put(tenantId, connectionProvider);
}
}

View File

@ -1,6 +0,0 @@
package com.baeldung.hibernate.multitenancy.database;
public class TenantIdNames {
public static final String MYDB1 = "mydb1";
public static final String MYDB2 = "mydb2";
}

View File

@ -1,26 +0,0 @@
package com.baeldung.hibernate.multitenancy.schema;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest;
import com.baeldung.hibernate.multitenancy.database.TenantIdNames;
public class SchemaApproachMultitenancyIntegrationTest extends MultitenancyIntegrationTest {
@Override
public String getPropertyFile() {
return "/hibernate-schema-multitenancy.properties";
}
@Test
public void givenSchemaApproach_whenAddingEntries_thenOnlyAddedToConcreteSchema() throws IOException {
whenCurrentTenantIs(TenantIdNames.MYDB1);
whenAddCar("Ferrari");
thenCarFound("Ferrari");
whenCurrentTenantIs(TenantIdNames.MYDB2);
thenCarNotFound("Ferrari");
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.hibernate.multitenancy.schema;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.AbstractMultiTenantConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
@SuppressWarnings("serial")
public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConnectionProvider {
private final ConnectionProvider connectionProvider;
public SchemaMultiTenantConnectionProvider() throws IOException {
connectionProvider = initConnectionProvider();
}
@Override
protected ConnectionProvider getAnyConnectionProvider() {
return connectionProvider;
}
@Override
protected ConnectionProvider selectConnectionProvider(String tenantIdentifier) {
return connectionProvider;
}
@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
Connection connection = super.getConnection(tenantIdentifier);
connection.createStatement()
.execute(String.format("SET SCHEMA %s;", tenantIdentifier));
return connection;
}
private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
return connectionProvider;
}
}

View File

@ -1,6 +0,0 @@
package com.baeldung.hibernate.multitenancy.schema;
public class TenantIdNames {
public static final String MYDB1 = "mydb1";
public static final String MYDB2 = "mydb2";
}

View File

@ -1,80 +0,0 @@
package com.baeldung.hibernate.onetoone;
import com.baeldung.hibernate.onetoone.foreignkeybased.Address;
import com.baeldung.hibernate.onetoone.foreignkeybased.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class HibernateOneToOneAnnotationFKBasedIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.FOREIGN_KEY);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsert_thenCreates1to1relationship() {
User user = new User();
user.setUserName("alice@baeldung.com");
Address address = new Address();
address.setStreet("FK Street");
address.setCity("FK City");
address.setUser(user);
user.setAddress(address);
//Address entry will automatically be created by hibernate, since cascade type is specified as ALL
session.persist(user);
session.getTransaction().commit();
assert1to1InsertedData();
}
private void assert1to1InsertedData() {
@SuppressWarnings("unchecked")
List<User> userList = session.createQuery("FROM User").list();
assertNotNull(userList);
assertEquals(1, userList.size());
User user = userList.get(0);
assertEquals("alice@baeldung.com", user.getUserName());
Address address = user.getAddress();
assertNotNull(address);
assertEquals("FK Street", address.getStreet());
assertEquals("FK City", address.getCity());
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,80 +0,0 @@
package com.baeldung.hibernate.onetoone;
import com.baeldung.hibernate.onetoone.jointablebased.Employee;
import com.baeldung.hibernate.onetoone.jointablebased.WorkStation;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class HibernateOneToOneAnnotationJTBasedIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.JOIN_TABLE_BASED);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsert_thenCreates1to1relationship() {
Employee employee = new Employee();
employee.setName("bob@baeldung.com");
WorkStation workStation = new WorkStation();
workStation.setWorkstationNumber(626);
workStation.setFloor("Sixth Floor");
employee.setWorkStation(workStation);
workStation.setEmployee(employee);
session.persist(employee);
session.getTransaction().commit();
assert1to1InsertedData();
}
private void assert1to1InsertedData() {
@SuppressWarnings("unchecked")
List<Employee> employeeList = session.createQuery("FROM Employee").list();
assertNotNull(employeeList);
assertEquals(1, employeeList.size());
Employee employee = employeeList.get(0);
assertEquals("bob@baeldung.com", employee.getName());
WorkStation workStation = employee.getWorkStation();
assertNotNull(workStation);
assertEquals((long) 626, (long) workStation.getWorkstationNumber());
assertEquals("Sixth Floor", workStation.getFloor());
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,79 +0,0 @@
package com.baeldung.hibernate.onetoone;
import com.baeldung.hibernate.onetoone.sharedkeybased.Address;
import com.baeldung.hibernate.onetoone.sharedkeybased.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class HibernateOneToOneAnnotationSPKBasedIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory(Strategy.SHARED_PRIMARY_KEY);
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsert_thenCreates1to1relationship() {
User user = new User();
user.setUserName("alice@baeldung.com");
Address address = new Address();
address.setStreet("SPK Street");
address.setCity("SPK City");
address.setUser(user);
user.setAddress(address);
//Address entry will automatically be created by hibernate, since cascade type is specified as ALL
session.persist(user);
session.getTransaction().commit();
assert1to1InsertedData();
}
private void assert1to1InsertedData() {
@SuppressWarnings("unchecked")
List<User> userList = session.createQuery("FROM User").list();
assertNotNull(userList);
assertEquals(1, userList.size());
User user = userList.get(0);
assertEquals("alice@baeldung.com", user.getUserName());
Address address = user.getAddress();
assertNotNull(address);
assertEquals("SPK Street", address.getStreet());
assertEquals("SPK City", address.getCity());
}
@After
public void tearDown() {
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,146 +0,0 @@
package com.baeldung.hibernate.optimisticlocking;
import java.io.IOException;
import java.util.Arrays;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.OptimisticLockException;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.HibernateUtil;
public class OptimisticLockingIntegrationTest {
private static SessionFactory sessionFactory;
@Before
public void setUp() throws IOException {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH");
OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course));
course.setStudent(student);
entityManager.persist(course);
entityManager.persist(student);
entityManager.getTransaction()
.commit();
entityManager.close();
}
@After
public void clean() throws IOException {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L);
OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L);
entityManager.remove(course);
entityManager.remove(student);
entityManager.getTransaction()
.commit();
entityManager.close();
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
em.refresh(student, LockModeType.OPTIMISTIC);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
em.lock(student, LockModeType.OPTIMISTIC);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,162 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import com.vividsolutions.jts.util.Assert;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.*;
import java.io.IOException;
import java.util.Arrays;
public class BasicPessimisticLockingIntegrationTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void setUp() throws IOException {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN");
PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student);
student.setCourses(Arrays.asList(course));
entityManager.persist(course);
entityManager.persist(student);
entityManager.getTransaction()
.commit();
entityManager.close();
}
@Test
public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
Query query = entityManager.createQuery("from Student where studentId = :studentId");
query.setParameter("studentId", 1L);
query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
query.getResultList();
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
Query query2 = entityManager2.createQuery("from Student where studentId = :studentId");
query2.setParameter("studentId", 1L);
query2.setLockMode(LockModeType.PESSIMISTIC_READ);
query2.getResultList();
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE);
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
resultStudent2.setName("Change");
entityManager2.persist(resultStudent2);
entityManager2.getTransaction()
.commit();
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
@Test
public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE);
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
resultStudent2.setName("Change");
entityManager2.persist(resultStudent2);
entityManager2.getTransaction()
.commit();
entityManager.close();
entityManager2.close();
} catch (Exception e) {
Assert.isTrue(e instanceof PessimisticLockException);
}
}
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,125 +0,0 @@
package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PessimisticLockScope;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class PessimisticLockScopesIntegrationTest {
private static SessionFactory sessionFactory;
@Test
public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5));
em.persist(employee);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
@Test
public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
Address address = new Address("Poland", "Warsaw");
Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address));
em.persist(customer);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em2.getTransaction()
.rollback();
em2.close();
em3.close();
}
@Test
public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE");
PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student);
student.setCourses(Arrays.asList(course));
em.persist(course);
em.persist(student);
em.getTransaction()
.commit();
em.close();
// NORMAL SCOPE
EntityManager em2 = getEntityManagerWithOpenTransaction();
PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE);
em2.getTransaction()
.rollback();
// EXTENDED SCOPE
Map<String, Object> map = new HashMap<>();
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
em3.getTransaction()
.rollback();
em2.close();
em3.close();
}
protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
String propertyFileName = "hibernate-pessimistic-locking.properties";
if (sessionFactory == null) {
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
}
EntityManager entityManager = sessionFactory.openSession();
entityManager.getTransaction().begin();
return entityManager;
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -1,106 +0,0 @@
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);
}
}

View File

@ -1,57 +0,0 @@
package com.baeldung.hibernate.transaction;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.pojo.Post;
import com.baeldung.hibernate.transaction.PostService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
public class TransactionIntegrationTest {
private static PostService postService;
private static Session session;
private static Logger logger = LoggerFactory.getLogger(TransactionIntegrationTest.class);
@BeforeClass
public static void init() throws IOException {
Properties properties = new Properties();
properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
properties.setProperty("hibernate.connection.url", "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1");
properties.setProperty("hibernate.connection.username", "sa");
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("jdbc.password", "");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
SessionFactory sessionFactory = HibernateUtil.getSessionFactoryByProperties(properties);
session = sessionFactory.openSession();
postService = new PostService(session);
}
@Test
public void givenTitleAndBody_whenRepositoryUpdatePost_thenUpdatePost() {
Post post = new Post("This is a title", "This is a sample post");
session.persist(post);
String title = "[UPDATE] Java HowTos";
String body = "This is an updated posts on Java how-tos";
postService.updatePost(title, body, post.getId());
session.refresh(post);
assertEquals(post.getTitle(), title);
assertEquals(post.getBody(), body);
}
}

View File

@ -1,14 +0,0 @@
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

View File

@ -1,2 +0,0 @@
hibernate.multiTenancy=DATABASE
hibernate.multi_tenant_connection_provider=com.baeldung.hibernate.multitenancy.database.MapMultiTenantConnectionProvider

View File

@ -1,4 +0,0 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect

View File

@ -1,4 +0,0 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb2;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect

View File

@ -1,16 +0,0 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:myexceptiondb1;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
hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory

View File

@ -1,9 +0,0 @@
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

View File

@ -1,8 +0,0 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
hibernate.connection.username=sa
hibernate.connection.autocommit=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

View File

@ -1,7 +0,0 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS MYDB1\\;CREATE SCHEMA IF NOT EXISTS MYDB2\\;
hibernate.connection.username=sa
hibernate.connection.autocommit=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.multiTenancy=SCHEMA
hibernate.multi_tenant_connection_provider=com.baeldung.hibernate.multitenancy.schema.SchemaMultiTenantConnectionProvider

View File

@ -1,14 +0,0 @@
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.spatial.dialect.h2geodb.GeoDBDialect
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