JAVA-4 : Split hibernate5 module to smaller parts
This commit is contained in:
@@ -4,38 +4,13 @@ This module contains articles about Hibernate 5.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Dynamic Mapping with Hibernate](http://www.baeldung.com/hibernate-dynamic-mapping)
|
||||
- [An Overview of Identifiers in Hibernate](http://www.baeldung.com/hibernate-identifiers)
|
||||
- [Hibernate – Mapping Date and Time](http://www.baeldung.com/hibernate-date-time)
|
||||
- [Hibernate Inheritance Mapping](http://www.baeldung.com/hibernate-inheritance)
|
||||
- [A Guide to Multitenancy in Hibernate 5](http://www.baeldung.com/hibernate-5-multitenancy)
|
||||
- [Introduction to Hibernate Spatial](http://www.baeldung.com/hibernate-spatial)
|
||||
- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor)
|
||||
- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters)
|
||||
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
|
||||
- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)
|
||||
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
|
||||
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)
|
||||
- [Optimistic Locking in JPA](http://www.baeldung.com/jpa-optimistic-locking)
|
||||
- [Hibernate Entity Lifecycle](https://www.baeldung.com/hibernate-entity-lifecycle)
|
||||
- [Mapping A Hibernate Query to a Custom Class](https://www.baeldung.com/hibernate-query-to-custom-class)
|
||||
- [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column)
|
||||
- [Hibernate 5 Naming Strategy Configuration](https://www.baeldung.com/hibernate-naming-strategy)
|
||||
- [Proxy in Hibernate load() Method](https://www.baeldung.com/hibernate-proxy-load-method)
|
||||
- [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types)
|
||||
- [Criteria API – An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions)
|
||||
- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby)
|
||||
- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api)
|
||||
- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)
|
||||
- [Guide to the Hibernate EntityManager](https://www.baeldung.com/hibernate-entitymanager)
|
||||
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
|
||||
- [One-to-One Relationship in JPA](https://www.baeldung.com/jpa-one-to-one)
|
||||
- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
|
||||
- [Using c3p0 with Hibernate](https://www.baeldung.com/hibernate-c3p0)
|
||||
- [Persist a JSON Object Using Hibernate](https://www.baeldung.com/hibernate-persist-json-object)
|
||||
- [Common Hibernate Exceptions](https://www.baeldung.com/hibernate-exceptions)
|
||||
- [Hibernate Aggregate Functions](https://www.baeldung.com/hibernate-aggregate-functions)
|
||||
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
|
||||
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
|
||||
- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks)
|
||||
- [[Next -->]](/hibernate5-2)
|
||||
-28
@@ -12,25 +12,13 @@ import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.customtypes.LocalDateStringType;
|
||||
import com.baeldung.hibernate.customtypes.OfficeEmployee;
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
import com.baeldung.hibernate.joincolumn.Email;
|
||||
import com.baeldung.hibernate.joincolumn.Office;
|
||||
import com.baeldung.hibernate.joincolumn.OfficeAddress;
|
||||
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
|
||||
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pessimisticlocking.Individual;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pojo.Course;
|
||||
import com.baeldung.hibernate.pojo.Employee;
|
||||
import com.baeldung.hibernate.pojo.EntityDescription;
|
||||
import com.baeldung.hibernate.pojo.OrderEntry;
|
||||
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
|
||||
import com.baeldung.hibernate.pojo.OrderEntryPK;
|
||||
import com.baeldung.hibernate.pojo.Person;
|
||||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import com.baeldung.hibernate.pojo.PointEntity;
|
||||
import com.baeldung.hibernate.pojo.PolygonEntity;
|
||||
@@ -88,7 +76,6 @@ public class HibernateUtil {
|
||||
metadataSources.addAnnotatedClass(MyEmployee.class);
|
||||
metadataSources.addAnnotatedClass(MyProduct.class);
|
||||
metadataSources.addAnnotatedClass(Pen.class);
|
||||
metadataSources.addAnnotatedClass(Person.class);
|
||||
metadataSources.addAnnotatedClass(Animal.class);
|
||||
metadataSources.addAnnotatedClass(Pet.class);
|
||||
metadataSources.addAnnotatedClass(Vehicle.class);
|
||||
@@ -96,26 +83,11 @@ public class HibernateUtil {
|
||||
metadataSources.addAnnotatedClass(Bag.class);
|
||||
metadataSources.addAnnotatedClass(PointEntity.class);
|
||||
metadataSources.addAnnotatedClass(PolygonEntity.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
|
||||
metadataSources.addAnnotatedClass(Individual.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
|
||||
metadataSources.addAnnotatedClass(DeptEmployee.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
|
||||
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
|
||||
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
|
||||
metadataSources.addAnnotatedClass(OfficeEmployee.class);
|
||||
metadataSources.addAnnotatedClass(Post.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class);
|
||||
metadataSources.addAnnotatedClass(Email.class);
|
||||
metadataSources.addAnnotatedClass(Office.class);
|
||||
metadataSources.addAnnotatedClass(OfficeAddress.class);
|
||||
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.applyBasicType(LocalDateStringType.INSTANCE)
|
||||
.build();
|
||||
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.hibernate.converters;
|
||||
|
||||
import javax.persistence.AttributeConverter;
|
||||
import javax.persistence.Converter;
|
||||
|
||||
import com.baeldung.hibernate.pojo.PersonName;
|
||||
|
||||
@Converter
|
||||
public class PersonNameConverter implements AttributeConverter<PersonName, String> {
|
||||
|
||||
private static final String SEPARATOR = ", ";
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(PersonName personName) {
|
||||
if (personName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (personName.getSurname() != null && !personName.getSurname()
|
||||
.isEmpty()) {
|
||||
sb.append(personName.getSurname());
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
|
||||
if (personName.getName() != null && !personName.getName()
|
||||
.isEmpty()) {
|
||||
sb.append(personName.getName());
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersonName convertToEntityAttribute(String dbPersonName) {
|
||||
if (dbPersonName == null || dbPersonName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] pieces = dbPersonName.split(SEPARATOR);
|
||||
|
||||
if (pieces == null || pieces.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PersonName personName = new PersonName();
|
||||
String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null;
|
||||
if (dbPersonName.contains(SEPARATOR)) {
|
||||
personName.setSurname(firstPiece);
|
||||
|
||||
if (pieces.length >= 2 && pieces[1] != null && !pieces[1].isEmpty()) {
|
||||
personName.setName(pieces[1]);
|
||||
}
|
||||
} else {
|
||||
personName.setName(firstPiece);
|
||||
}
|
||||
|
||||
return personName;
|
||||
}
|
||||
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package com.baeldung.hibernate.criteriaquery;
|
||||
|
||||
import com.baeldung.hibernate.customtypes.LocalDateStringType;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private HibernateUtil() {
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = buildSessionFactory();
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
try {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
|
||||
metadataSources.addAnnotatedClass(Student.class);
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.applyBasicType(LocalDateStringType.INSTANCE)
|
||||
.build();
|
||||
return metadata.getSessionFactoryBuilder().build();
|
||||
} catch (IOException ex) {
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties).build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource("hibernate.properties");
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
package com.baeldung.hibernate.criteriaquery;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "students")
|
||||
public class Student {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private int id;
|
||||
|
||||
@Column(name = "first_name")
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "last_name")
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "grad_year")
|
||||
private int gradYear;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public int getGradYear() {
|
||||
return gradYear;
|
||||
}
|
||||
|
||||
public void setGradYear(int gradYear) {
|
||||
this.gradYear = gradYear;
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String addressLine1;
|
||||
private String addressLine2;
|
||||
private String city;
|
||||
private String country;
|
||||
private int zipCode;
|
||||
|
||||
public String getAddressLine1() {
|
||||
return addressLine1;
|
||||
}
|
||||
|
||||
public String getAddressLine2() {
|
||||
return addressLine2;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public int getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setAddressLine1(String addressLine1) {
|
||||
this.addressLine1 = addressLine1;
|
||||
}
|
||||
|
||||
public void setAddressLine2(String addressLine2) {
|
||||
this.addressLine2 = addressLine2;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public void setZipCode(int zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Address address = (Address) o;
|
||||
return zipCode == address.zipCode &&
|
||||
Objects.equals(addressLine1, address.addressLine1) &&
|
||||
Objects.equals(addressLine2, address.addressLine2) &&
|
||||
Objects.equals(city, address.city) &&
|
||||
Objects.equals(country, address.country);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(addressLine1, addressLine2, city, country, zipCode);
|
||||
}
|
||||
}
|
||||
-169
@@ -1,169 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.engine.spi.SharedSessionContractImplementor;
|
||||
import org.hibernate.type.IntegerType;
|
||||
import org.hibernate.type.StringType;
|
||||
import org.hibernate.type.Type;
|
||||
import org.hibernate.usertype.CompositeUserType;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.Objects;
|
||||
|
||||
public class AddressType implements CompositeUserType {
|
||||
|
||||
@Override
|
||||
public String[] getPropertyNames() {
|
||||
return new String[]{"addressLine1", "addressLine2",
|
||||
"city", "country", "zipcode"};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type[] getPropertyTypes() {
|
||||
return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
|
||||
StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPropertyValue(Object component, int property) throws HibernateException {
|
||||
|
||||
Address empAdd = (Address) component;
|
||||
|
||||
switch (property) {
|
||||
case 0:
|
||||
return empAdd.getAddressLine1();
|
||||
case 1:
|
||||
return empAdd.getAddressLine2();
|
||||
case 2:
|
||||
return empAdd.getCity();
|
||||
case 3:
|
||||
return empAdd.getCountry();
|
||||
case 4:
|
||||
return Integer.valueOf(empAdd.getZipCode());
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(property +
|
||||
" is an invalid property index for class type " +
|
||||
component.getClass().getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
|
||||
|
||||
Address empAdd = (Address) component;
|
||||
|
||||
switch (property) {
|
||||
case 0:
|
||||
empAdd.setAddressLine1((String) value);
|
||||
case 1:
|
||||
empAdd.setAddressLine2((String) value);
|
||||
case 2:
|
||||
empAdd.setCity((String) value);
|
||||
case 3:
|
||||
empAdd.setCountry((String) value);
|
||||
case 4:
|
||||
empAdd.setZipCode((Integer) value);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(property +
|
||||
" is an invalid property index for class type " +
|
||||
component.getClass().getName());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class returnedClass() {
|
||||
return Address.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object x, Object y) throws HibernateException {
|
||||
if (x == y)
|
||||
return true;
|
||||
|
||||
if (Objects.isNull(x) || Objects.isNull(y))
|
||||
return false;
|
||||
|
||||
return x.equals(y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode(Object x) throws HibernateException {
|
||||
return x.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
|
||||
|
||||
Address empAdd = new Address();
|
||||
empAdd.setAddressLine1(rs.getString(names[0]));
|
||||
|
||||
if (rs.wasNull())
|
||||
return null;
|
||||
|
||||
empAdd.setAddressLine2(rs.getString(names[1]));
|
||||
empAdd.setCity(rs.getString(names[2]));
|
||||
empAdd.setCountry(rs.getString(names[3]));
|
||||
empAdd.setZipCode(rs.getInt(names[4]));
|
||||
|
||||
return empAdd;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
|
||||
|
||||
if (Objects.isNull(value))
|
||||
st.setNull(index, Types.VARCHAR);
|
||||
else {
|
||||
|
||||
Address empAdd = (Address) value;
|
||||
st.setString(index, empAdd.getAddressLine1());
|
||||
st.setString(index + 1, empAdd.getAddressLine2());
|
||||
st.setString(index + 2, empAdd.getCity());
|
||||
st.setString(index + 3, empAdd.getCountry());
|
||||
st.setInt(index + 4, empAdd.getZipCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object deepCopy(Object value) throws HibernateException {
|
||||
|
||||
if (Objects.isNull(value))
|
||||
return null;
|
||||
|
||||
Address oldEmpAdd = (Address) value;
|
||||
Address newEmpAdd = new Address();
|
||||
|
||||
newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
|
||||
newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
|
||||
newEmpAdd.setCity(oldEmpAdd.getCity());
|
||||
newEmpAdd.setCountry(oldEmpAdd.getCountry());
|
||||
newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
|
||||
|
||||
return newEmpAdd;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMutable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
|
||||
return (Serializable) deepCopy(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
|
||||
return deepCopy(cached);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
|
||||
return original;
|
||||
}
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.type.LocalDateType;
|
||||
import org.hibernate.type.descriptor.WrapperOptions;
|
||||
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
|
||||
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
|
||||
import org.hibernate.type.descriptor.java.MutabilityPlan;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
|
||||
|
||||
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
|
||||
|
||||
public LocalDateStringJavaDescriptor() {
|
||||
super(LocalDate.class, ImmutableMutabilityPlan.INSTANCE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(LocalDate value) {
|
||||
return LocalDateType.FORMATTER.format(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate fromString(String string) {
|
||||
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
|
||||
|
||||
if (value == null)
|
||||
return null;
|
||||
|
||||
if (String.class.isAssignableFrom(type))
|
||||
return (X) LocalDateType.FORMATTER.format(value);
|
||||
|
||||
throw unknownUnwrap(type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <X> LocalDate wrap(X value, WrapperOptions options) {
|
||||
if (value == null)
|
||||
return null;
|
||||
|
||||
if(String.class.isInstance(value))
|
||||
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
|
||||
|
||||
throw unknownWrap(value.getClass());
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.dialect.Dialect;
|
||||
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
|
||||
import org.hibernate.type.DiscriminatorType;
|
||||
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
|
||||
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
|
||||
|
||||
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
|
||||
|
||||
public LocalDateStringType() {
|
||||
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "LocalDateString";
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDate stringToObject(String xml) throws Exception {
|
||||
return fromString(xml);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
|
||||
return '\'' + toString(value) + '\'';
|
||||
}
|
||||
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import org.hibernate.annotations.Columns;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
import org.hibernate.annotations.Type;
|
||||
import org.hibernate.annotations.TypeDef;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
import java.time.LocalDate;
|
||||
|
||||
@TypeDef(name = "PhoneNumber",
|
||||
typeClass = PhoneNumberType.class,
|
||||
defaultForType = PhoneNumber.class)
|
||||
@Entity
|
||||
@Table(name = "OfficeEmployee")
|
||||
public class OfficeEmployee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private long id;
|
||||
|
||||
@Column
|
||||
@Type(type = "LocalDateString")
|
||||
private LocalDate dateOfJoining;
|
||||
|
||||
@Columns(columns = {@Column(name = "country_code"),
|
||||
@Column(name = "city_code"),
|
||||
@Column(name = "number")})
|
||||
private PhoneNumber employeeNumber;
|
||||
|
||||
@Columns(columns = {@Column(name = "address_line_1"),
|
||||
@Column(name = "address_line_2"),
|
||||
@Column(name = "city"), @Column(name = "country"),
|
||||
@Column(name = "zip_code")})
|
||||
@Type(type = "com.baeldung.hibernate.customtypes.AddressType")
|
||||
private Address empAddress;
|
||||
|
||||
@Type(type = "com.baeldung.hibernate.customtypes.SalaryType",
|
||||
parameters = {@Parameter(name = "currency", value = "USD")})
|
||||
@Columns(columns = {@Column(name = "amount"),
|
||||
@Column(name = "currency")})
|
||||
private Salary salary;
|
||||
|
||||
public Salary getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(Salary salary) {
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public LocalDate getDateOfJoining() {
|
||||
return dateOfJoining;
|
||||
}
|
||||
|
||||
public void setDateOfJoining(LocalDate dateOfJoining) {
|
||||
this.dateOfJoining = dateOfJoining;
|
||||
}
|
||||
|
||||
public PhoneNumber getEmployeeNumber() {
|
||||
return employeeNumber;
|
||||
}
|
||||
|
||||
public void setEmployeeNumber(PhoneNumber employeeNumber) {
|
||||
this.employeeNumber = employeeNumber;
|
||||
}
|
||||
|
||||
public Address getEmpAddress() {
|
||||
return empAddress;
|
||||
}
|
||||
|
||||
public void setEmpAddress(Address empAddress) {
|
||||
this.empAddress = empAddress;
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PhoneNumber {
|
||||
|
||||
private final int countryCode;
|
||||
private final int cityCode;
|
||||
private final int number;
|
||||
|
||||
public PhoneNumber(int countryCode, int cityCode, int number) {
|
||||
this.countryCode = countryCode;
|
||||
this.cityCode = cityCode;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public int getCountryCode() {
|
||||
return countryCode;
|
||||
}
|
||||
|
||||
public int getCityCode() {
|
||||
return cityCode;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
PhoneNumber that = (PhoneNumber) o;
|
||||
return countryCode == that.countryCode &&
|
||||
cityCode == that.cityCode &&
|
||||
number == that.number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(countryCode, cityCode, number);
|
||||
}
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.engine.spi.SharedSessionContractImplementor;
|
||||
import org.hibernate.usertype.UserType;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.Objects;
|
||||
|
||||
|
||||
public class PhoneNumberType implements UserType {
|
||||
@Override
|
||||
public int[] sqlTypes() {
|
||||
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class returnedClass() {
|
||||
return PhoneNumber.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object x, Object y) throws HibernateException {
|
||||
if (x == y)
|
||||
return true;
|
||||
if (Objects.isNull(x) || Objects.isNull(y))
|
||||
return false;
|
||||
|
||||
return x.equals(y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode(Object x) throws HibernateException {
|
||||
return x.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
|
||||
int countryCode = rs.getInt(names[0]);
|
||||
|
||||
if (rs.wasNull())
|
||||
return null;
|
||||
|
||||
int cityCode = rs.getInt(names[1]);
|
||||
int number = rs.getInt(names[2]);
|
||||
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
|
||||
|
||||
return employeeNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
|
||||
|
||||
if (Objects.isNull(value)) {
|
||||
st.setNull(index, Types.INTEGER);
|
||||
} else {
|
||||
PhoneNumber employeeNumber = (PhoneNumber) value;
|
||||
st.setInt(index,employeeNumber.getCountryCode());
|
||||
st.setInt(index+1,employeeNumber.getCityCode());
|
||||
st.setInt(index+2,employeeNumber.getNumber());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object deepCopy(Object value) throws HibernateException {
|
||||
if (Objects.isNull(value))
|
||||
return null;
|
||||
|
||||
PhoneNumber empNumber = (PhoneNumber) value;
|
||||
PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
|
||||
|
||||
return newEmpNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMutable() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Serializable disassemble(Object value) throws HibernateException {
|
||||
return (Serializable) value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object assemble(Serializable cached, Object owner) throws HibernateException {
|
||||
return cached;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object replace(Object original, Object target, Object owner) throws HibernateException {
|
||||
return original;
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Salary {
|
||||
|
||||
private Long amount;
|
||||
private String currency;
|
||||
|
||||
public Long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(Long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Salary salary = (Salary) o;
|
||||
return Objects.equals(amount, salary.amount) &&
|
||||
Objects.equals(currency, salary.currency);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(amount, currency);
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
public class SalaryCurrencyConvertor {
|
||||
|
||||
public static Long convert(Long amount, String oldCurr, String newCurr){
|
||||
if (newCurr.equalsIgnoreCase(oldCurr))
|
||||
return amount;
|
||||
|
||||
return convertTo();
|
||||
}
|
||||
|
||||
private static Long convertTo() {
|
||||
return 10L;
|
||||
}
|
||||
}
|
||||
-161
@@ -1,161 +0,0 @@
|
||||
package com.baeldung.hibernate.customtypes;
|
||||
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.engine.spi.SharedSessionContractImplementor;
|
||||
import org.hibernate.type.LongType;
|
||||
import org.hibernate.type.StringType;
|
||||
import org.hibernate.type.Type;
|
||||
import org.hibernate.usertype.CompositeUserType;
|
||||
import org.hibernate.usertype.DynamicParameterizedType;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.Objects;
|
||||
import java.util.Properties;
|
||||
|
||||
public class SalaryType implements CompositeUserType, DynamicParameterizedType {
|
||||
|
||||
private String localCurrency;
|
||||
|
||||
@Override
|
||||
public String[] getPropertyNames() {
|
||||
return new String[]{"amount", "currency"};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type[] getPropertyTypes() {
|
||||
return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPropertyValue(Object component, int property) throws HibernateException {
|
||||
|
||||
Salary salary = (Salary) component;
|
||||
|
||||
switch (property) {
|
||||
case 0:
|
||||
return salary.getAmount();
|
||||
case 1:
|
||||
return salary.getCurrency();
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(property +
|
||||
" is an invalid property index for class type " +
|
||||
component.getClass().getName());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
|
||||
|
||||
Salary salary = (Salary) component;
|
||||
|
||||
switch (property) {
|
||||
case 0:
|
||||
salary.setAmount((Long) value);
|
||||
case 1:
|
||||
salary.setCurrency((String) value);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException(property +
|
||||
" is an invalid property index for class type " +
|
||||
component.getClass().getName());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class returnedClass() {
|
||||
return Salary.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object x, Object y) throws HibernateException {
|
||||
|
||||
if (x == y)
|
||||
return true;
|
||||
|
||||
if (Objects.isNull(x) || Objects.isNull(y))
|
||||
return false;
|
||||
|
||||
return x.equals(y);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode(Object x) throws HibernateException {
|
||||
return x.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
|
||||
|
||||
Salary salary = new Salary();
|
||||
salary.setAmount(rs.getLong(names[0]));
|
||||
|
||||
if (rs.wasNull())
|
||||
return null;
|
||||
|
||||
salary.setCurrency(rs.getString(names[1]));
|
||||
|
||||
return salary;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
|
||||
|
||||
|
||||
if (Objects.isNull(value))
|
||||
st.setNull(index, Types.BIGINT);
|
||||
else {
|
||||
|
||||
Salary salary = (Salary) value;
|
||||
st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
|
||||
salary.getCurrency(), localCurrency));
|
||||
st.setString(index + 1, salary.getCurrency());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object deepCopy(Object value) throws HibernateException {
|
||||
|
||||
if (Objects.isNull(value))
|
||||
return null;
|
||||
|
||||
Salary oldSal = (Salary) value;
|
||||
Salary newSal = new Salary();
|
||||
|
||||
newSal.setAmount(oldSal.getAmount());
|
||||
newSal.setCurrency(oldSal.getCurrency());
|
||||
|
||||
return newSal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMutable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
|
||||
return (Serializable) deepCopy(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
|
||||
return deepCopy(cached);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
|
||||
return original;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setParameterValues(Properties parameters) {
|
||||
this.localCurrency = parameters.getProperty("currency");
|
||||
}
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.baeldung.hibernate.exception;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
|
||||
@Entity
|
||||
public class EntityWithNoId {
|
||||
private int id;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package com.baeldung.hibernate.exception;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName)
|
||||
throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(
|
||||
ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addAnnotatedClass(Product.class);
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.build();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry()
|
||||
throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME,
|
||||
"hibernate-exception.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(
|
||||
propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.hibernate.exception;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Product {
|
||||
|
||||
private int id;
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
@Id
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(nullable=false)
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.hibernate.findall;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
|
||||
import org.hibernate.Session;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
|
||||
public class FindAll {
|
||||
|
||||
private Session session;
|
||||
|
||||
public FindAll(Session session) {
|
||||
super();
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
public List<Student> findAllWithJpql() {
|
||||
return session.createQuery("SELECT a FROM Student a", Student.class).getResultList();
|
||||
}
|
||||
|
||||
public List<Student> findAllWithCriteriaQuery() {
|
||||
CriteriaBuilder cb = session.getCriteriaBuilder();
|
||||
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
|
||||
Root<Student> rootEntry = cq.from(Student.class);
|
||||
CriteriaQuery<Student> all = cq.select(rootEntry);
|
||||
TypedQuery<Student> allQuery = session.createQuery(all);
|
||||
return allQuery.getResultList();
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Email {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
private String address;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "employee_id")
|
||||
private OfficialEmployee employee;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public OfficialEmployee getEmployee() {
|
||||
return employee;
|
||||
}
|
||||
|
||||
public void setEmployee(OfficialEmployee employee) {
|
||||
this.employee = employee;
|
||||
}
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinColumns;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
@Entity
|
||||
public class Office {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumns({
|
||||
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
|
||||
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
|
||||
})
|
||||
private OfficeAddress address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public OfficeAddress getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(OfficeAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class OfficeAddress {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "ZIP")
|
||||
private String zipCode;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getZipCode() {
|
||||
return zipCode;
|
||||
}
|
||||
|
||||
public void setZipCode(String zipCode) {
|
||||
this.zipCode = zipCode;
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.hibernate.joincolumn;
|
||||
|
||||
import java.util.List;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.FetchType;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class OfficialEmployee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
|
||||
private List<Email> emails;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Email> getEmails() {
|
||||
return emails;
|
||||
}
|
||||
|
||||
public void setEmails(List<Email> emails) {
|
||||
this.emails = emails;
|
||||
}
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.application;
|
||||
|
||||
import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
|
||||
import com.baeldung.hibernate.jpabootstrap.entities.User;
|
||||
import javax.persistence.EntityManager;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
EntityManager entityManager = getJpaEntityManager();
|
||||
User user = entityManager.find(User.class, 1);
|
||||
System.out.println(user);
|
||||
entityManager.getTransaction().begin();
|
||||
user.setName("John");
|
||||
user.setEmail("[email protected]");
|
||||
entityManager.merge(user);
|
||||
entityManager.getTransaction().commit();
|
||||
entityManager.getTransaction().begin();
|
||||
entityManager.persist(new User("Monica", "[email protected]"));
|
||||
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;
|
||||
}
|
||||
}
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.config;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import javax.sql.DataSource;
|
||||
import javax.persistence.SharedCacheMode;
|
||||
import javax.persistence.ValidationMode;
|
||||
import javax.persistence.spi.ClassTransformer;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
import javax.persistence.spi.PersistenceUnitTransactionType;
|
||||
import org.hibernate.jpa.HibernatePersistenceProvider;
|
||||
|
||||
public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
|
||||
|
||||
public static final String JPA_VERSION = "2.1";
|
||||
private final String persistenceUnitName;
|
||||
private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
|
||||
private final List<String> managedClassNames;
|
||||
private final List<String> mappingFileNames = new ArrayList<>();
|
||||
private final Properties properties;
|
||||
private DataSource jtaDataSource;
|
||||
private DataSource nonjtaDataSource;
|
||||
private final List<ClassTransformer> transformers = new ArrayList<>();
|
||||
|
||||
public HibernatePersistenceUnitInfo(String persistenceUnitName, List<String> managedClassNames, Properties properties) {
|
||||
this.persistenceUnitName = persistenceUnitName;
|
||||
this.managedClassNames = managedClassNames;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPersistenceUnitName() {
|
||||
return persistenceUnitName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPersistenceProviderClassName() {
|
||||
return HibernatePersistenceProvider.class.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PersistenceUnitTransactionType getTransactionType() {
|
||||
return transactionType;
|
||||
}
|
||||
|
||||
public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) {
|
||||
this.jtaDataSource = jtaDataSource;
|
||||
this.nonjtaDataSource = null;
|
||||
transactionType = PersistenceUnitTransactionType.JTA;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataSource getJtaDataSource() {
|
||||
return jtaDataSource;
|
||||
}
|
||||
|
||||
public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) {
|
||||
this.nonjtaDataSource = nonJtaDataSource;
|
||||
this.jtaDataSource = null;
|
||||
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataSource getNonJtaDataSource() {
|
||||
return nonjtaDataSource;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getMappingFileNames() {
|
||||
return mappingFileNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<URL> getJarFileUrls() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public URL getPersistenceUnitRootUrl() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getManagedClassNames() {
|
||||
return managedClassNames;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean excludeUnlistedClasses() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SharedCacheMode getSharedCacheMode() {
|
||||
return SharedCacheMode.UNSPECIFIED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ValidationMode getValidationMode() {
|
||||
return ValidationMode.AUTO;
|
||||
}
|
||||
|
||||
public Properties getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPersistenceXMLSchemaVersion() {
|
||||
return JPA_VERSION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassLoader getClassLoader() {
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addTransformer(ClassTransformer transformer) {
|
||||
transformers.add(transformer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassLoader getNewTempClassLoader() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.config;
|
||||
|
||||
import com.mysql.cj.jdbc.MysqlDataSource;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.sql.DataSource;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.spi.PersistenceUnitInfo;
|
||||
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
|
||||
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
|
||||
|
||||
public class JpaEntityManagerFactory {
|
||||
|
||||
private final String DB_URL = "jdbc:mysql://databaseurl";
|
||||
private final String DB_USER_NAME = "username";
|
||||
private final String DB_PASSWORD = "password";
|
||||
private final Class[] entityClasses;
|
||||
|
||||
public JpaEntityManagerFactory(Class[] entityClasses) {
|
||||
this.entityClasses = entityClasses;
|
||||
}
|
||||
|
||||
public EntityManager getEntityManager() {
|
||||
return getEntityManagerFactory().createEntityManager();
|
||||
}
|
||||
|
||||
protected EntityManagerFactory getEntityManagerFactory() {
|
||||
PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
|
||||
Map<String, Object> configuration = new HashMap<>();
|
||||
return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
|
||||
.build();
|
||||
}
|
||||
|
||||
protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) {
|
||||
return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties());
|
||||
}
|
||||
|
||||
protected List<String> getEntityClassNames() {
|
||||
return Arrays.asList(getEntities())
|
||||
.stream()
|
||||
.map(Class::getName)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected Properties getProperties() {
|
||||
Properties properties = new Properties();
|
||||
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
|
||||
properties.put("hibernate.id.new_generator_mappings", false);
|
||||
properties.put("hibernate.connection.datasource", getMysqlDataSource());
|
||||
return properties;
|
||||
}
|
||||
|
||||
protected Class[] getEntities() {
|
||||
return entityClasses;
|
||||
}
|
||||
|
||||
protected DataSource getMysqlDataSource() {
|
||||
MysqlDataSource mysqlDataSource = new MysqlDataSource();
|
||||
mysqlDataSource.setURL(DB_URL);
|
||||
mysqlDataSource.setUser(DB_USER_NAME);
|
||||
mysqlDataSource.setPassword(DB_PASSWORD);
|
||||
return mysqlDataSource;
|
||||
}
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package com.baeldung.hibernate.jpabootstrap.entities;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private long id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(){}
|
||||
|
||||
public User(String name, String email) {
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.hibernate.jpacriteriabuilder.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
|
||||
public interface EmployeeSearchService {
|
||||
|
||||
List<DeptEmployee> filterbyTitleUsingCriteriaBuilder(List<String> titles);
|
||||
|
||||
List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles);
|
||||
|
||||
List<DeptEmployee> searchByDepartmentQuery(String query);
|
||||
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
package com.baeldung.hibernate.jpacriteriabuilder.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaBuilder.In;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.persistence.criteria.Subquery;
|
||||
|
||||
import com.baeldung.hibernate.entities.Department;
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
|
||||
public class EmployeeSearchServiceImpl implements EmployeeSearchService {
|
||||
|
||||
private EntityManager entityManager;
|
||||
private CriteriaBuilder criteriaBuilder;
|
||||
|
||||
public EmployeeSearchServiceImpl(EntityManager entityManager) {
|
||||
this.entityManager = entityManager;
|
||||
this.criteriaBuilder = entityManager.getCriteriaBuilder();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeptEmployee> filterbyTitleUsingCriteriaBuilder(List<String> titles) {
|
||||
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
|
||||
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
|
||||
In<String> inClause = criteriaBuilder.in(root.get("title"));
|
||||
for (String title : titles) {
|
||||
inClause.value(title);
|
||||
}
|
||||
criteriaQuery.select(root)
|
||||
.where(inClause);
|
||||
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
|
||||
return query.getResultList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles) {
|
||||
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
|
||||
Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
|
||||
criteriaQuery.select(root)
|
||||
.where(root.get("title")
|
||||
.in(titles));
|
||||
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
|
||||
return query.getResultList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeptEmployee> searchByDepartmentQuery(String searchKey) {
|
||||
CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
|
||||
Root<DeptEmployee> emp = criteriaQuery.from(DeptEmployee.class);
|
||||
|
||||
Subquery<Department> subquery = criteriaQuery.subquery(Department.class);
|
||||
Root<Department> dept = subquery.from(Department.class);
|
||||
subquery.select(dept)
|
||||
.distinct(true)
|
||||
.where(criteriaBuilder.like(dept.get("name"), new StringBuffer("%").append(searchKey)
|
||||
.append("%")
|
||||
.toString()));
|
||||
|
||||
criteriaQuery.select(emp)
|
||||
.where(criteriaBuilder.in(emp.get("department"))
|
||||
.value(subquery));
|
||||
|
||||
TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
|
||||
return query.getResultList();
|
||||
}
|
||||
|
||||
private <T> CriteriaQuery<T> createCriteriaQuery(Class<T> klass) {
|
||||
return criteriaBuilder.createQuery(klass);
|
||||
}
|
||||
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package com.baeldung.hibernate.lob;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.lob.model.User;
|
||||
|
||||
public class HibernateSessionUtil {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addAnnotatedClass(User.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user