JAVA-4: Removed hibernate5-mapping; merged into to hibernate-mapping

This commit is contained in:
sampadawagde
2020-03-15 12:53:28 +05:30
parent 729d35140e
commit bf60206022
47 changed files with 83 additions and 805 deletions
@@ -1,21 +1,48 @@
package com.baeldung.hibernate;
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 {
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.entities.DeptEmployee;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
import com.baeldung.hibernate.pojo.inheritance.Animal;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Pet;
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
public class HibernateUtil {
private static String PROPERTY_FILE_NAME;
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory("");
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
if(propertyFileName.equals("")) propertyFileName = null;
PROPERTY_FILE_NAME = propertyFileName;
ServiceRegistry serviceRegistry = configureServiceRegistry();
return makeSessionFactory(serviceRegistry);
}
public static SessionFactory getSessionFactory(Strategy strategy) {
return buildSessionFactory(strategy);
}
@@ -40,6 +67,35 @@ public class HibernateUtil {
}
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Employee.class);
metadataSources.addAnnotatedClass(Phone.class);
metadataSources.addAnnotatedClass(EntityDescription.class);
metadataSources.addAnnotatedClass(TemporalValues.class);
metadataSources.addAnnotatedClass(DeptEmployee.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(Book.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(MyEmployee.class);
metadataSources.addAnnotatedClass(MyProduct.class);
metadataSources.addAnnotatedClass(Pen.class);
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
@@ -51,7 +107,7 @@ public class HibernateUtil {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
@@ -0,0 +1,45 @@
package com.baeldung.hibernate.entities;
import java.util.List;
import javax.persistence.*;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String name;
@OneToMany(mappedBy="department")
private List<DeptEmployee> employees;
public Department(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DeptEmployee> getEmployees() {
return employees;
}
public void setEmployees(List<DeptEmployee> employees) {
this.employees = employees;
}
}
@@ -0,0 +1,83 @@
package com.baeldung.hibernate.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
@org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_UpdateEmployeeDesignation", query = "call UPDATE_EMPLOYEE_DESIGNATION(:employeeNumber, :newDesignation)", resultClass = DeptEmployee.class) })
@Entity
public class DeptEmployee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String employeeNumber;
private String title;
private String name;
@ManyToOne
private Department department;
public DeptEmployee(String name, String employeeNumber, Department department) {
this.name = name;
this.employeeNumber = employeeNumber;
this.department = department;
}
public DeptEmployee(String name, String employeeNumber, String title, Department department) {
super();
this.name = name;
this.employeeNumber = employeeNumber;
this.title = title;
this.department = department;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
@@ -0,0 +1,61 @@
package com.baeldung.hibernate.lob;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.lob.model.User;
public class HibernateSessionUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory() throws IOException {
return getSessionFactory(null);
}
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addAnnotatedClass(User.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.hibernate.lob.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class User {
@Id
private String id;
@Column(name = "name", columnDefinition="VARCHAR(128)")
private String name;
@Lob
@Column(name = "photo", columnDefinition="BLOB")
private byte[] photo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
}
@@ -1,34 +0,0 @@
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;
}
}
@@ -1,71 +0,0 @@
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();
}
}
}
}
@@ -1,60 +0,0 @@
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();
}
}
}
}
@@ -1,67 +0,0 @@
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();
}
}
}
}
@@ -1,43 +0,0 @@
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;
}
}
@@ -1,42 +0,0 @@
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;
}
}
@@ -1,50 +0,0 @@
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;
}
}
@@ -1,47 +0,0 @@
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;
}
}
@@ -0,0 +1,87 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.*;
import javax.persistence.Entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Where(clause = "deleted = false")
@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int"))
@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private long grossIncome;
private int taxInPercents;
private boolean deleted;
public long getTaxJavaWay() {
return grossIncome * taxInPercents / 100;
}
@Formula("grossIncome * taxInPercents / 100")
private long tax;
@OneToMany
@JoinColumn(name = "employee_id")
@Where(clause = "deleted = false")
private Set<Phone> phones = new HashSet<>(0);
public Employee() {
}
public Employee(long grossIncome, int taxInPercents) {
this.grossIncome = grossIncome;
this.taxInPercents = taxInPercents;
}
public Integer getId() {
return id;
}
public long getGrossIncome() {
return grossIncome;
}
public int getTaxInPercents() {
return taxInPercents;
}
public long getTax() {
return tax;
}
public void setId(Integer id) {
this.id = id;
}
public void setGrossIncome(long grossIncome) {
this.grossIncome = grossIncome;
}
public void setTaxInPercents(int taxInPercents) {
this.taxInPercents = taxInPercents;
}
public boolean getDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Set<Phone> getPhones() {
return phones;
}
}
@@ -0,0 +1,55 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.Any;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class EntityDescription implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String description;
@Any(
metaDef = "EntityDescriptionMetaDef",
metaColumn = @Column(name = "entity_type")
)
@JoinColumn(name = "entity_id")
private Serializable entity;
public EntityDescription() {
}
public EntityDescription(String description, Serializable entity) {
this.description = description;
this.entity = entity;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Serializable getEntity() {
return entity;
}
public void setEntity(Serializable entity) {
this.entity = entity;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
@Entity
public class Phone implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private boolean deleted;
private String number;
public Phone() {
}
public Phone(String number) {
this.number = number;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.hibernate.pojo;
public class Result {
private String employeeName;
private String departmentName;
public Result(String employeeName, String departmentName) {
this.employeeName = employeeName;
this.departmentName = departmentName;
}
public Result() {
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
@@ -0,0 +1,195 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.*;
import java.util.Calendar;
@Entity
public class TemporalValues implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Basic
private java.sql.Date sqlDate;
@Basic
private java.sql.Time sqlTime;
@Basic
private java.sql.Timestamp sqlTimestamp;
@Basic
@Temporal(TemporalType.DATE)
private java.util.Date utilDate;
@Basic
@Temporal(TemporalType.TIME)
private java.util.Date utilTime;
@Basic
@Temporal(TemporalType.TIMESTAMP)
private java.util.Date utilTimestamp;
@Basic
@Temporal(TemporalType.DATE)
private java.util.Calendar calendarDate;
@Basic
@Temporal(TemporalType.TIMESTAMP)
private java.util.Calendar calendarTimestamp;
@Basic
private java.time.LocalDate localDate;
@Basic
private java.time.LocalTime localTime;
@Basic
private java.time.OffsetTime offsetTime;
@Basic
private java.time.Instant instant;
@Basic
private java.time.LocalDateTime localDateTime;
@Basic
private java.time.OffsetDateTime offsetDateTime;
@Basic
private java.time.ZonedDateTime zonedDateTime;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getSqlDate() {
return sqlDate;
}
public void setSqlDate(Date sqlDate) {
this.sqlDate = sqlDate;
}
public Time getSqlTime() {
return sqlTime;
}
public void setSqlTime(Time sqlTime) {
this.sqlTime = sqlTime;
}
public Timestamp getSqlTimestamp() {
return sqlTimestamp;
}
public void setSqlTimestamp(Timestamp sqlTimestamp) {
this.sqlTimestamp = sqlTimestamp;
}
public java.util.Date getUtilDate() {
return utilDate;
}
public void setUtilDate(java.util.Date utilDate) {
this.utilDate = utilDate;
}
public java.util.Date getUtilTime() {
return utilTime;
}
public void setUtilTime(java.util.Date utilTime) {
this.utilTime = utilTime;
}
public java.util.Date getUtilTimestamp() {
return utilTimestamp;
}
public void setUtilTimestamp(java.util.Date utilTimestamp) {
this.utilTimestamp = utilTimestamp;
}
public Calendar getCalendarDate() {
return calendarDate;
}
public void setCalendarDate(Calendar calendarDate) {
this.calendarDate = calendarDate;
}
public Calendar getCalendarTimestamp() {
return calendarTimestamp;
}
public void setCalendarTimestamp(Calendar calendarTimestamp) {
this.calendarTimestamp = calendarTimestamp;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.hibernate.pojo.generator;
import java.io.Serializable;
import java.util.Properties;
import java.util.stream.Stream;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
public class MyGenerator implements IdentifierGenerator, Configurable {
private String prefix;
@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
String query = String.format("select %s from %s",
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(),
obj.getClass().getSimpleName());
Stream<String> ids = session.createQuery(query).stream();
Long max = ids.map(o -> o.replace(prefix + "-", ""))
.mapToLong(Long::parseLong)
.max()
.orElse(0L);
return prefix + "-" + (max + 1);
}
@Override
public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
prefix = properties.getProperty("prefix");
}
}
@@ -0,0 +1,40 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Animal {
@Id
private long animalId;
private String species;
public Animal() {}
public Animal(long animalId, String species) {
this.animalId = animalId;
this.species = species;
}
public long getAnimalId() {
return animalId;
}
public void setAnimalId(long animalId) {
this.animalId = animalId;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Polymorphism;
import org.hibernate.annotations.PolymorphismType;
@Entity
@Polymorphism(type = PolymorphismType.EXPLICIT)
public class Bag implements Item {
@Id
private long bagId;
private String type;
public Bag(long bagId, String type) {
this.bagId = bagId;
this.type = type;
}
public long getBagId() {
return bagId;
}
public void setBagId(long bagId) {
this.bagId = bagId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("1")
public class Book extends MyProduct {
private String author;
public Book() {
}
public Book(long productId, String name, String author) {
super(productId, name);
this.author = author;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
@Entity
public class Car extends Vehicle {
private String engine;
public Car() {
}
public Car(long vehicleId, String manufacturer, String engine) {
super(vehicleId, manufacturer);
this.engine = engine;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
}
@@ -0,0 +1,5 @@
package com.baeldung.hibernate.pojo.inheritance;
public interface Item {
}
@@ -0,0 +1,22 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
@Entity
public class MyEmployee extends Person {
private String company;
public MyEmployee(long personId, String name, String company) {
super(personId, name);
this.company = company;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
@@ -0,0 +1,47 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import org.hibernate.annotations.DiscriminatorFormula;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "product_type", discriminatorType = DiscriminatorType.INTEGER)
// @DiscriminatorFormula("case when author is not null then 1 else 2 end")
public class MyProduct {
@Id
private long productId;
private String name;
public MyProduct() {
}
public MyProduct(long productId, String name) {
super();
this.productId = productId;
this.name = name;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("2")
public class Pen extends MyProduct {
private String color;
public Pen() {
}
public Pen(long productId, String name, String color) {
super(productId, name);
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
@@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public class Person {
@Id
private long personId;
private String name;
public Person() {
}
public Person(long personId, String name) {
this.personId = personId;
this.name = name;
}
public long getPersonId() {
return personId;
}
public void setPersonId(long personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
@PrimaryKeyJoinColumn(name = "petId")
public class Pet extends Animal {
private String name;
public Pet() {
}
public Pet(long animalId, String species, String name) {
super(animalId, species);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,40 @@
package com.baeldung.hibernate.pojo.inheritance;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
@Id
private long vehicleId;
private String manufacturer;
public Vehicle() {
}
public Vehicle(long vehicleId, String manufacturer) {
this.vehicleId = vehicleId;
this.manufacturer = manufacturer;
}
public long getVehicleId() {
return vehicleId;
}
public void setVehicleId(long vehicleId) {
this.vehicleId = vehicleId;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}
@@ -0,0 +1,9 @@
@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int",
metaValues = {
@MetaValue(value = "Employee", targetEntity = Employee.class),
@MetaValue(value = "Phone", targetEntity = Phone.class)
})
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.MetaValue;
@@ -1,56 +0,0 @@
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 + "]";
}
}
@@ -1,74 +0,0 @@
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 + "]";
}
}
@@ -1,31 +0,0 @@
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;
}
}
@@ -1,7 +0,0 @@
package com.baeldung.hibernate.wherejointable;
public enum UserGroupRole {
MEMBER, MODERATOR
}