JAVA-4: Renamed hibernate5-annotations to hibernate-annotations
This commit is contained in:
+73
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.joincolumn.Email;
|
||||
import com.baeldung.hibernate.joincolumn.Office;
|
||||
import com.baeldung.hibernate.joincolumn.OfficeAddress;
|
||||
|
||||
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(com.baeldung.hibernate.joincolumn.OfficialEmployee.class);
|
||||
metadataSources.addAnnotatedClass(Email.class);
|
||||
metadataSources.addAnnotatedClass(Office.class);
|
||||
metadataSources.addAnnotatedClass(OfficeAddress.class);
|
||||
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.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;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.hibernate;
|
||||
|
||||
public class UnsupportedTenancyException extends Exception {
|
||||
public UnsupportedTenancyException (String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
}
|
||||
+69
@@ -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);
|
||||
}
|
||||
}
|
||||
+169
@@ -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;
|
||||
}
|
||||
}
|
||||
+51
@@ -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());
|
||||
}
|
||||
}
|
||||
+34
@@ -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) + '\'';
|
||||
}
|
||||
|
||||
}
|
||||
+88
@@ -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;
|
||||
}
|
||||
}
|
||||
+43
@@ -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);
|
||||
}
|
||||
}
|
||||
+98
@@ -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;
|
||||
}
|
||||
}
|
||||
+39
@@ -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);
|
||||
}
|
||||
}
|
||||
+15
@@ -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;
|
||||
}
|
||||
}
|
||||
+161
@@ -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");
|
||||
}
|
||||
}
|
||||
+47
@@ -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;
|
||||
}
|
||||
}
|
||||
+41
@@ -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;
|
||||
}
|
||||
}
|
||||
+34
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hibernate.oneToMany.config;
|
||||
|
||||
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 HibernateAnnotationUtil {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
try {
|
||||
// Create the SessionFactory from hibernate-annotation.cfg.xml
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build();
|
||||
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
|
||||
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
|
||||
|
||||
return sessionFactory;
|
||||
|
||||
} catch (Throwable ex) {
|
||||
System.err.println("Initial SessionFactory creation failed." + ex);
|
||||
ex.printStackTrace();
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
if (sessionFactory == null)
|
||||
sessionFactory = buildSessionFactory();
|
||||
return sessionFactory;
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
import com.baeldung.hibernate.oneToMany.model.ItemsOIO;
|
||||
|
||||
public class HibernateManyisOwningSide {
|
||||
public static void main(String[] args) {
|
||||
|
||||
Cart cart = new Cart();
|
||||
Cart cart2 = new Cart();
|
||||
|
||||
Items item1 = new Items(cart);
|
||||
Items item2 = new Items(cart2);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(cart2);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
tx = session.beginTransaction();
|
||||
|
||||
item1 = (Items) session.get(Items.class, new Long(1));
|
||||
item2 = (Items) session.get(Items.class, new Long(2));
|
||||
tx.commit();
|
||||
|
||||
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart()
|
||||
.getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart()
|
||||
.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.Cart;
|
||||
import com.baeldung.hibernate.oneToMany.model.Items;
|
||||
|
||||
public class HibernateOneToManyAnnotationMain {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
Cart cart = new Cart();
|
||||
|
||||
Items item1 = new Items(cart);
|
||||
Items item2 = new Items(cart);
|
||||
Set<Items> itemsSet = new HashSet<Items>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
System.out.println("Cart ID=" + cart.getId());
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.baeldung.hibernate.oneToMany.main;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
|
||||
import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
|
||||
import com.baeldung.hibernate.oneToMany.model.CartOIO;
|
||||
import com.baeldung.hibernate.oneToMany.model.ItemsOIO;
|
||||
|
||||
public class HibernateOneisOwningSide {
|
||||
public static void main(String[] args) {
|
||||
|
||||
CartOIO cart = new CartOIO();
|
||||
CartOIO cart2 = new CartOIO();
|
||||
|
||||
ItemsOIO item1 = new ItemsOIO(cart);
|
||||
ItemsOIO item2 = new ItemsOIO(cart2);
|
||||
Set<ItemsOIO> itemsSet = new HashSet<ItemsOIO>();
|
||||
itemsSet.add(item1);
|
||||
itemsSet.add(item2);
|
||||
|
||||
cart.setItems(itemsSet);
|
||||
|
||||
SessionFactory sessionFactory = null;
|
||||
Session session = null;
|
||||
Transaction tx = null;
|
||||
try {
|
||||
// Get Session
|
||||
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
|
||||
session = sessionFactory.getCurrentSession();
|
||||
System.out.println("Session created");
|
||||
// start transaction
|
||||
tx = session.beginTransaction();
|
||||
// Save the Model object
|
||||
session.save(cart);
|
||||
session.save(cart2);
|
||||
session.save(item1);
|
||||
session.save(item2);
|
||||
// Commit transaction
|
||||
tx.commit();
|
||||
|
||||
session = sessionFactory.getCurrentSession();
|
||||
tx = session.beginTransaction();
|
||||
item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1));
|
||||
item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2));
|
||||
tx.commit();
|
||||
|
||||
System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO()
|
||||
.getId());
|
||||
System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO()
|
||||
.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception occured. " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (!sessionFactory.isClosed()) {
|
||||
System.out.println("Closing SessionFactory");
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.hibernate.oneToMany.model;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "CART")
|
||||
public class Cart {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "cart_id")
|
||||
private long id;
|
||||
|
||||
|
||||
@OneToMany(mappedBy = "cart")
|
||||
private Set<Items> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
public Set<Items> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(Set<Items> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.hibernate.oneToMany.model;
|
||||
|
||||
import java.util.Set;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.OneToMany;
|
||||
import javax.persistence.Table;
|
||||
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name = "CARTOIO")
|
||||
public class CartOIO {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@OneToMany
|
||||
@JoinColumn(name = "cart_id") // we need to duplicate the physical information
|
||||
private Set<ItemsOIO> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Set<ItemsOIO> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(Set<ItemsOIO> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.hibernate.oneToMany.model;
|
||||
|
||||
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.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "ITEMS")
|
||||
public class Items {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@Column(name = "id")
|
||||
private long id;
|
||||
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "cart_id", nullable = false)
|
||||
private Cart cart;
|
||||
|
||||
// Hibernate requires no-args constructor
|
||||
public Items() {
|
||||
}
|
||||
|
||||
public Items(Cart c) {
|
||||
this.cart = c;
|
||||
}
|
||||
|
||||
public Cart getCart() {
|
||||
return cart;
|
||||
}
|
||||
|
||||
public void setCart(Cart cart) {
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.hibernate.oneToMany.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "ITEMSOIO")
|
||||
public class ItemsOIO {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "cart_id", insertable = false, updatable = false)
|
||||
private CartOIO cart;
|
||||
|
||||
// Hibernate requires no-args constructor
|
||||
public ItemsOIO() {
|
||||
}
|
||||
|
||||
public ItemsOIO(CartOIO c) {
|
||||
this.cart = c;
|
||||
}
|
||||
|
||||
public CartOIO getCartOIO() {
|
||||
return cart;
|
||||
}
|
||||
|
||||
public void setCartOIO(CartOIO cart) {
|
||||
this.cart = cart;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -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;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.hibernate.wherejointable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToMany;
|
||||
|
||||
@Entity(name = "e_group")
|
||||
public class Group {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToMany(mappedBy = "groups")
|
||||
private List<User> users = new ArrayList<>();
|
||||
|
||||
public Group(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<User> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public void setUsers(List<User> users) {
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Group [name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.hibernate.wherejointable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.JoinColumn;
|
||||
import javax.persistence.JoinTable;
|
||||
import javax.persistence.ManyToMany;
|
||||
|
||||
import org.hibernate.annotations.WhereJoinTable;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
@ManyToMany
|
||||
@JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
|
||||
private List<Group> groups = new ArrayList<>();
|
||||
|
||||
@WhereJoinTable(clause = "role='MODERATOR'")
|
||||
@ManyToMany
|
||||
@JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id"))
|
||||
private List<Group> moderatorGroups = new ArrayList<>();
|
||||
|
||||
public User(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<Group> getGroups() {
|
||||
return groups;
|
||||
}
|
||||
|
||||
public void setGroups(List<Group> groups) {
|
||||
this.groups = groups;
|
||||
}
|
||||
|
||||
public void setModeratorGroups(List<Group> moderatorGroups) {
|
||||
this.moderatorGroups = moderatorGroups;
|
||||
}
|
||||
|
||||
public List<Group> getModeratorGroups() {
|
||||
return moderatorGroups;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User [name=" + name + "]";
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.hibernate.wherejointable;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.EnumType;
|
||||
import javax.persistence.Enumerated;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity(name = "r_user_group")
|
||||
public class UserGroupRelation implements Serializable {
|
||||
|
||||
@Id
|
||||
@Column(name = "user_id", insertable = false, updatable = false)
|
||||
private final Long userId;
|
||||
|
||||
@Id
|
||||
@Column(name = "group_id", insertable = false, updatable = false)
|
||||
private final Long groupId;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
private final UserGroupRole role;
|
||||
|
||||
public UserGroupRelation(Long userId, Long groupId, UserGroupRole role) {
|
||||
this.userId = userId;
|
||||
this.groupId = groupId;
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.hibernate.wherejointable;
|
||||
|
||||
public enum UserGroupRole {
|
||||
|
||||
MEMBER, MODERATOR
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
|
||||
version="2.0">
|
||||
<persistence-unit name="com.baeldung.movie_catalog">
|
||||
<description>Hibernate EntityManager Demo</description>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="update"/>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
|
||||
<property name="javax.persistence.jdbc.user" value="root"/>
|
||||
<property name="javax.persistence.jdbc.password" value="root"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user