BAEL-3091: The Prototype Pattern in Java (changed code based on valid comments from a reader)

This commit is contained in:
Vivek Balasubramaniam
2019-10-29 22:27:15 +05:30
parent db85c8f275
commit d3d5b060e7
20517 changed files with 1642290 additions and 0 deletions
@@ -0,0 +1,145 @@
package com.baeldung.hibernate;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.customtypes.LocalDateStringType;
import com.baeldung.hibernate.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;
import com.baeldung.hibernate.pojo.Post;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.TemporalValues;
import com.baeldung.hibernate.pojo.User;
import com.baeldung.hibernate.pojo.UserProfile;
import com.baeldung.hibernate.pojo.inheritance.Animal;
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.MyProduct;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
public class HibernateUtil {
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
ServiceRegistry serviceRegistry = configureServiceRegistry();
return makeSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
ServiceRegistry serviceRegistry = configureServiceRegistry(properties);
return makeSessionFactory(serviceRegistry);
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Employee.class);
metadataSources.addAnnotatedClass(Phone.class);
metadataSources.addAnnotatedClass(EntityDescription.class);
metadataSources.addAnnotatedClass(TemporalValues.class);
metadataSources.addAnnotatedClass(User.class);
metadataSources.addAnnotatedClass(Student.class);
metadataSources.addAnnotatedClass(Course.class);
metadataSources.addAnnotatedClass(Product.class);
metadataSources.addAnnotatedClass(OrderEntryPK.class);
metadataSources.addAnnotatedClass(OrderEntry.class);
metadataSources.addAnnotatedClass(OrderEntryIdClass.class);
metadataSources.addAnnotatedClass(UserProfile.class);
metadataSources.addAnnotatedClass(Book.class);
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);
metadataSources.addAnnotatedClass(Car.class);
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()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
return configureServiceRegistry(getProperties());
}
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
public static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.hibernate;
public class UnsupportedTenancyException extends Exception {
public UnsupportedTenancyException (String message) {
super(message);
}
}
@@ -0,0 +1,61 @@
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;
}
}
@@ -0,0 +1,60 @@
package com.baeldung.hibernate.criteriaquery;
import com.baeldung.hibernate.customtypes.LocalDateStringType;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
private static SessionFactory buildSessionFactory() {
try {
ServiceRegistry serviceRegistry = configureServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(Student.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder().build();
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);
}
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties).build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.hibernate.criteriaquery;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "grad_year")
private int gradYear;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getGradYear() {
return gradYear;
}
public void setGradYear(int gradYear) {
this.gradYear = gradYear;
}
}
@@ -0,0 +1,69 @@
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);
}
}
@@ -0,0 +1,169 @@
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;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.type.LocalDateType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
public LocalDateStringJavaDescriptor() {
super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE);
}
@Override
public String toString(LocalDate value) {
return LocalDateType.FORMATTER.format(value);
}
@Override
public LocalDate fromString(String string) {
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
}
@Override
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
if (value == null)
return null;
if (String.class.isAssignableFrom(type))
return (X) LocalDateType.FORMATTER.format(value);
throw unknownUnwrap(type);
}
@Override
public <X> LocalDate wrap(X value, WrapperOptions options) {
if (value == null)
return null;
if(String.class.isInstance(value))
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
throw unknownWrap(value.getClass());
}
}
@@ -0,0 +1,34 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.DiscriminatorType;
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import java.time.LocalDate;
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
public String getName() {
return "LocalDateString";
}
@Override
public LocalDate stringToObject(String xml) throws Exception {
return fromString(xml);
}
@Override
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
return '\'' + toString(value) + '\'';
}
}
@@ -0,0 +1,88 @@
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;
}
}
@@ -0,0 +1,43 @@
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);
}
}
@@ -0,0 +1,98 @@
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;
}
}
@@ -0,0 +1,39 @@
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);
}
}
@@ -0,0 +1,15 @@
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;
}
}
@@ -0,0 +1,161 @@
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");
}
}
@@ -0,0 +1,45 @@
package com.baeldung.hibernate.entities;
import java.util.List;
import javax.persistence.*;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToMany(mappedBy="department")
private List<DeptEmployee> employees;
public Department(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DeptEmployee> getEmployees() {
return employees;
}
public void setEmployees(List<DeptEmployee> employees) {
this.employees = employees;
}
}
@@ -0,0 +1,83 @@
package com.baeldung.hibernate.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
@org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) })
@Entity
public class DeptEmployee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String employeeNumber;
private String title;
private String name;
@ManyToOne
private Department department;
public DeptEmployee(String name, String employeeNumber, Department department) {
this.name = name;
this.employeeNumber = employeeNumber;
this.department = department;
}
public DeptEmployee(String name, String employeeNumber, String title, Department department) {
super();
this.name = name;
this.employeeNumber = employeeNumber;
this.title = title;
this.department = department;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@@ -0,0 +1,16 @@
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;
}
}
@@ -0,0 +1,63 @@
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;
}
}
@@ -0,0 +1,40 @@
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;
}
}
@@ -0,0 +1,35 @@
package com.baeldung.hibernate.findall;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import com.baeldung.hibernate.pojo.Student;
public class FindAll {
private Session session;
public FindAll(Session session) {
super();
this.session = session;
}
public List<Student> findAllWithJpql() {
return session.createQuery("SELECT a FROM Student a", Student.class).getResultList();
}
public List<Student> findAllWithCriteriaQuery() {
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
Root<Student> rootEntry = cq.from(Student.class);
CriteriaQuery<Student> all = cq.select(rootEntry);
TypedQuery<Student> allQuery = session.createQuery(all);
return allQuery.getResultList();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.hibernate.interceptors;
import java.io.Serializable;
import java.util.Date;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.hibernate.interceptors.entity.User;
public class CustomInterceptor extends EmptyInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
if (entity instanceof User) {
logger.info(((User) entity).toString());
}
return super.onSave(entity, id, state, propertyNames, types);
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) {
if (entity instanceof User) {
((User) entity).setLastModified(new Date());
logger.info(((User) entity).toString());
}
return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
}
}
@@ -0,0 +1,122 @@
package com.baeldung.hibernate.interceptors;
import java.io.Serializable;
import java.util.Iterator;
import org.hibernate.CallbackException;
import org.hibernate.EntityMode;
import org.hibernate.Interceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;
public class CustomInterceptorImpl implements Interceptor, Serializable {
@Override
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
// TODO Auto-generated method stub
return false;
}
@Override
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public void preFlush(Iterator entities) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public void postFlush(Iterator entities) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public Boolean isTransient(Object entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getEntityName(Object object) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getEntity(String entityName, Serializable id) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public void afterTransactionBegin(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public void beforeTransactionCompletion(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public void afterTransactionCompletion(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public String onPrepareStatement(String sql) {
// TODO Auto-generated method stub
return null;
}
}
@@ -0,0 +1,79 @@
package com.baeldung.hibernate.interceptors;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.interceptors.entity.User;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
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 = getSessionFactoryBuilder(serviceRegistry).build();
}
return sessionFactory;
}
public static SessionFactory getSessionFactoryWithInterceptor(String propertyFileName, Interceptor interceptor) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(interceptor)
.build();
}
return sessionFactory;
}
public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
return getSessionFactory().withOptions()
.interceptor(interceptor)
.openSession();
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.interceptors");
metadataSources.addAnnotatedClass(User.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
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-interceptors.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
@@ -0,0 +1,64 @@
package com.baeldung.hibernate.interceptors.entity;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity(name = "hbi_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
private String about;
@Basic
@Temporal(TemporalType.DATE)
private Date lastModified;
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public long getId() {
return id;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
@Override
public String toString() {
return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
}
}
@@ -0,0 +1,47 @@
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;
}
}
@@ -0,0 +1,41 @@
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;
}
}
@@ -0,0 +1,34 @@
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;
}
}
@@ -0,0 +1,36 @@
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;
}
}
@@ -0,0 +1,34 @@
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;
}
}
@@ -0,0 +1,131 @@
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;
}
}
@@ -0,0 +1,69 @@
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;
}
}
@@ -0,0 +1,45 @@
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;
}
}
@@ -0,0 +1,15 @@
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);
}
@@ -0,0 +1,77 @@
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);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.hibernate.lifecycle;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class DirtyDataInspector extends EmptyInterceptor {
private static final ArrayList<FootballPlayer> dirtyEntities = new ArrayList<>();
@Override
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
dirtyEntities.add((FootballPlayer) entity);
return true;
}
public static List<FootballPlayer> getDirtyEntities() {
return dirtyEntities;
}
public static void clearDirtyEntitites() {
dirtyEntities.clear();
}
}
@@ -0,0 +1,35 @@
package com.baeldung.hibernate.lifecycle;
import javax.persistence.*;
@Entity
@Table(name = "Football_Player")
public class FootballPlayer {
@Id
@GeneratedValue
private long id;
@Column
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
@@ -0,0 +1,96 @@
package com.baeldung.hibernate.lifecycle;
import org.h2.tools.RunScript;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.service.ServiceRegistry;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
public class HibernateLifecycleUtil {
private static SessionFactory sessionFactory;
private static Connection connection;
public static void init() throws Exception {
Properties hbConfigProp = getHibernateProperties();
Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class"));
connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
RunScript.execute(connection, h2InitReader);
}
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build();
}
public static void tearDown() throws Exception {
sessionFactory.close();
connection.close();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(FootballPlayer.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getHibernateProperties();
return new StandardServiceRegistryBuilder().applySettings(properties).build();
}
private static Properties getHibernateProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
public static List<EntityEntry> getManagedEntities(Session session) {
Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries();
return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList());
}
public static Transaction startTransaction(Session s) {
Transaction tx = s.getTransaction();
tx.begin();
return tx;
}
public static int queryCount(String query) throws Exception {
try (ResultSet rs = connection.createStatement().executeQuery(query)) {
rs.next();
return rs.getInt(1);
}
}
}
@@ -0,0 +1,61 @@
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;
}
}
@@ -0,0 +1,46 @@
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;
}
}
@@ -0,0 +1,47 @@
package com.baeldung.hibernate.namingstrategy;
import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.naming.PhysicalNamingStrategy;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {
@Override
public Identifier toPhysicalCatalogName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalColumnName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalSchemaName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalSequenceName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
@Override
public Identifier toPhysicalTableName(final Identifier identifier, final JdbcEnvironment jdbcEnv) {
return convertToSnakeCase(identifier);
}
private Identifier convertToSnakeCase(final Identifier identifier) {
if (identifier == null) {
return identifier;
}
final String regex = "([a-z])([A-Z])";
final String replacement = "$1_$2";
final String newName = identifier.getText()
.replaceAll(regex, replacement)
.toLowerCase();
return Identifier.toIdentifier(newName);
}
}
@@ -0,0 +1,56 @@
package com.baeldung.hibernate.namingstrategy;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Customers")
public class Customer {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
@Column(name = "email")
private String emailAddress;
public Long getId() {
return id;
}
public void setId(Long 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 String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
@@ -0,0 +1,63 @@
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;
}
}
@@ -0,0 +1,25 @@
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;
}
}
@@ -0,0 +1,60 @@
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;
}
}
@@ -0,0 +1,51 @@
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;
}
}
@@ -0,0 +1,53 @@
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;
}
}
@@ -0,0 +1,61 @@
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;
}
}
@@ -0,0 +1,60 @@
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;
}
}
@@ -0,0 +1,50 @@
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;
}
}
@@ -0,0 +1,114 @@
package com.baeldung.hibernate.operations;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.baeldung.hibernate.pojo.Movie;
/**
*
*Class to illustrate the usage of EntityManager API.
*/
public class HibernateOperations {
private static final EntityManagerFactory emf;
/**
* Static block for creating EntityManagerFactory. The Persistence class looks for META-INF/persistence.xml in the classpath.
*/
static {
emf = Persistence.createEntityManagerFactory("com.baeldung.movie_catalog");
}
/**
* Static method returning EntityManager.
* @return EntityManager
*/
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
/**
* Saves the movie entity into the database. Here we are using Application Managed EntityManager, hence should handle transactions by ourselves.
*/
public void saveMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = new Movie();
movie.setId(1L);
movie.setMovieName("The Godfather");
movie.setReleaseYear(1972);
movie.setLanguage("English");
em.persist(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the querying support in EntityManager when the result is a single object.
* @return Movie
*/
public Movie queryForMovieById() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = (Movie) em.createQuery("SELECT movie from Movie movie where movie.id = ?1")
.setParameter(1, new Long(1L))
.getSingleResult();
return movie;
}
/**
* Method to illustrate the querying support in EntityManager when the result is a list.
* @return
*/
public List<?> queryForMovies() {
EntityManager em = HibernateOperations.getEntityManager();
List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
.setParameter(1, "English")
.getResultList();
return movies;
}
/**
* Method to illustrate the usage of find() method.
* @param movieId
* @return Movie
*/
public Movie getMovie(Long movieId) {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = em.find(Movie.class, new Long(movieId));
return movie;
}
/**
* Method to illustrate the usage of merge() function.
*/
public void mergeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
Movie movie = getMovie(1L);
em.detach(movie);
movie.setLanguage("Italian");
em.getTransaction()
.begin();
em.merge(movie);
em.getTransaction()
.commit();
}
/**
* Method to illustrate the usage of remove() function.
*/
public void removeMovie() {
EntityManager em = HibernateOperations.getEntityManager();
em.getTransaction()
.begin();
Movie movie = em.find(Movie.class, new Long(1L));
em.remove(movie);
em.getTransaction()
.commit();
}
}
@@ -0,0 +1,48 @@
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;
}
}
@@ -0,0 +1,70 @@
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;
}
}
@@ -0,0 +1,80 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Entity
@Table(name = "Customers")
public class Customer {
@Id
private int id;
private String firstName;
private String lastName;
private String customerAttributeJSON;
@Convert(converter = HashMapConverter.class)
private Map<String, Object> customerAttributes;
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 String getCustomerAttributeJSON() {
return customerAttributeJSON;
}
public void setCustomerAttributeJSON(String customerAttributeJSON) {
this.customerAttributeJSON = customerAttributeJSON;
}
public Map<String, Object> getCustomerAttributes() {
return customerAttributes;
}
public void setCustomerAttributes(Map<String, Object> customerAttributes) {
this.customerAttributes = customerAttributes;
}
private static final ObjectMapper objectMapper = new ObjectMapper();
public void serializeCustomerAttributes() throws JsonProcessingException {
this.customerAttributeJSON = objectMapper.writeValueAsString(customerAttributes);
}
public void deserializeCustomerAttributes() throws IOException {
this.customerAttributes = objectMapper.readValue(customerAttributeJSON, Map.class);
}
}
@@ -0,0 +1,47 @@
package com.baeldung.hibernate.persistjson;
import java.io.IOException;
import java.util.Map;
import javax.persistence.AttributeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.hibernate.interceptors.CustomInterceptor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HashMapConverter implements AttributeConverter<Map<String, Object>, String> {
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Map<String, Object> customerInfo) {
String customerInfoJson = null;
try {
customerInfoJson = objectMapper.writeValueAsString(customerInfo);
} catch (final JsonProcessingException e) {
logger.error("JSON writing error", e);
}
return customerInfoJson;
}
@Override
public Map<String, Object> convertToEntityAttribute(String customerInfoJSON) {
Map<String, Object> customerInfo = null;
try {
customerInfo = objectMapper.readValue(customerInfoJSON, Map.class);
} catch (final IOException e) {
logger.error("JSON reading error", e);
}
return customerInfo;
}
}
@@ -0,0 +1,34 @@
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;
}
}
@@ -0,0 +1,58 @@
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;
}
}
@@ -0,0 +1,49 @@
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;
}
}
@@ -0,0 +1,47 @@
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;
}
}
@@ -0,0 +1,27 @@
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;
}
}
@@ -0,0 +1,46 @@
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;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Course {
@Id
@GeneratedValue
private UUID courseId;
public UUID getCourseId() {
return courseId;
}
public void setCourseId(UUID courseId) {
this.courseId = courseId;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator")
@TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value")
private long depId;
public long getDepId() {
return depId;
}
public void setDepId(long depId) {
this.depId = depId;
}
}
@@ -0,0 +1,87 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.*;
import javax.persistence.Entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Where(clause = "deleted = false")
@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int"))
@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private long grossIncome;
private int taxInPercents;
private boolean deleted;
public long getTaxJavaWay() {
return grossIncome * taxInPercents / 100;
}
@Formula("grossIncome * taxInPercents / 100")
private long tax;
@OneToMany
@JoinColumn(name = "employee_id")
@Where(clause = "deleted = false")
private Set<Phone> phones = new HashSet<>(0);
public Employee() {
}
public Employee(long grossIncome, int taxInPercents) {
this.grossIncome = grossIncome;
this.taxInPercents = taxInPercents;
}
public Integer getId() {
return id;
}
public long getGrossIncome() {
return grossIncome;
}
public int getTaxInPercents() {
return taxInPercents;
}
public long getTax() {
return tax;
}
public void setId(Integer id) {
this.id = id;
}
public void setGrossIncome(long grossIncome) {
this.grossIncome = grossIncome;
}
public void setTaxInPercents(int taxInPercents) {
this.taxInPercents = taxInPercents;
}
public boolean getDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Set<Phone> getPhones() {
return phones;
}
}
@@ -0,0 +1,55 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.Any;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class EntityDescription implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String description;
@Any(
metaDef = "EntityDescriptionMetaDef",
metaColumn = @Column(name = "entity_type")
)
@JoinColumn(name = "entity_id")
private Serializable entity;
public EntityDescription() {
}
public EntityDescription(String description, Serializable entity) {
this.description = description;
this.entity = entity;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Serializable getEntity() {
return entity;
}
public void setEntity(Serializable entity) {
this.entity = entity;
}
}
@@ -0,0 +1,52 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "MOVIE")
public class Movie {
@Id
private Long id;
private String movieName;
private Integer releaseYear;
private String language;
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public Integer getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(Integer releaseYear) {
this.releaseYear = releaseYear;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
@Entity
public class OrderEntry {
@EmbeddedId
private OrderEntryPK entryId;
public OrderEntryPK getEntryId() {
return entryId;
}
public void setEntryId(OrderEntryPK entryId) {
this.entryId = entryId;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity
@IdClass(OrderEntryPK.class)
public class OrderEntryIdClass {
@Id
private long orderId;
@Id
private long productId;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.hibernate.pojo;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Embeddable;
@Embeddable
public class OrderEntryPK implements Serializable {
private long orderId;
private long productId;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderEntryPK pk = (OrderEntryPK) o;
return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
}
@@ -0,0 +1,32 @@
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;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.hibernate.pojo;
import java.io.Serializable;
public class PersonName implements Serializable {
private static final long serialVersionUID = 7883094644631050150L;
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
@Entity
public class Phone implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private boolean deleted;
private String number;
public Phone() {
}
public Phone(String number) {
this.number = number;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Point;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class PointEntity {
@Id
@GeneratedValue
private Long id;
@Column(columnDefinition="BINARY(2048)")
private Point point;
public PointEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
@Override
public String toString() {
return "PointEntity{" + "id=" + id + ", point=" + point + '}';
}
}
@@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Polygon;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class PolygonEntity {
@Id
@GeneratedValue
private Long id;
private Polygon polygon;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Polygon getPolygon() {
return polygon;
}
public void setPolygon(Polygon polygon) {
this.polygon = polygon;
}
@Override
public String toString() {
return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}';
}
}
@@ -0,0 +1,59 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue
private int id;
private String title;
private String body;
public Post() { }
public Post(String title, String body) {
this.title = title;
this.body = body;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "Post{" +
"id=" + id +
", title='" + title + '\'' +
", body='" + body + '\'' +
'}';
}
}
@@ -0,0 +1,26 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
public class Product {
@Id
@GeneratedValue(generator = "prod-generator")
@GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator")
private String prodId;
public String getProdId() {
return prodId;
}
public void setProdId(String prodId) {
this.prodId = prodId;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.hibernate.pojo;
public class Result {
private String employeeName;
private String departmentName;
public Result(String employeeName, String departmentName) {
this.employeeName = employeeName;
this.departmentName = departmentName;
}
public Result() {
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long studentId;
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@@ -0,0 +1,195 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.*;
import java.util.Calendar;
@Entity
public class TemporalValues implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Basic
private java.sql.Date sqlDate;
@Basic
private java.sql.Time sqlTime;
@Basic
private java.sql.Timestamp sqlTimestamp;
@Basic
@Temporal(TemporalType.DATE)
private java.util.Date utilDate;
@Basic
@Temporal(TemporalType.TIME)
private java.util.Date utilTime;
@Basic
@Temporal(TemporalType.TIMESTAMP)
private java.util.Date utilTimestamp;
@Basic
@Temporal(TemporalType.DATE)
private java.util.Calendar calendarDate;
@Basic
@Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar calendarTimestamp;
@Basic
private java.time.LocalDate localDate;
@Basic
private java.time.LocalTime localTime;
@Basic
private java.time.OffsetTime offsetTime;
@Basic
private java.time.Instant instant;
@Basic
private java.time.LocalDateTime localDateTime;
@Basic
private java.time.OffsetDateTime offsetDateTime;
@Basic
private java.time.ZonedDateTime zonedDateTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getSqlDate() {
return sqlDate;
}
public void setSqlDate(Date sqlDate) {
this.sqlDate = sqlDate;
}
public Time getSqlTime() {
return sqlTime;
}
public void setSqlTime(Time sqlTime) {
this.sqlTime = sqlTime;
}
public Timestamp getSqlTimestamp() {
return sqlTimestamp;
}
public void setSqlTimestamp(Timestamp sqlTimestamp) {
this.sqlTimestamp = sqlTimestamp;
}
public java.util.Date getUtilDate() {
return utilDate;
}
public void setUtilDate(java.util.Date utilDate) {
this.utilDate = utilDate;
}
public java.util.Date getUtilTime() {
return utilTime;
}
public void setUtilTime(java.util.Date utilTime) {
this.utilTime = utilTime;
}
public java.util.Date getUtilTimestamp() {
return utilTimestamp;
}
public void setUtilTimestamp(java.util.Date utilTimestamp) {
this.utilTimestamp = utilTimestamp;
}
public Calendar getCalendarDate() {
return calendarDate;
}
public void setCalendarDate(Calendar calendarDate) {
this.calendarDate = calendarDate;
}
public Calendar getCalendarTimestamp() {
return calendarTimestamp;
}
public void setCalendarTimestamp(Calendar calendarTimestamp) {
this.calendarTimestamp = calendarTimestamp;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
public class User {
@Id
@GeneratedValue(generator = "sequence-generator")
@GenericGenerator(
name = "sequence-generator",
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
parameters = {
@Parameter(name = "sequence_name", value = "user_sequence"),
@Parameter(name = "initial_value", value = "4"),
@Parameter(name = "increment_size", value = "1")
}
)
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
@Entity
public class UserProfile {
@Id
private long profileId;
@OneToOne
@MapsId
private User user;
public long getProfileId() {
return profileId;
}
public void setProfileId(long profileId) {
this.profileId = profileId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.hibernate.pojo.generator;
import java.io.Serializable;
import java.util.Properties;
import java.util.stream.Stream;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
public class MyGenerator implements IdentifierGenerator, Configurable {
private String prefix;
@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
String query = String.format("select %s from %s",
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(),
obj.getClass().getSimpleName());
Stream<String> ids = session.createQuery(query).stream();
Long max = ids.map(o -> o.replace(prefix + "-", ""))
.mapToLong(Long::parseLong)
.max()
.orElse(0L);
return prefix + "-" + (max + 1);
}
@Override
public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
prefix = properties.getProperty("prefix");
}
}
@@ -0,0 +1,40 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Animal {
@Id
private long animalId;
private String species;
public Animal() {}
public Animal(long animalId, String species) {
this.animalId = animalId;
this.species = species;
}
public long getAnimalId() {
return animalId;
}
public void setAnimalId(long animalId) {
this.animalId = animalId;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Polymorphism;
import org.hibernate.annotations.PolymorphismType;
@Entity
@Polymorphism(type = PolymorphismType.EXPLICIT)
public class Bag implements Item {
@Id
private long bagId;
private String type;
public Bag(long bagId, String type) {
this.bagId = bagId;
this.type = type;
}
public long getBagId() {
return bagId;
}
public void setBagId(long bagId) {
this.bagId = bagId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("1")
public class Book extends MyProduct {
private String author;
public Book() {
}
public Book(long productId, String name, String author) {
super(productId, name);
this.author = author;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
@Entity
public class Car extends Vehicle {
private String engine;
public Car() {
}
public Car(long vehicleId, String manufacturer, String engine) {
super(vehicleId, manufacturer);
this.engine = engine;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
}
@@ -0,0 +1,5 @@
package com.baeldung.hibernate.pojo.inheritance;
public interface Item {
}
@@ -0,0 +1,22 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
@Entity
public class MyEmployee extends Person {
private String company;
public MyEmployee(long personId, String name, String company) {
super(personId, name);
this.company = company;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
@@ -0,0 +1,47 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import org.hibernate.annotations.DiscriminatorFormula;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER)
// @DiscriminatorFormula("case when author is not null then 1 else 2 end")
public class MyProduct {
@Id
private long productId;
private String name;
public MyProduct() {
}
public MyProduct(long productId, String name) {
super();
this.productId = productId;
this.name = name;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("2")
public class Pen extends MyProduct {
private String color;
public Pen() {
}
public Pen(long productId, String name, String color) {
super(productId, name);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class Person {
@Id
private long personId;
private String name;
public Person() {
}
public Person(long personId, String name) {
this.personId = personId;
this.name = name;
}
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
@PrimaryKeyJoinColumn(name = "petId")
public class Pet extends Animal {
private String name;
public Pet() {
}
public Pet(long animalId, String species, String name) {
super(animalId, species);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
@Id
private long vehicleId;
private String manufacturer;
public Vehicle() {
}
public Vehicle(long vehicleId, String manufacturer) {
this.vehicleId = vehicleId;
this.manufacturer = manufacturer;
}
public long getVehicleId() {
return vehicleId;
}
public void setVehicleId(long vehicleId) {
this.vehicleId = vehicleId;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}
@@ -0,0 +1,9 @@
@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int",
metaValues = {
@MetaValue(value = "Employee", targetEntity = Employee.class),
@MetaValue(value = "Phone", targetEntity = Phone.class)
})
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.MetaValue;
@@ -0,0 +1,62 @@
package com.baeldung.hibernate.proxy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
public class Company implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(name = "name")
private String name;
@OneToMany
@JoinColumn(name = "workplace_id")
private Set<Employee> employees = new HashSet<>();
public Company() { }
public Company(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Employee> getEmployees() {
return this.employees;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Company company = (Company) o;
return Objects.equals(id, company.id) &&
Objects.equals(name, company.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
@@ -0,0 +1,69 @@
package com.baeldung.hibernate.proxy;
import org.hibernate.annotations.BatchSize;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@Entity
@BatchSize(size = 5)
public class Employee implements Serializable {
@Id
@GeneratedValue (strategy = GenerationType.SEQUENCE)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "workplace_id")
private Company workplace;
@Column(name = "first_name")
private String firstName;
public Employee() { }
public Employee(Company workplace, String firstName) {
this.workplace = workplace;
this.firstName = firstName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getWorkplace() {
return workplace;
}
public void setWorkplace(Company workplace) {
this.workplace = workplace;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id) &&
Objects.equals(workplace, employee.workplace) &&
Objects.equals(firstName, employee.firstName);
}
@Override
public int hashCode() {
return Objects.hash(id, workplace, firstName);
}
}
@@ -0,0 +1,57 @@
package com.baeldung.hibernate.proxy;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder;
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 static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
}
return sessionFactory;
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.proxy");
metadataSources.addAnnotatedClass(Company.class);
metadataSources.addAnnotatedClass(Employee.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
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;
}
}
@@ -0,0 +1,29 @@
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();
}
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="com.baeldung.movie_catalog">
<description>Hibernate EntityManager Demo</description>
<class>com.baeldung.hibernate.pojo.Movie</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>
@@ -0,0 +1,10 @@
CREATE ALIAS UPDATE_EMPLOYEE_DESIGNATION AS $$
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
@CODE
void updateEmployeeDesignation(final Connection conn, final String employeeNumber, final String title) throws SQLException {
CallableStatement updateStatement = conn.prepareCall("update deptemployee set title = '" + title + "' where employeeNumber = '" + employeeNumber + "'");
updateStatement.execute();
}
$$;

Some files were not shown because too many files have changed in this diff Show More