Skip to content

Instantly share code, notes, and snippets.

@dimMaryanto93
Last active February 3, 2021 05:07
Show Gist options
  • Save dimMaryanto93/e8d2abb5361e811860d6a462270f119b to your computer and use it in GitHub Desktop.
Save dimMaryanto93/e8d2abb5361e811860d6a462270f119b to your computer and use it in GitHub Desktop.
Hibernate Core
package com.maryanto.dimas.bootcamp.example.query.hql.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AggregateFunctionModel {
private Long countFunction;
private Double avgFunction;
private BigDecimal minFunction;
private BigDecimal maxFunction;
private BigDecimal sumFunction;
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Embeddable
public class AlamatEmbeddable {
@Column(name = "provinsi", length = 50)
private String provinsi;
@Column(name = "kota", length = 50)
private String kota;
@Column(name = "kelurahan", length = 100)
private String kelurahan;
@Column(name = "kecamatan", length = 100)
private String kecamatan;
@Column(name = "rw", length = 3)
private Integer rw;
@Column(name = "rt", length = 3)
private Integer rt;
@Column(name = "kode_pos", length = 6)
private Integer kodePos;
@Column(name = "nama_jalan", length = 100)
private String namaJalan;
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "alamat", schema = "mapping")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
public class AlamatEntity {
@Id
@Column(name = "id")
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "provinsi", length = 50)
private String provinsi;
@Column(name = "kota", length = 50)
private String kota;
@Column(name = "kelurahan", length = 100)
private String kelurahan;
@Column(name = "kecamatan", length = 100)
private String kecamatan;
@Column(name = "rw", length = 3)
private Integer rw;
@Column(name = "rt", length = 3)
private Integer rt;
@Column(name = "kode_pos", length = 6)
private Integer kodePos;
@Column(name = "nama_jalan", length = 100)
private String namaJalan;
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.AlamatEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class AlamatEntityDao implements CrudRepository<AlamatEntity, String> {
private Session session;
public AlamatEntityDao(Session session) {
this.session = session;
}
@Override
public AlamatEntity save(AlamatEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public AlamatEntity update(AlamatEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<AlamatEntity> findById(String value) throws HibernateException {
AlamatEntity alamat = this.session.find(AlamatEntity.class, value);
return alamat != null ? Optional.of(alamat) : Optional.empty();
}
@Override
public List<AlamatEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AritmaticModel {
private String id;
private String nama;
private BigDecimal salarySetahun;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.ClassRoomEmbeddedMapping;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.KeyClassRoomEmbeddedId;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.KeyClassRoomIdClass;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
public class ClassRoomEmbeddedDao implements CrudRepository<ClassRoomEmbeddedMapping, KeyClassRoomEmbeddedId> {
private Session session;
public ClassRoomEmbeddedDao(Session session) {
this.session = session;
}
@Override
public ClassRoomEmbeddedMapping save(ClassRoomEmbeddedMapping value) throws HibernateException {
KeyClassRoomEmbeddedId primaryKey = (KeyClassRoomEmbeddedId) this.session.save(value);
value.setPk(primaryKey);
return value;
}
@Override
public ClassRoomEmbeddedMapping update(ClassRoomEmbeddedMapping value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(KeyClassRoomEmbeddedId value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<ClassRoomEmbeddedMapping> findById(KeyClassRoomEmbeddedId value) throws HibernateException {
ClassRoomEmbeddedMapping classRoom = this.session.find(ClassRoomEmbeddedMapping.class, value);
return classRoom != null ? Optional.of(classRoom) : Optional.empty();
}
@Override
public List<ClassRoomEmbeddedMapping> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "kelas_embedded", schema = "kampus")
public class ClassRoomEmbeddedMapping {
@EmbeddedId
private KeyClassRoomEmbeddedId pk;
@Column(name = "kelas_name")
private String name;
@Column(name = "prodi")
private String programStudy;
@Column(name = "description")
private String description;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.ClassRoomEmbeddedMapping;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.KeyClassRoomEmbeddedId;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.ClassRoomMappingIdClass;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.KeyClassRoomIdClass;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class ClassRoomIdClassDao implements CrudRepository<ClassRoomMappingIdClass, KeyClassRoomIdClass> {
private Session session;
public ClassRoomIdClassDao(Session session) {
this.session = session;
}
@Override
public ClassRoomMappingIdClass save(ClassRoomMappingIdClass value) throws HibernateException {
KeyClassRoomIdClass primaryKey = (KeyClassRoomIdClass) this.session.save(value);
value.setClassId(primaryKey.getClassId());
value.setYear(primaryKey.getYear());
return value;
}
@Override
public ClassRoomMappingIdClass update(ClassRoomMappingIdClass value) throws HibernateException {
return null;
}
@Override
public boolean removeById(KeyClassRoomIdClass value) throws HibernateException {
return false;
}
@Override
public Optional<ClassRoomMappingIdClass> findById(KeyClassRoomIdClass value) throws HibernateException {
ClassRoomMappingIdClass classRoom = this.session.find(ClassRoomMappingIdClass.class, value);
return classRoom != null ? Optional.of(classRoom) : Optional.empty();
}
@Override
public List<ClassRoomMappingIdClass> findAll() throws HibernateException {
return null;
}
}
package com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@IdClass(KeyClassRoomIdClass.class)
@Table(name = "kelas_idclass", schema = "kampus")
public class ClassRoomMappingIdClass {
@Id
@Column(name = "tahun_angkatan", length = 4, columnDefinition = "int check(tahun_angkatan >= 1999)")
private Integer year;
@Id
@Column(name = "class_id", length = 50)
private String classId;
@Column(name = "kelas_name")
private String name;
@Column(name = "prodi")
private String programStudy;
@Column(name = "description")
private String description;
}
package com.maryanto.dimas.bootcamp.example.simple.entity.kampus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Check;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(
name = "kelas_check",
schema = "kampus"
)
public class ClassWithCheckConstraints {
@Id
@Column(name = "kode")
private String id;
@Column(name = "nama", length = 10)
private String name;
@Column(name = "angkatan", length = 4, columnDefinition = "int check(angkatan >= 2000)")
private Integer year;
@Column(name = "created_by", length = 100, nullable = false)
private String createdBy;
@Column(name = "created_datetime", nullable = false)
private LocalDateTime createdDateTime;
@Column(name = "last_updated_by", length = 100)
private String lastUpdateBy;
@Column(name = "last_updated_datetime")
private LocalDateTime lastUpdatedBy;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.constraints.ClassWithCheckConstraints;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class ClassWithCheckDao implements CrudRepository<ClassWithCheckConstraints, String> {
private Session session;
public ClassWithCheckDao(Session session) {
this.session = session;
}
@Override
public ClassWithCheckConstraints save(ClassWithCheckConstraints value) throws HibernateException {
this.session.save(value);
return value;
}
@Override
public ClassWithCheckConstraints update(ClassWithCheckConstraints value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<ClassWithCheckConstraints> findById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List<ClassWithCheckConstraints> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.simple.entity.kampus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(
name = "kelas_sequance_table",
schema = "kampus"
)
@SequenceGenerator(
name = "seq_gen_kelas",
schema = "kampus",
allocationSize = 1,
sequenceName = "seq_kelas",
initialValue = 1)
public class ClassWithSequanceGenerator {
@Id
@Column(name = "kode")
@GeneratedValue(generator = "seq_gen_kelas")
private Long id;
@Column(name = "nama", length = 10)
private String name;
@Column(name = "angkatan", length = 4)
private Integer year;
@Column(name = "created_by", length = 100, nullable = false)
private String createdBy;
@Column(name = "created_datetime", nullable = false)
private LocalDateTime createdDateTime;
@Column(name = "last_updated_by", length = 100)
private String lastUpdateBy;
@Column(name = "last_updated_datetime")
private LocalDateTime lastUpdatedBy;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithSequanceGenerator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class ClassWithSequanceGeneratorDao implements CrudRepository<ClassWithSequanceGenerator, String> {
private Session session;
public ClassWithSequanceGeneratorDao(Session session) {
this.session = session;
}
@Override
public ClassWithSequanceGenerator save(ClassWithSequanceGenerator value) throws HibernateException {
Long primaryKey = (Long) this.session.save(value);
value.setId(primaryKey);
return value;
}
@Override
public ClassWithSequanceGenerator update(ClassWithSequanceGenerator value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<ClassWithSequanceGenerator> findById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List<ClassWithSequanceGenerator> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.simple.entity.kampus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(
name = "kelas_unique",
schema = "kampus",
uniqueConstraints = {
@UniqueConstraint(
name = "un_kelas",
columnNames = {"nama", "angkatan"}
)
}
)
public class ClassWithUniqueConstraints {
@Id
@Column(name = "kode")
private String id;
@Column(name = "nama", length = 10)
private String name;
@Column(name = "angkatan", length = 4)
private Integer year;
@Column(name = "created_by", length = 100, nullable = false)
private String createdBy;
@Column(name = "created_datetime", nullable = false)
private LocalDateTime createdDateTime;
@Column(name = "last_updated_by", length = 100)
private String lastUpdateBy;
@Column(name = "last_updated_datetime")
private LocalDateTime lastUpdatedBy;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.constraints.ClassWithUniqueConstraints;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class ClassWithUniqueDao implements CrudRepository<ClassWithUniqueConstraints, String> {
private Session session;
public ClassWithUniqueDao(Session session) {
this.session = session;
}
@Override
public ClassWithUniqueConstraints save(ClassWithUniqueConstraints value) throws HibernateException {
this.session.save(value);
return value;
}
@Override
public ClassWithUniqueConstraints update(ClassWithUniqueConstraints value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<ClassWithUniqueConstraints> findById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List<ClassWithUniqueConstraints> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.simple.entity.kampus;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.time.LocalDateTime;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(
name = "kelas_check",
schema = "kampus"
)
@GenericGenerator(name = "uuid_kelas_gen", strategy = "uuid2")
public class ClassWithUuidGenerator {
@Id
@Column(name = "kode")
@GeneratedValue(generator = "uuid_kelas_gen")
private String id;
@Column(name = "nama", length = 10)
private String name;
@Column(name = "angkatan", length = 4, columnDefinition = "int check(angkatan >= 2000)")
private Integer year;
@Column(name = "created_by", length = 100, nullable = false)
private String createdBy;
@Column(name = "created_datetime", nullable = false)
private LocalDateTime createdDateTime;
@Column(name = "last_updated_by", length = 100)
private String lastUpdateBy;
@Column(name = "last_updated_datetime")
private LocalDateTime lastUpdatedBy;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithUuidGenerator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class ClassWIthUuidGeneratorDao implements CrudRepository<ClassWithUuidGenerator, String> {
private Session session;
public ClassWIthUuidGeneratorDao(Session session) {
this.session = session;
}
@Override
public ClassWithUuidGenerator save(ClassWithUuidGenerator value) throws HibernateException {
String primaryKey = (String) this.session.save(value);
value.setId(primaryKey);
return value;
}
@Override
public ClassWithUuidGenerator update(ClassWithUuidGenerator value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<ClassWithUuidGenerator> findById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List<ClassWithUuidGenerator> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ConcatnationModel {
private String nama;
private String alamat;
}
package com.maryanto.dimas.bootcamp.example.repository;
import org.hibernate.HibernateException;
public interface CrudRepository<T, PK> extends ReadRepository<T, PK> {
T save(T value) throws HibernateException;
T update(T value) throws HibernateException;
boolean removeById(PK value) throws HibernateException;
}
package com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "employee_ordinal", schema = "enumeration")
public class EmployeeEnumOrdinal {
@Id
@GeneratedValue
@Column(name = "employee_id")
private Long id;
@Column(name = "employee_name", length = 25, nullable = false)
private String name;
@Column(name = "birth_date", nullable = false)
private LocalDate birthDate;
@Enumerated(EnumType.ORDINAL)
@Column(name = "employee_status")
private EmployeeStatus status;
}
package com.maryanto.dimas.bootcamp.example.mapping.enumeration.dao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumOrdinal;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class EmployeeEnumOrdinalDao implements CrudRepository<EmployeeEnumOrdinal, Long> {
private Session session;
public EmployeeEnumOrdinalDao(Session session) {
this.session = session;
}
@Override
public EmployeeEnumOrdinal save(EmployeeEnumOrdinal value) throws HibernateException {
Long returnKey = (Long) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public EmployeeEnumOrdinal update(EmployeeEnumOrdinal value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<EmployeeEnumOrdinal> findById(Long value) throws HibernateException {
EmployeeEnumOrdinal empl = this.session.find(EmployeeEnumOrdinal.class, value);
return empl != null ? Optional.of(empl) : Optional.empty();
}
@Override
public List<EmployeeEnumOrdinal> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "employee_string", schema = "enumeration")
public class EmployeeEnumString {
@Id
@GeneratedValue
@Column(name = "employee_id")
private Long id;
@Column(name = "employee_name", length = 25, nullable = false)
private String name;
@Column(name = "birth_date", nullable = false)
private LocalDate birthDate;
@Enumerated(EnumType.STRING)
@Column(name = "employee_status")
private EmployeeStatus status;
}
package com.maryanto.dimas.bootcamp.example.mapping.enumeration.dao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class EmployeeEnumStringDao implements CrudRepository<EmployeeEnumString, Long> {
private Session session;
public EmployeeEnumStringDao(Session session) {
this.session = session;
}
@Override
public EmployeeEnumString save(EmployeeEnumString value) throws HibernateException {
Long returnKey = (Long) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public EmployeeEnumString update(EmployeeEnumString value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<EmployeeEnumString> findById(Long value) throws HibernateException {
EmployeeEnumString empl = this.session.find(EmployeeEnumString.class, value);
return empl != null ? Optional.of(empl) : Optional.empty();
}
@Override
public List<EmployeeEnumString> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.parentchild.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class EmployeeParentChildDao implements CrudRepository<EmployeeParentChildEntity, String> {
private Session session;
public EmployeeParentChildDao(Session session) {
this.session = session;
}
@Override
public EmployeeParentChildEntity save(EmployeeParentChildEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public EmployeeParentChildEntity update(EmployeeParentChildEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<EmployeeParentChildEntity> findById(String value) throws HibernateException {
EmployeeParentChildEntity empl = this.session.find(EmployeeParentChildEntity.class, value);
return empl != null ? Optional.of(empl) : Optional.empty();
}
@Override
public List<EmployeeParentChildEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "employees", schema = "parentchild")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
public class EmployeeParentChildEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "full_name", length = 50)
private String name;
@Column(name = "street_address", length = 100)
private String address;
@Column(name = "salary", nullable = false)
private BigDecimal salary;
@Column(name = "job_id", nullable = false)
private String job;
@ManyToOne
@JoinColumn(name = "manager_id")
@FieldNameConstants.Exclude
@EqualsAndHashCode.Exclude
@ToString.Exclude
private EmployeeParentChildEntity manager;
@OneToMany(mappedBy = "manager")
@FieldNameConstants.Exclude
@EqualsAndHashCode.Exclude
@ToString.Exclude
private Set<EmployeeParentChildEntity> employees = new HashSet<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity;
public enum EmployeeStatus {
ACTIVE, RESIGN, LEAVE, OUT_OF_TOWN_DUTY, FOREIGN_SERVICE
}
package com.maryanto.dimas.bootcamp.example.query.hql.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GroupByModel {
private String jobName;
private BigDecimal salary;
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- connection db -->
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernate_core</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">bootcamp</property>
<property name="hibernate.connection.password">bootcamp</property>
<!-- show generated sql -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- set default not auto commit -->
<property name="hibernate.connection.autocommit">false</property>
<!-- how hibernate translate from java to db -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL10Dialect</property>
<!-- DB schema will be updated if needed -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- connection pooling-->
<property name="hibernate.connection.pool_size">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">50</property>
</session-factory>
</hibernate-configuration>
package com.maryanto.dimas.bootcamp.example.config;
import com.maryanto.dimas.bootcamp.example.entity.buku.Penerbit;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
@Slf4j
public class HibernateConfiguration {
private static final SessionFactory ourSessionFactory;
static {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
MetadataSources metadataSources = new MetadataSources(registry);
// TODO add your mapping here!
metadataSources.addAnnotatedClass(Penerbit.class);
ourSessionFactory = metadataSources.buildMetadata().buildSessionFactory();
} catch (Throwable ex) {
StandardServiceRegistryBuilder.destroy(registry);
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.AggregateFunctionModel;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.math.BigDecimal;
public class HQLAggregationFunctionDao {
private Session session;
public HQLAggregationFunctionDao(Session session) {
this.session = session;
}
public AggregateFunctionModel aggregateFunctions(){
Query<AggregateFunctionModel> query = this.session.createQuery(
"select new com.maryanto.dimas.bootcamp.example.query.hql.dto.AggregateFunctionModel(count(*), avg(salary), min(salary), max(salary), sum(salary)) \n" +
"from EmployeeParentChildEntity", AggregateFunctionModel.class);
return query.getSingleResult();
}
/**
* count function always return Long
* @return
*/
public Long countData(){
Query<Long> query = this.session.createQuery(
"select count(*) \n" +
"from EmployeeParentChildEntity", Long.class);
return query.getSingleResult();
}
/**
* avg function always return Double
* @return
*/
public Double avgGajiKarwayan(){
Query<Double> query = this.session.createQuery(
"select avg(salary) \n" +
"from EmployeeParentChildEntity", Double.class);
return query.getSingleResult();
}
/**
* min & max function return type same as property in entity
* @return
*/
public Object[] minAndMaxGajiKarywan() {
Query<Object[]> query = this.session.createQuery(
"select min(salary), \n" +
"max(salary) \n" +
"from EmployeeParentChildEntity", Object[].class);
return query.getSingleResult();
}
/**
* sum function return type same as property in entity
* @return
*/
public BigDecimal sumGajiKaryawan(){
Query<BigDecimal> query = this.session.createQuery(
"select sum(salary) \n" +
"from EmployeeParentChildEntity", BigDecimal.class);
return query.getSingleResult();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.AritmaticModel;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.math.BigDecimal;
import java.util.List;
public class HQLArithmeticDao {
private Session session;
public HQLArithmeticDao(Session session) {
this.session = session;
}
/**
* mapping to other class
*
* @return
*/
public List<AritmaticModel> hitungSalaryEmployeeDalamSetahun() {
Query<AritmaticModel> query = this.session.createQuery(
"select new com.maryanto.dimas.bootcamp.example.query.hql.dto.AritmaticModel(id, name, (salary * :berapaBulan)) \n" +
"from EmployeeParentChildEntity", AritmaticModel.class);
query.setParameter("berapaBulan", new BigDecimal(12));
return query.getResultList();
}
/**
* multiply operation
*
* @return
*/
public BigDecimal hitungTotalSalarySemuaEmployeeDalamSetahun() {
Query<BigDecimal> query = this.session.createQuery(
"select sum(salary * 12) \n" +
"from EmployeeParentChildEntity", BigDecimal.class);
return query.getSingleResult();
}
public List<EmployeeParentChildEntity> cariKaryawanYangSalaryDalamSetahunDiatas(BigDecimal salaryCompare) {
Query<EmployeeParentChildEntity> query = this.session.createQuery(
"from EmployeeParentChildEntity \n" +
"where (salary * 12) >= :salaryCompare", EmployeeParentChildEntity.class);
query.setParameter("salaryCompare", salaryCompare);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
public class HQLBetweenPredicateDao {
private Session session;
public HQLBetweenPredicateDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> findFirstCharacterBetween(String from, String to) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where substring(lower(name) , 1, 1) between :from and :to";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("from", from)
.setParameter("to", to);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findSalaryBetween(BigDecimal from, BigDecimal to) {
//language=HQL
String hql = "from EmployeeParentChildEntity\n" +
"where coalesce(salary, 0) between :from and :to";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("to", to)
.setParameter("from", from);
return query.getResultList();
}
public List<EmployeeEnumString> findBirthDateBetween(LocalDate from, LocalDate to){
//language=HQL
String hql = "from EmployeeEnumString \n" +
"where birthDate between :dateFrom and :dateTo";
Query<EmployeeEnumString> query = this.session.createQuery(hql, EmployeeEnumString.class)
.setParameter("dateFrom", from)
.setParameter("dateTo", to);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import org.hibernate.Session;
import org.hibernate.query.Query;
public class HQLCaseWhenExpresionDao {
private Session session;
public HQLCaseWhenExpresionDao(Session session) {
this.session = session;
}
public String simpleCaseWhenExpresion(String employeeId) {
//language=HQL
String hql = "select \n" +
" case \n" +
" when empl.manager is not null then concat('your manager name is ', man.name) \n" +
" else 'you don''t have a manager' \n" +
" end \n" +
"from EmployeeParentChildEntity empl left join EmployeeParentChildEntity man on (empl.manager = man)\n" +
"where empl.id = :id";
Query<String> query = this.session.createQuery(hql, String.class);
query.setParameter("id", employeeId);
return query.getSingleResult();
}
public String multipleConditionCaseWhenExpresion(String employeeId){
//language=HQL
String hql = "select \n" +
" case \n" +
" when salary > 10000000 then concat(name, ' gajinya lebih dari Rp. 10jt / bulan') \n" +
" when salary between 5000000 and 10000000 then concat(name, ' gajinya diantara Rp. 10jt s/d Rp. 5jt / bulan')\n" +
" when salary between 0 and 5000000 then concat(name, ' gajinya dibawah Rp. 5jt / bulan')\n" +
" else concat(name, ' kemungkinan karyawan tersebut belum memiliki pekerjaan')\n" +
" end\n" +
"from EmployeeParentChildEntity \n" +
"where id = :id";
Query<String> query = this.session.createQuery(hql, String.class);
query.setParameter("id", employeeId);
return query.getSingleResult();
}
public String nestedCaseWhenExpresion(String employeeId) {
//language=HQL
String hql = "select \n" +
" case when empl.manager is not null then \n" +
" case when empl.salary > 3000000 then concat(empl.name, ' mendapatan gaji sebulan lebih besar dari Rp.3,000,000.00 dan memiliki atasan bernama ', man.name)\n" +
" else concat(empl.name, ' mendapatkan gaji sebulan lebih kecil dari Rp.3,000,000.00 dan memiliki atasan bernama ', man.name)\n" +
" end \n" +
" else concat(empl.name, ' mendapatkan gaji sebulan sebesar ', empl.salary, ' dan tidak memiliki atasan')\n" +
" end \n" +
"from EmployeeParentChildEntity empl left join EmployeeParentChildEntity man on (empl.manager = man)\n" +
"where empl.id = :id";
Query<String> query = this.session.createQuery(hql, String.class);
query.setParameter("id", employeeId);
return query.getSingleResult();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import org.hibernate.Session;
import org.hibernate.query.Query;
public class HQLCoalesceAndNullIfDao {
private Session session;
public HQLCoalesceAndNullIfDao(Session session) {
this.session = session;
}
public String coalesceFunction(Long penerbitId){
//language=HQL
String hql = "select coalesce(noFax, phoneNumber, 'publisher not have contact number!') \n" +
"from Penerbit \n" +
"where id = :id";
Query<String> query = this.session.createQuery(hql, String.class);
return query.setParameter("id", penerbitId)
.getSingleResult();
}
/**
* sama seperti: `select case when noFax = phoneNumber then null else noFax from Penerbit`
* @param penerbitId
* @return
*/
public String nullIfFunction(Long penerbitId){
//language=HQL
String hql = "select nullif(noFax, phoneNumber) \n" +
"from Penerbit \n" +
"where id = :id";
Query<String> query = this.session.createQuery(hql, String.class);
return query.setParameter("id", penerbitId)
.getSingleResult();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.math.BigDecimal;
import java.util.List;
public class HQLCombinePredicateDao {
private Session session;
public HQLCombinePredicateDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> findBySalaryHigherThanAndJobName(
BigDecimal salary, String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where salary >= :salary and job = :jobName";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("salary", salary)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findBySalaryHigherThanOrJobName(
BigDecimal salary, String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where salary >= :salary or job = :jobName";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("salary", salary)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findBySalaryHigherThanAndJobNameOrManagerIsNotNull(
BigDecimal salary, String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where salary >= :salary and job = :jobName or manager is null";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("salary", salary)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findBySalaryHigherThanOrJobNameAndManagerIsNotNullPriority(
BigDecimal salary, String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where salary >= :salary or (job = :jobName and manager is null)";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("salary", salary)
.setParameter("jobName", jobName);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.ConcatnationModel;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLConcatnationDao {
private Session session;
public HQLConcatnationDao(Session session) {
this.session = session;
}
public List<ConcatnationModel> concatFunctionJpa() {
Query<ConcatnationModel> query = this.session.createQuery(
"select new com.maryanto.dimas.bootcamp.example.query.hql.dto.ConcatnationModel(\n" +
" mhs.nama, \n" +
" concat(alamat.provinsi, ', ', alamat.kota)\n" +
")\n" +
"from MahasiswaOneToOneEntity mhs \n" +
"join AlamatEntity alamat on (mhs.alamat = alamat)", ConcatnationModel.class);
return query.getResultList();
}
public List<ConcatnationModel> concatHQL() {
Query<ConcatnationModel> query = this.session.createQuery(
"select new com.maryanto.dimas.bootcamp.example.query.hql.dto.ConcatnationModel(\n" +
" mhs.nama, \n" +
" alamat.provinsi || ', ' || alamat.kota\n" +
")\n" +
"from MahasiswaOneToOneEntity mhs \n" +
"join AlamatEntity alamat on (mhs.alamat = alamat)", ConcatnationModel.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLDistinctAsEntityDao {
private Session session;
public HQLDistinctAsEntityDao(Session session) {
this.session = session;
}
public List<KelasEntity> findKelasByListMahasiswa() {
Query<KelasEntity> query = this.session.createQuery("select distinct mhs.kelas " +
"from MahasiswaManyToOneEntity mhs", KelasEntity.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLDistinctAsProjectionsDao {
private Session session;
public HQLDistinctAsProjectionsDao(Session session) {
this.session = session;
}
public List<EmployeeStatus> findEmployeeStatusOnUsedByEmployees() {
Query<EmployeeStatus> query = this.session.createQuery("select distinct sts.status \n" +
"from EmployeeEnumString sts", EmployeeStatus.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsType;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsValue;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToManyEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLEmptyCollectionPredicateDao {
private Session session;
public HQLEmptyCollectionPredicateDao(Session session) {
this.session = session;
}
public List<MahasiswaElementCollectionAsValue> emptyCollectionAsValue() {
//language=HQL
String hql = "select mhs\n" +
"from MahasiswaElementCollectionAsValue mhs\n" +
"where mhs.hobies is empty";
Query<MahasiswaElementCollectionAsValue> query = this.session
.createQuery(hql, MahasiswaElementCollectionAsValue.class);
return query.getResultList();
}
public List<MahasiswaElementCollectionAsValue> notEmptyCollectionAsValue() {
//language=HQL
String hql = "select mhs\n" +
"from MahasiswaElementCollectionAsValue mhs\n" +
"where mhs.hobies is not empty";
Query<MahasiswaElementCollectionAsValue> query = this.session
.createQuery(hql, MahasiswaElementCollectionAsValue.class);
return query.getResultList();
}
public List<MahasiswaElementCollectionAsType> emptyCollectionAsType() {
//language=HQL
String hql = "select mhs\n" +
"from MahasiswaElementCollectionAsType mhs\n" +
"where mhs.addresses is empty";
Query<MahasiswaElementCollectionAsType> query = this.session
.createQuery(hql, MahasiswaElementCollectionAsType.class);
return query.getResultList();
}
public List<MahasiswaElementCollectionAsType> notEmptyCollectionAsType() {
//language=HQL
String hql = "select mhs\n" +
"from MahasiswaElementCollectionAsType mhs\n" +
"where mhs.addresses is not empty";
Query<MahasiswaElementCollectionAsType> query = this.session
.createQuery(hql, MahasiswaElementCollectionAsType.class);
return query.getResultList();
}
public List<MahasiswaOneToManyEntity> emptyCollectionAsEntity() {
//language=HQL
String hql = "select mhs\n" +
"from MahasiswaOneToManyEntity mhs\n" +
"where mhs.listAlamat is empty";
Query<MahasiswaOneToManyEntity> query = this.session
.createQuery(hql, MahasiswaOneToManyEntity.class);
return query.getResultList();
}
public List<MahasiswaOneToManyEntity> notEmptyCollectionAsEntity() {
//language=HQL
String hql = "select mhs\n" +
"from MahasiswaOneToManyEntity mhs\n" +
"where mhs.listAlamat is empty";
Query<MahasiswaOneToManyEntity> query = this.session
.createQuery(hql, MahasiswaOneToManyEntity.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.GroupByModel;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.math.BigDecimal;
import java.util.List;
public class HQLGroupByDao {
private Session session;
public HQLGroupByDao(Session session) {
this.session = session;
}
public List<GroupByModel> findGroupByJob(){
//language=HQL
String hql = "select new com.maryanto.dimas.bootcamp.example.query.hql.dto.GroupByModel(job, sum(salary))\n" +
"from EmployeeParentChildEntity \n" +
"group by job";
Query<GroupByModel> query = this.session.createQuery(hql, GroupByModel.class);
return query.getResultList();
}
public List<GroupByModel> findGroupByJobWithHaving(BigDecimal salary){
//language=HQL
String hql = "select new com.maryanto.dimas.bootcamp.example.query.hql.dto.GroupByModel(job, sum(salary))\n" +
"from EmployeeParentChildEntity \n" +
"group by job\n" +
"having sum(salary) >= :salary";
Query<GroupByModel> query = this.session.createQuery(hql, GroupByModel.class)
.setParameter("salary", salary);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
public class HQLInPredicateDao {
private Session session;
public HQLInPredicateDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> findSalaryIn(List<BigDecimal> salaries) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where salary in (:salaries)";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameterList("salaries", salaries);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findJobIn(List<String> jobs) {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where job in (:jobs)";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameterList("jobs", jobs);
return query.getResultList();
}
public List<EmployeeEnumString> findBirthDateIn(List<LocalDate> dates) {
//language=HQL
String hql = "from EmployeeEnumString \n" +
"where birthDate in (:dates)";
Query<EmployeeEnumString> query = this.session.createQuery(hql, EmployeeEnumString.class)
.setParameterList("dates", dates);
return query.getResultList();
}
public List<EmployeeEnumString> findStatusIn(List<EmployeeStatus> statuses) {
//language=HQL
String hql = "from EmployeeEnumString \n" +
"where status in (:statuses)";
Query<EmployeeEnumString> query = this.session.createQuery(hql, EmployeeEnumString.class)
.setParameterList("statuses", statuses);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLJoinExplicitDao {
private Session session;
public HQLJoinExplicitDao(Session session) {
this.session = session;
}
public List<MahasiswaOneToOneEntity> findByAlamatProvinsiKeywordOn(String provinsi) throws HibernateException {
Query<MahasiswaOneToOneEntity> query = this.session
.createQuery("select mhs from MahasiswaOneToOneEntity mhs \n" +
"join AlamatEntity alamat on (mhs.alamat = alamat)\n" +
"where alamat.provinsi = :provinsi",
MahasiswaOneToOneEntity.class);
query.setParameter("provinsi", provinsi);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findByAlamatProvinsiKeywordWith(String provinsi) throws HibernateException {
Query<MahasiswaOneToOneEntity> query = this.session
.createQuery("select mhs from MahasiswaOneToOneEntity mhs \n" +
"join AlamatEntity alamat with mhs.alamat = alamat where alamat.provinsi = :provinsi",
MahasiswaOneToOneEntity.class);
query.setParameter("provinsi", provinsi);
return query.list();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLJoinImplicitDao {
private Session session;
public HQLJoinImplicitDao(Session session) {
this.session = session;
}
public List<MahasiswaOneToOneEntity> findByAlamatProvinsi(String provinsi) throws HibernateException {
Query<MahasiswaOneToOneEntity> query = this.session
.createQuery("from MahasiswaOneToOneEntity mhs where mhs.alamat.provinsi = :provinsi",
MahasiswaOneToOneEntity.class);
query.setParameter("provinsi", provinsi);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLLikePredicatesDao {
private Session session;
public HQLLikePredicatesDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> likeOperator(String employeeName) {
//language=HQL
String hql = "from EmployeeParentChildEntity where name like :nameExpression";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("nameExpression", employeeName);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MataKuliahEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import javax.persistence.NoResultException;
import java.util.List;
import java.util.Optional;
@Slf4j
public class HQLMatakuliahCUDDao implements CrudRepository<MataKuliahEntity, String> {
private Session session;
public HQLMatakuliahCUDDao(Session session) {
this.session = session;
}
/**
* hanya support insert from select
* ref: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#hql-from-clause
*
* @param value
* @return
* @throws HibernateException
*/
@Override
public MataKuliahEntity save(MataKuliahEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MataKuliahEntity update(MataKuliahEntity value) throws HibernateException {
Query query = this.session
.createQuery("update MataKuliahEntity set nama = :nama, sks = :sks where id = :id");
query.setParameter("id", value.getId());
query.setParameter("nama", value.getNama());
query.setParameter("sks", value.getSks());
query.executeUpdate();
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
Query query = this.session
.createQuery("delete from MataKuliahEntity where id = :id");
query.setParameter("id", value);
int rowsUpdated = query.executeUpdate();
return rowsUpdated >= 1;
}
@Override
public Optional<MataKuliahEntity> findById(String value) throws HibernateException {
Query<MataKuliahEntity> query = this.session
.createQuery("select mt from MataKuliahEntity mt where mt.id = :id", MataKuliahEntity.class);
query.setParameter("id", value);
try {
MataKuliahEntity matakuliah = query.getSingleResult();
return matakuliah != null ? Optional.of(matakuliah) : Optional.empty();
} catch (NoResultException nre) {
log.error("data not found", nre);
return Optional.empty();
}
}
@Override
public List<MataKuliahEntity> findAll() throws HibernateException {
Query<MataKuliahEntity> query = this.session
.createQuery("select mt from MataKuliahEntity mt", MataKuliahEntity.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MataKuliahEntity;
import com.maryanto.dimas.bootcamp.example.repository.ReadRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
import java.util.Optional;
public class HQLMatakuliahReadDao implements ReadRepository<MataKuliahEntity, String> {
private Session session;
public HQLMatakuliahReadDao(Session session) {
this.session = session;
}
/**
* simple query using HQL
* @return
* @throws HibernateException
*/
@Override
public List<MataKuliahEntity> findAll() throws HibernateException {
Query<MataKuliahEntity> query = this.session
.createQuery(
"from MataKuliahEntity",
MataKuliahEntity.class);
return query.getResultList();
}
/**
* simple query using HQL with where clause index params
* @param value
* @return
* @throws HibernateException
*/
@Override
public Optional<MataKuliahEntity> findById(String value) throws HibernateException {
Query<MataKuliahEntity> query = this.session
.createQuery(
"from MataKuliahEntity where id = ?1",
MataKuliahEntity.class);
query.setParameter(1, value);
MataKuliahEntity matakuliah = query.getSingleResult();
return matakuliah != null ? Optional.of(matakuliah) : Optional.empty();
}
/**
* simple query using HQL with where clause named params
* @param nama
* @return
* @throws HibernateException
*/
public List<MataKuliahEntity> findByNamaNamedParameters(String nama) throws HibernateException {
Query<MataKuliahEntity> query = this.session
.createQuery(
"from MataKuliahEntity where nama = :namaMatakuliah",
MataKuliahEntity.class);
query.setParameter("namaMatakuliah", nama);
return query.getResultList();
}
/**
* simple query using HQL with where clause operator and
* @param nama
* @param sks
* @return
* @throws HibernateException
*/
public List<MataKuliahEntity> findByNamaAndSks(String nama, Integer sks) throws HibernateException {
Query<MataKuliahEntity> query = this.session
.createQuery(
"from MataKuliahEntity where nama = :namaMatakuliah and sks = :jumlahSks",
MataKuliahEntity.class);
query.setParameter("namaMatakuliah", nama);
query.setParameter("jumlahSks", sks);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.simple.entity.kampus.Mahasiswa;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.time.LocalDate;
import java.util.List;
public class HQLNotPredicateDao {
private Session session;
public HQLNotPredicateDao(Session session) {
this.session = session;
}
public List<Mahasiswa> findByNotActive() {
//language=HQL
String hql = "from Mahasiswa\n" +
"where not (active = true) ";
Query<Mahasiswa> query = this.session.createQuery(hql, Mahasiswa.class);
return query.getResultList();
}
public List<Mahasiswa> findByBirthDateNotIn(List<LocalDate> birthDates) {
//language=HQL
String hql = "from Mahasiswa\n" +
"where tglLahir not in (:tanggalLahir)";
Query<Mahasiswa> query = this.session.createQuery(hql, Mahasiswa.class)
.setParameterList("tanggalLahir", birthDates);
return query.getResultList();
}
public List<Mahasiswa> findByBioNotNull() {
//language=HQL
String hql = "from Mahasiswa \n" +
"where biodata is not null";
Query<Mahasiswa> query = this.session.createQuery(hql, Mahasiswa.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import java.util.List;
public class HQLNullLessPredicateDao {
private Session session;
public HQLNullLessPredicateDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> employeesWithoutManager() {
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where manager is null";
return this.session.createQuery(hql, EmployeeParentChildEntity.class).getResultList();
}
public List<EmployeeParentChildEntity> employeeHaveAManager(){
//language=HQL
String hql = "from EmployeeParentChildEntity \n" +
"where manager is not null ";
return this.session.createQuery(hql, EmployeeParentChildEntity.class).getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLOffsetAndLimitDao {
private Session session;
public HQLOffsetAndLimitDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> limit(Integer max) {
//language=HQL
String hql = "from EmployeeParentChildEntity";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class);
query.setMaxResults(max);
return query.getResultList();
}
public List<EmployeeParentChildEntity> offset(Integer offset) {
//language=HQL
String hql = "from EmployeeParentChildEntity";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class);
query.setFirstResult(offset);
return query.getResultList();
}
public List<EmployeeParentChildEntity> offsetAndLimit(Integer max, Integer offset) {
//language=HQL
String hql = "from EmployeeParentChildEntity";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class);
query.setFirstResult(offset);
query.setMaxResults(max);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLOrderingDao {
private Session session;
public HQLOrderingDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> findAllSortBySalaryAsc() {
String hql = "from EmployeeParentChildEntity \n" +
"order by salary asc";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findAllSortBySalaryDesc() {
String hql = "from EmployeeParentChildEntity \n" +
"order by salary desc";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsType;
import org.hibernate.Session;
import org.hibernate.query.Query;
import javax.persistence.NoResultException;
import java.util.Optional;
public class HQLReadOnlyEntityDao {
private Session session;
public HQLReadOnlyEntityDao(Session session) {
this.session = session;
}
public Optional<MahasiswaElementCollectionAsType> findById(Long id) {
String hql = "from MahasiswaElementCollectionAsType\n" +
"where id = :id";
try {
Query<MahasiswaElementCollectionAsType> query = this.session
.createQuery(hql, MahasiswaElementCollectionAsType.class).setParameter("id", id);
return Optional.of(query.getSingleResult());
} catch (NoResultException nre) {
return Optional.empty();
}
}
public Optional<MahasiswaElementCollectionAsType> findByIdReadOnly(Long id) {
String hql = "from MahasiswaElementCollectionAsType\n" +
"where id = :id";
try {
Query<MahasiswaElementCollectionAsType> query = this.session
.createQuery(hql, MahasiswaElementCollectionAsType.class)
.setParameter("id", id)
.setReadOnly(true);
return Optional.of(query.getSingleResult());
} catch (NoResultException nre) {
return Optional.empty();
}
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilSingleTableEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLRelationalComparisonBooleanDao {
private Session session;
public HQLRelationalComparisonBooleanDao(Session session) {
this.session = session;
}
public List<MobilSingleTableEntity> findEqualByStatusAllWheelDrive(Boolean status) {
//language=HQL
String hql = "from MobilSingleTableEntity where allWheelDrive = :status";
Query<MobilSingleTableEntity> query = this.session.createQuery(hql, MobilSingleTableEntity.class)
.setParameter("status", status);
return query.getResultList();
}
public List<MobilSingleTableEntity> findNegationByStatusAllWheelDrive(Boolean status) {
//language=HQL
String hql = "from MobilSingleTableEntity where allWheelDrive != :status";
Query<MobilSingleTableEntity> query = this.session.createQuery(hql, MobilSingleTableEntity.class)
.setParameter("status", status);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.time.LocalDate;
import java.util.List;
public class HQLRelationalComparisonDateAndTimeDao {
private Session session;
public HQLRelationalComparisonDateAndTimeDao(Session session) {
this.session = session;
}
public List<MahasiswaOneToOneEntity> findEqualByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir = :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findNotSameByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir != :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findNotEqualByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir <> :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findHigherByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir > :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findHigherThanByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir >= :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findLowerByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir < :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
public List<MahasiswaOneToOneEntity> findLowerThanByTanggalLahir(LocalDate tanggalLahir) {
//language=HQL
String hql = "from MahasiswaOneToOneEntity where tanggalLahir <= :tanggalLahir";
Query<MahasiswaOneToOneEntity> query = this.session.createQuery(hql, MahasiswaOneToOneEntity.class)
.setParameter("tanggalLahir", tanggalLahir);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumOrdinal;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLRelationalComparisonEnumDao {
private Session session;
public HQLRelationalComparisonEnumDao(Session session) {
this.session = session;
}
public List<EmployeeEnumOrdinal> findEqualByEmployeeStatus(EmployeeStatus status) {
//language=HQL
String hql = "from EmployeeEnumOrdinal where status = :status";
Query<EmployeeEnumOrdinal> query = this.session.createQuery(hql, EmployeeEnumOrdinal.class)
.setParameter("status", status);
return query.getResultList();
}
public List<EmployeeEnumOrdinal> findNotSameByEmployeeStatus(EmployeeStatus status) {
//language=HQL
String hql = "from EmployeeEnumOrdinal where status != :status";
Query<EmployeeEnumOrdinal> query = this.session.createQuery(hql, EmployeeEnumOrdinal.class)
.setParameter("status", status);
return query.getResultList();
}
public List<EmployeeEnumOrdinal> findNotEqualByEmployeeStatus(EmployeeStatus status) {
//language=HQL
String hql = "from EmployeeEnumOrdinal where status <> :status";
Query<EmployeeEnumOrdinal> query = this.session.createQuery(hql, EmployeeEnumOrdinal.class)
.setParameter("status", status);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLRelationalComparisonNumberDao {
private Session session;
public HQLRelationalComparisonNumberDao(Session session) {
this.session = session;
}
public List<KelasEntity> findEqualByTahunAngkatan(Integer angkatan) {
//language=HQL
String hql = "from KelasEntity where angkatan = :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
public List<KelasEntity> findNotSameByTahunAngkatan(Integer angkatan) {
String hql = "from KelasEntity where angkatan != :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
public List<KelasEntity> findNotEqualByTahunAngkatan(Integer angkatan) {
String hql = "from KelasEntity where angkatan <> :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
public List<KelasEntity> findHigherByTahunAngkatan(Integer angkatan) {
String hql = "from KelasEntity where angkatan > :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
public List<KelasEntity> findHigherThenByTahunAngkatan(Integer angkatan) {
String hql = "from KelasEntity where angkatan >= :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
public List<KelasEntity> findLowerByTahunAngkatan(Integer angkatan) {
String hql = "from KelasEntity where angkatan < :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
public List<KelasEntity> findLowerThanByTahunAngkatan(Integer angkatan) {
String hql = "from KelasEntity where angkatan <= :angkatan";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class);
return query.setParameter("angkatan", angkatan)
.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLRelationalComparisonStringDao {
private Session session;
public HQLRelationalComparisonStringDao(Session session) {
this.session = session;
}
public List<KelasEntity> findEqualBy(String namaKelas) {
//language=HQL
String hql = "from KelasEntity where nama = :namaKelas";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class)
.setParameter("namaKelas", namaKelas);
return query.getResultList();
}
public List<KelasEntity> findNotEqualBy(String namaKelas) {
//language=HQL
String hql = "from KelasEntity where nama <> :namaKelas";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class)
.setParameter("namaKelas", namaKelas);
return query.getResultList();
}
public List<KelasEntity> findNotSameBy(String namaKelas) {
//language=HQL
String hql = "from KelasEntity where nama != :namaKelas";
Query<KelasEntity> query = this.session.createQuery(hql, KelasEntity.class)
.setParameter("namaKelas", namaKelas);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.query.hql.dao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.List;
public class HQLSubQueryQualifierDao {
private Session session;
public HQLSubQueryQualifierDao(Session session) {
this.session = session;
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryInEmployeeJob(String jobName){
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary in (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryLowerAllByAvgSalary(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary > ALL (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryEqualAllByAvgSalary(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary = ALL (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryHigherAllByAvgSalary(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary > ALL (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryEqualAnyByEmployeeJob(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary = ANY (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryEqualSomeByEmployeeJob(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary = SOME (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryHigherAnyByEmployeeJob(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary > ANY (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryHigherSomeByEmployeeJob(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary > SOME (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryLowerAnyByEmployeeJob(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary < ANY (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
public List<EmployeeParentChildEntity> findEmployeesWhenSalaryLowerSomeByEmployeeJob(String jobName) {
//language=HQL
String hql = "from EmployeeParentChildEntity emp\n" +
"where emp.salary < SOME (\n" +
" select emp_sub.salary \n" +
" from EmployeeParentChildEntity emp_sub \n" +
" where emp_sub.job = :jobName\n" +
")";
Query<EmployeeParentChildEntity> query = this.session.createQuery(hql, EmployeeParentChildEntity.class)
.setParameter("jobName", jobName);
return query.getResultList();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.*;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "kelas", schema = "mapping")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@ToString(exclude = {"listMahasiswa"})
public class KelasEntity {
@Id
@Column(name = "id")
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nama_kelas", nullable = false)
private String nama;
@Column(name = "tahun_angkatan", nullable = false)
private Integer angkatan;
@Column(name = "program_studi")
private String programStudi;
@OneToMany(mappedBy = "kelas")
private List<MahasiswaManyToOneEntity> listMahasiswa = new ArrayList<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class KelasEntityDao implements CrudRepository<KelasEntity, String> {
private Session session;
public KelasEntityDao(Session session) {
this.session = session;
}
@Override
public KelasEntity save(KelasEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public KelasEntity update(KelasEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<KelasEntity> findById(String value) throws HibernateException {
KelasEntity kelas = this.session.find(KelasEntity.class, value);
return kelas != null ? Optional.of(kelas) : Optional.empty();
}
@Override
public List<KelasEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanJoinTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilJoinTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorJoinTableEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class KendaraanJoinTableDao implements CrudRepository<KendaraanJoinTableEntity, String> {
private Session session;
public KendaraanJoinTableDao(Session session) {
this.session = session;
}
@Override
public KendaraanJoinTableEntity save(KendaraanJoinTableEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public KendaraanJoinTableEntity update(KendaraanJoinTableEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<KendaraanJoinTableEntity> findById(String value) throws HibernateException {
KendaraanJoinTableEntity kendaraan = this.session.find(KendaraanJoinTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MobilJoinTableEntity> findByMobilId(String value) throws HibernateException {
MobilJoinTableEntity kendaraan = this.session.find(MobilJoinTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MotorJoinTableEntity> findByMotorId(String value) throws HibernateException {
MotorJoinTableEntity kendaraan = this.session.find(MotorJoinTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
@Override
public List<KendaraanJoinTableEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@Entity
@Table(name = "kendaraan_jointable", schema = "inherintance")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@Inheritance(strategy = InheritanceType.JOINED)
public class KendaraanJoinTableEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nama", length = 50)
private String nama;
@Column(name = "jumlah_roda", length = 2)
private Integer jumlahRoda;
@Column(name = "jumlah_cylinder", length = 3)
private Integer jumlahCylinder;
@Column(name = "cc", length = 4)
private Integer cc;
@Column(name = "nama_pabrikan", nullable = false, length = 50)
private String namaPabrikan;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@MappedSuperclass
public class KendaraanMappedSuperclass {
@Column(name = "nama", length = 50)
private String nama;
@Column(name = "jumlah_roda", length = 2)
private Integer jumlahRoda;
@Column(name = "jumlah_cylinder", length = 3)
private Integer jumlahCylinder;
@Column(name = "cc", length = 4)
private Integer cc;
@Column(name = "nama_pabrikan", nullable = false, length = 50)
private String namaPabrikan;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.*;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanSeparateTableEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class KendaraanSeparateTableDao implements CrudRepository<KendaraanSeparateTableEntity, String> {
private Session session;
public KendaraanSeparateTableDao(Session session) {
this.session = session;
}
@Override
public KendaraanSeparateTableEntity save(KendaraanSeparateTableEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public KendaraanSeparateTableEntity update(KendaraanSeparateTableEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<KendaraanSeparateTableEntity> findById(String value) throws HibernateException {
KendaraanSeparateTableEntity kendaraan = this.session.find(KendaraanSeparateTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MobilSeparateTableEntity> findByMobilId(String value) throws HibernateException {
MobilSeparateTableEntity kendaraan = this.session.find(MobilSeparateTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MotorSeparateTableEntity> findByMotorId(String value) throws HibernateException {
MotorSeparateTableEntity kendaraan = this.session.find(MotorSeparateTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
@Override
public List<KendaraanSeparateTableEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@Entity
@Table(name = "kendaraan_tableperclass", schema = "inherintance")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class KendaraanSeparateTableEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nama", length = 50)
private String nama;
@Column(name = "jumlah_roda", length = 2)
private Integer jumlahRoda;
@Column(name = "jumlah_cylinder", length = 3)
private Integer jumlahCylinder;
@Column(name = "cc", length = 4)
private Integer cc;
@Column(name = "nama_pabrikan", nullable = false, length = 50)
private String namaPabrikan;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanSingleTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilSingleTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorSingleTableEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class KendaraanSingleTableDao implements CrudRepository<KendaraanSingleTableEntity, String> {
private Session session;
public KendaraanSingleTableDao(Session session) {
this.session = session;
}
@Override
public KendaraanSingleTableEntity save(KendaraanSingleTableEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public KendaraanSingleTableEntity update(KendaraanSingleTableEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<KendaraanSingleTableEntity> findById(String value) throws HibernateException {
KendaraanSingleTableEntity kendaraan = this.session.find(KendaraanSingleTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MobilSingleTableEntity> findByMobilId(String value) throws HibernateException {
MobilSingleTableEntity kendaraan = this.session.find(MobilSingleTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MotorSingleTableEntity> findByMotorId(String value) throws HibernateException {
MotorSingleTableEntity kendaraan = this.session.find(MotorSingleTableEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
@Override
public List<KendaraanSingleTableEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.*;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanSingleTableDiscriminatorEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class KendaraanSingleTableDiscriminatorDao implements CrudRepository<KendaraanSingleTableDiscriminatorEntity, String> {
private Session session;
public KendaraanSingleTableDiscriminatorDao(Session session) {
this.session = session;
}
@Override
public KendaraanSingleTableDiscriminatorEntity save(KendaraanSingleTableDiscriminatorEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public KendaraanSingleTableDiscriminatorEntity update(KendaraanSingleTableDiscriminatorEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<KendaraanSingleTableDiscriminatorEntity> findById(String value) throws HibernateException {
KendaraanSingleTableDiscriminatorEntity kendaraan = this.session.find(KendaraanSingleTableDiscriminatorEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MobilSingleTableDiscriminatorEntity> findByMobilId(String value) throws HibernateException {
MobilSingleTableDiscriminatorEntity kendaraan = this.session.find(MobilSingleTableDiscriminatorEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
public Optional<MotorSingleTableDiscriminatorEntity> findByMotorId(String value) throws HibernateException {
MotorSingleTableDiscriminatorEntity kendaraan = this.session.find(MotorSingleTableDiscriminatorEntity.class, value);
return kendaraan != null ? Optional.of(kendaraan) : Optional.empty();
}
@Override
public List<KendaraanSingleTableDiscriminatorEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@Entity
@Table(name = "kendaraan_singletable_discriminator", schema = "inherintance")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name = "jenis_kendaraan",
discriminatorType = DiscriminatorType.STRING,
length = 50)
public class KendaraanSingleTableDiscriminatorEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nama", length = 50)
private String nama;
@Column(name = "jumlah_roda", length = 2)
private Integer jumlahRoda;
@Column(name = "jumlah_cylinder", length = 3)
private Integer jumlahCylinder;
@Column(name = "cc", length = 4)
private Integer cc;
@Column(name = "nama_pabrikan", nullable = false, length = 50)
private String namaPabrikan;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@Entity
@Table(name = "kendaraan_singletable", schema = "inherintance")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class KendaraanSingleTableEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nama", length = 50)
private String nama;
@Column(name = "jumlah_roda", length = 2)
private Integer jumlahRoda;
@Column(name = "jumlah_cylinder", length = 3)
private Integer jumlahCylinder;
@Column(name = "cc", length = 4)
private Integer cc;
@Column(name = "nama_pabrikan", nullable = false, length = 50)
private String namaPabrikan;
}
package com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
@Embeddable
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class KeyClassRoomEmbeddedId implements Serializable {
@Column(name = "tahun_angkatan", length = 4, columnDefinition = "int check(tahun_angkatan >= 1999)")
private Integer year;
@Column(name = "class_id")
private String classId;
}
package com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KeyClassRoomIdClass implements Serializable {
private Integer year;
private String classId;
}
package com.maryanto.dimas.bootcamp.example.simple.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "mahasiswa", schema = "master")
public class Mahasiswa {
@Id
private Long kode;
@Column(name = "nim_mahasiswa", nullable = false, unique = true, length = 8)
private String nim;
@Column(name = "nama_mahasiswa", nullable = false, length = 25)
private String nama;
@Column(name = "tahun_masuk", length = 4)
private Integer thnMasuk;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tglLahir;
@Column(name = "created_date", nullable = false)
private LocalDateTime createdDate;
@Column(name = "created_by")
private String createdBy;
@Column(name = "is_active")
private Boolean active;
@Type(type = "text")
@Column(name = "bio")
private String biodata;
}
package com.maryanto.dimas.bootcamp.example.simple.dao.kampus;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import com.maryanto.dimas.bootcamp.example.simple.entity.Mahasiswa;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaDao implements CrudRepository<Mahasiswa, Long> {
private Session session;
public MahasiswaDao(Session session) {
this.session = session;
}
@Override
public Mahasiswa save(Mahasiswa value) throws HibernateException {
Long pk = (Long) this.session.save(value);
value.setKode(pk);
return value;
}
@Override
public Mahasiswa update(Mahasiswa value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
public boolean remove(Mahasiswa value) throws HibernateException {
this.session.remove(value);
return true;
}
@Override
public Optional<Mahasiswa> findById(Long value) throws HibernateException {
Mahasiswa mhs = this.session.find(Mahasiswa.class, value);
return mhs != null ? Optional.of(mhs) : Optional.empty();
}
@Override
public List<Mahasiswa> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.entity;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "mahasiswa_listastype", schema = "collections")
public class MahasiswaElementCollectionAsType {
@Id
@GeneratedValue
private Long id;
@Column(name = "nim")
private String nim;
@Column(name = "nama", nullable = false)
private String name;
@ElementCollection
@CollectionTable(
name = "mahasiswa_address",
schema = "collections",
joinColumns = @JoinColumn(name = "mahasiswa_id", nullable = false),
foreignKey = @ForeignKey(name = "fk_address_mahasiswa_id")
)
@EqualsAndHashCode.Exclude
@FieldNameConstants.Exclude
@ToString.Exclude
private List<AlamatEmbeddable> addresses = new ArrayList<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.dao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsType;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaElementCollectionAsTypeDao implements CrudRepository<MahasiswaElementCollectionAsType, Long> {
private Session session;
public MahasiswaElementCollectionAsTypeDao(Session session) {
this.session = session;
}
@Override
public MahasiswaElementCollectionAsType save(MahasiswaElementCollectionAsType value) throws HibernateException {
Long returnKey = (Long) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaElementCollectionAsType update(MahasiswaElementCollectionAsType value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaElementCollectionAsType> findById(Long value) throws HibernateException {
MahasiswaElementCollectionAsType mahasiswa = this.session.find(MahasiswaElementCollectionAsType.class, value);
return mahasiswa != null ? Optional.of(mahasiswa) : Optional.empty();
}
@Override
public List<MahasiswaElementCollectionAsType> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.entity;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "mahasiswa_listasvalue", schema = "collections")
public class MahasiswaElementCollectionAsValue {
@Id
@GeneratedValue
private Long id;
@Column(name = "nim")
private String nim;
@Column(name = "nama", nullable = false)
private String name;
@Column(name = "alamat", nullable = false)
private String address;
@ElementCollection
@Column(name = "hobi")
@CollectionTable(
name = "mahasiswa_hoby",
schema = "collections",
foreignKey = @ForeignKey(name = "fk_hobi_mahasiswa_id"),
joinColumns = @JoinColumn(name = "mahasiswa_id", nullable = false)
)
@ToString.Exclude
@EqualsAndHashCode.Exclude
@FieldNameConstants.Exclude
private List<String> hobies = new ArrayList<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.dao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsValue;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaElementCollectionAsValueDao implements CrudRepository<MahasiswaElementCollectionAsValue, Long> {
private Session session;
public MahasiswaElementCollectionAsValueDao(Session session) {
this.session = session;
}
@Override
public MahasiswaElementCollectionAsValue save(MahasiswaElementCollectionAsValue value) throws HibernateException {
Long returnKey = (Long) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaElementCollectionAsValue update(MahasiswaElementCollectionAsValue value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaElementCollectionAsValue> findById(Long value) throws HibernateException {
MahasiswaElementCollectionAsValue mahasiswa = this.session.find(MahasiswaElementCollectionAsValue.class, value);
return mahasiswa != null ? Optional.of(mahasiswa) : Optional.empty();
}
@Override
public List<MahasiswaElementCollectionAsValue> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "mahasiswa_embedded", schema = "embedded")
public class MahasiswaEmbedded {
@Id
@GeneratedValue
private Long id;
@Column(name = "nim", length = 8, nullable = false, unique = true)
private String nim;
@Column(name = "nama", length = 50, nullable = false)
private String nama;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tanggalLahir;
@Column(name = "tahun_masuk", length = 4, nullable = false)
private Integer tahunMasuk;
@Embedded
private AlamatEmbeddable alamat;
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.dao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaEmbedded;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaEmbeddedDao implements CrudRepository<MahasiswaEmbedded, Long> {
private Session session;
public MahasiswaEmbeddedDao(Session session) {
this.session = session;
}
@Override
public MahasiswaEmbedded save(MahasiswaEmbedded value) throws HibernateException {
Long returnKey = (Long) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaEmbedded update(MahasiswaEmbedded value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaEmbedded> findById(Long value) throws HibernateException {
MahasiswaEmbedded msh = this.session.find(MahasiswaEmbedded.class, value);
return msh != null ? Optional.of(msh) : Optional.empty();
}
@Override
public List<MahasiswaEmbedded> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "mahasiswa_override_att", schema = "embedded")
public class MahasiswaEmbeddedOverrideAttributes {
@Id
@GeneratedValue
private Long id;
@Column(name = "nim", length = 8, nullable = false, unique = true)
private String nim;
@Column(name = "nama", length = 50, nullable = false)
private String nama;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tanggalLahir;
@Column(name = "tahun_masuk", length = 4, nullable = false)
private Integer tahunMasuk;
@Embedded
@AttributeOverrides(value = {
@AttributeOverride(name = "provinsi",
column = @Column(name = "rumah_provinsi", length = 50, nullable = false)),
@AttributeOverride(name = "kota",
column = @Column(name = "rumah_kota", length = 50, nullable = false)),
@AttributeOverride(name = "kelurahan",
column = @Column(name = "rumah_kelurahan", length = 100, nullable = false)),
@AttributeOverride(name = "kecamatan",
column = @Column(name = "rumah_kecamatan", length = 100, nullable = false)),
@AttributeOverride(name = "rw",
column = @Column(name = "rumah_rw", length = 3, nullable = false)),
@AttributeOverride(name = "rt",
column = @Column(name = "rumah_rt", length = 3, nullable = false)),
@AttributeOverride(name = "kodePos",
column = @Column(name = "rumah_kode_pos", length = 6, nullable = false)),
@AttributeOverride(name = "namaJalan",
column = @Column(name = "rumah_jalan", length = 100)),
})
private AlamatEmbeddable alamatRumah;
@Embedded
@AttributeOverrides(value = {
@AttributeOverride(name = "provinsi",
column = @Column(name = "ortu_provinsi", length = 50)),
@AttributeOverride(name = "kota",
column = @Column(name = "ortu_kota", length = 50)),
@AttributeOverride(name = "kelurahan",
column = @Column(name = "ortu_kelurahan", length = 100)),
@AttributeOverride(name = "kecamatan",
column = @Column(name = "ortu_kecamatan", length = 100)),
@AttributeOverride(name = "rw",
column = @Column(name = "ortu_rw", length = 3)),
@AttributeOverride(name = "rt",
column = @Column(name = "ortu_rt", length = 3)),
@AttributeOverride(name = "kodePos",
column = @Column(name = "ortu_kode_pos", length = 6)),
@AttributeOverride(name = "namaJalan",
column = @Column(name = "ortu_jalan", length = 100)),
})
private AlamatEmbeddable alamatOrangTua;
}
package com.maryanto.dimas.bootcamp.example.mapping.embedded.dao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaEmbeddedOverrideAttributes;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaEmbeddedOverrideAttributesDao implements CrudRepository<MahasiswaEmbeddedOverrideAttributes, Long> {
private Session session;
public MahasiswaEmbeddedOverrideAttributesDao(Session session) {
this.session = session;
}
@Override
public MahasiswaEmbeddedOverrideAttributes save(MahasiswaEmbeddedOverrideAttributes value) throws HibernateException {
Long returnKey = (Long) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaEmbeddedOverrideAttributes update(MahasiswaEmbeddedOverrideAttributes value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(Long value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaEmbeddedOverrideAttributes> findById(Long value) throws HibernateException {
MahasiswaEmbeddedOverrideAttributes mhs = this.session.find(MahasiswaEmbeddedOverrideAttributes.class, value);
return mhs != null ? Optional.of(mhs) : Optional.empty();
}
@Override
public List<MahasiswaEmbeddedOverrideAttributes> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "mahasiswa_manytomany", schema = "mapping")
public class MahasiswaManyToManyEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nim", length = 8, nullable = false, unique = true)
private String nim;
@Column(name = "nama", length = 50, nullable = false)
private String nama;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tanggalLahir;
@Column(name = "tahun_masuk", length = 4, nullable = false)
private Integer tahunMasuk;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "mahasiswa_matakuliah_list", schema = "mapping",
joinColumns = @JoinColumn(name = "mahasiswa_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "matakuliah_id", nullable = false),
foreignKey = @ForeignKey(name = "fk_msh_kuliah_mahasiswa_id"),
inverseForeignKey = @ForeignKey(name = "fk_msh_kuliah_matakuliah_id")
)
@ToString.Exclude
@EqualsAndHashCode.Exclude
@FieldNameConstants.Exclude
private Set<MataKuliahEntity> listMatakuliah = new HashSet<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaManyToManyEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaManyToManyEntityDao implements CrudRepository<MahasiswaManyToManyEntity, String> {
private Session session;
public MahasiswaManyToManyEntityDao(Session session) {
this.session = session;
}
@Override
public MahasiswaManyToManyEntity save(MahasiswaManyToManyEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaManyToManyEntity update(MahasiswaManyToManyEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaManyToManyEntity> findById(String value) throws HibernateException {
MahasiswaManyToManyEntity msh = this.session.find(MahasiswaManyToManyEntity.class, value);
return msh != null ? Optional.of(msh) : Optional.empty();
}
@Override
public List<MahasiswaManyToManyEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "mahasiswa_manytoone", schema = "mapping")
public class MahasiswaManyToOneEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nim", length = 8, nullable = false, unique = true)
private String nim;
@Column(name = "nama", length = 50, nullable = false)
private String nama;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tanggalLahir;
@Column(name = "tahun_masuk", length = 4, nullable = false)
private Integer tahunMasuk;
@ManyToOne
@JoinColumn(name = "kelas_id", nullable = false)
private KelasEntity kelas;
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaManyToOneEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaManyToOneEntityDao implements CrudRepository<MahasiswaManyToOneEntity, String> {
private Session session;
public MahasiswaManyToOneEntityDao(Session session) {
this.session = session;
}
@Override
public MahasiswaManyToOneEntity save(MahasiswaManyToOneEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaManyToOneEntity update(MahasiswaManyToOneEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaManyToOneEntity> findById(String value) throws HibernateException {
MahasiswaManyToOneEntity msh = this.session.find(MahasiswaManyToOneEntity.class, value);
return msh != null ? Optional.of(msh) : Optional.empty();
}
@Override
public List<MahasiswaManyToOneEntity> findAll() throws HibernateException {
return null;
}
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.*;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "mahasiswa_onetomany", schema = "mapping")
@ToString(exclude = {"listAlamat"})
public class MahasiswaOneToManyEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nim", length = 8, nullable = false, unique = true)
private String nim;
@Column(name = "nama", length = 50, nullable = false)
private String nama;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tanggalLahir;
@Column(name = "tahun_masuk", length = 4, nullable = false)
private Integer tahunMasuk;
@OneToMany
@JoinTable(
name = "mahasiswa_alamat_list",
schema = "mapping",
joinColumns = @JoinColumn(name = "mahasiswa_id", nullable = false),
foreignKey = @ForeignKey(name = "fk_mahasiswa_id"),
inverseJoinColumns = @JoinColumn(name = "alamat_id", nullable = false),
inverseForeignKey = @ForeignKey(name = "fk_alamat_id")
)
private List<AlamatEntity> listAlamat = new ArrayList<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToManyEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaOneToManyEntityDao implements CrudRepository<MahasiswaOneToManyEntity, String> {
private Session session;
public MahasiswaOneToManyEntityDao(Session session) {
this.session = session;
}
@Override
public MahasiswaOneToManyEntity save(MahasiswaOneToManyEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaOneToManyEntity update(MahasiswaOneToManyEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaOneToManyEntity> findById(String value) throws HibernateException {
MahasiswaOneToManyEntity msh = this.session.find(MahasiswaOneToManyEntity.class, value);
return msh != null ? Optional.of(msh) : Optional.empty();
}
@Override
public List<MahasiswaOneToManyEntity> findAll() throws HibernateException {
return null;
}
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "mahasiswa_onetoone", schema = "mapping")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
public class MahasiswaOneToOneEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
private String id;
@Column(name = "nim", length = 8, nullable = false, unique = true)
private String nim;
@Column(name = "nama", length = 50, nullable = false)
private String nama;
@Column(name = "tanggal_lahir", nullable = false)
private LocalDate tanggalLahir;
@Column(name = "tahun_masuk", length = 4, nullable = false)
private Integer tahunMasuk;
@OneToOne
@JoinColumn(name = "alamat")
private AlamatEntity alamat;
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MahasiswaOneToOneEntityDao implements CrudRepository<MahasiswaOneToOneEntity, String> {
private Session session;
public MahasiswaOneToOneEntityDao(Session session) {
this.session = session;
}
@Override
public MahasiswaOneToOneEntity save(MahasiswaOneToOneEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MahasiswaOneToOneEntity update(MahasiswaOneToOneEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MahasiswaOneToOneEntity> findById(String value) throws HibernateException {
MahasiswaOneToOneEntity msh = this.session.find(MahasiswaOneToOneEntity.class, value);
return msh!=null ? Optional.of(msh): Optional.empty();
}
@Override
public List<MahasiswaOneToOneEntity> findAll() throws HibernateException {
return null;
}
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.entity;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "matakuliah", schema = "mapping")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
public class MataKuliahEntity {
@Id
@GeneratedValue(generator = "uuid_gen")
@Column(name = "id")
private String id;
@Column(name = "nama_kuliah")
private String nama;
@Column(name = "jumlah_sks")
private Integer sks;
@ManyToMany(mappedBy = "listMatakuliah")
@ToString.Exclude
@EqualsAndHashCode.Exclude
@FieldNameConstants.Exclude
private Set<MahasiswaManyToManyEntity> listMahasiswa = new HashSet<>();
}
package com.maryanto.dimas.bootcamp.example.mapping.jointable.dao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MataKuliahEntity;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MataKuliahEntityDao implements CrudRepository<MataKuliahEntity, String> {
private Session session;
public MataKuliahEntityDao(Session session) {
this.session = session;
}
@Override
public MataKuliahEntity save(MataKuliahEntity value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MataKuliahEntity update(MataKuliahEntity value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MataKuliahEntity> findById(String value) throws HibernateException {
MataKuliahEntity msh = this.session.find(MataKuliahEntity.class, value);
return msh != null ? Optional.of(msh) : Optional.empty();
}
@Override
public List<MataKuliahEntity> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.*;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "mobil_jointable", schema = "inherintance")
@PrimaryKeyJoinColumn(
name = "kendaraan_id",
foreignKey = @ForeignKey(name = "fk_kendaraan_mobil_id")
)
public class MobilJoinTableEntity extends KendaraanJoinTableEntity {
@Column(name = "jumlah_kursi", length = 1)
private Integer jumlahKursi;
@Column(name = "is_all_wheel_drive")
private boolean allWheelDrive;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "mobil_mappedsuperclass", schema = "inherintance")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
public class MobilMappedSuperclass extends KendaraanMappedSuperclass {
@Id
@GeneratedValue(generator = "uuid_gen")
@Column(name = "id", length = 64)
private String id;
@Column(name = "jumlah_kursi", length = 1)
private Integer jumlahKursi;
@Column(name = "is_all_wheel_drive", nullable = false)
private boolean allWheelDrive;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilMappedSuperclass;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MobilMappedSuperClassDao implements CrudRepository<MobilMappedSuperclass, String> {
private Session session;
public MobilMappedSuperClassDao(Session session) {
this.session = session;
}
@Override
public MobilMappedSuperclass save(MobilMappedSuperclass value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MobilMappedSuperclass update(MobilMappedSuperclass value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MobilMappedSuperclass> findById(String value) throws HibernateException {
MobilMappedSuperclass mobil = this.session.find(MobilMappedSuperclass.class, value);
return mobil != null ? Optional.of(mobil) : Optional.empty();
}
@Override
public List<MobilMappedSuperclass> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "mobil_tableperclass", schema = "inherintance")
public class MobilSeparateTableEntity extends KendaraanSeparateTableEntity {
@Column(name = "jumlah_kursi", length = 1)
private Integer jumlahKursi;
@Column(name = "is_all_wheel_drive")
private boolean allWheelDrive;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@DiscriminatorValue(value = "Mobil")
public class MobilSingleTableDiscriminatorEntity extends KendaraanSingleTableDiscriminatorEntity {
@Column(name = "jumlah_kursi", length = 1)
private Integer jumlahKursi;
@Column(name = "is_all_wheel_drive")
private boolean allWheelDrive;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
public class MobilSingleTableEntity extends KendaraanSingleTableEntity {
@Column(name = "jumlah_kursi", length = 1)
private Integer jumlahKursi;
@Column(name = "is_all_wheel_drive")
private boolean allWheelDrive;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.*;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "motor_jointable", schema = "inherintance")
@PrimaryKeyJoinColumn(
name = "kendaraan_id",
foreignKey = @ForeignKey(name = "fk_kendaraan_motor_id")
)
public class MotorJoinTableEntity extends KendaraanJoinTableEntity {
@Column(name = "jenis_rantai")
private String jenisRantai;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "motor_mappedsuperclass", schema = "inherintance")
@GenericGenerator(name = "uuid_gen", strategy = "uuid2")
public class MotorMappedSuperClass extends KendaraanMappedSuperclass {
@Id
@GeneratedValue(generator = "uuid_gen")
@Column(name = "id", length = 64)
private String id;
@Column(name = "jenis_rantai")
private String jenisRantai;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorMappedSuperClass;
import com.maryanto.dimas.bootcamp.example.repository.CrudRepository;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import java.util.List;
import java.util.Optional;
public class MotorMappedSuperClassDao implements CrudRepository<MotorMappedSuperClass, String> {
private Session session;
public MotorMappedSuperClassDao(Session session) {
this.session = session;
}
@Override
public MotorMappedSuperClass save(MotorMappedSuperClass value) throws HibernateException {
String returnKey = (String) this.session.save(value);
value.setId(returnKey);
return value;
}
@Override
public MotorMappedSuperClass update(MotorMappedSuperClass value) throws HibernateException {
this.session.update(value);
return value;
}
@Override
public boolean removeById(String value) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Optional<MotorMappedSuperClass> findById(String value) throws HibernateException {
MotorMappedSuperClass motor = this.session.find(MotorMappedSuperClass.class, value);
return motor != null ? Optional.of(motor) : Optional.empty();
}
@Override
public List<MotorMappedSuperClass> findAll() throws HibernateException {
throw new UnsupportedOperationException();
}
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@Table(name = "motor_tableperclass", schema = "inherintance")
public class MotorSeparateTableEntity extends KendaraanSeparateTableEntity {
@Column(name = "jenis_rantai")
private String jenisRantai;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
@DiscriminatorValue(value = "Motor")
public class MotorSingleTableDiscriminatorEntity extends KendaraanSingleTableDiscriminatorEntity {
@Column(name = "jenis_rantai")
private String jenisRantai;
}
package com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity;
import lombok.*;
import lombok.experimental.SuperBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
@Data
@ToString(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Entity
public class MotorSingleTableEntity extends KendaraanSingleTableEntity {
@Column(name = "jenis_rantai")
private String jenisRantai;
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maryanto.dimas.bootcamp.example</groupId>
<artifactId>hibernate-core-example</artifactId>
<version>2020.11.01-release</version>
<packaging>jar</packaging>
<name>hibernate-core-example</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hibernate.version>5.4.22.Final</hibernate.version>
</properties>
<dependencies>
<!-- enabled setter & getter method automaticly generated -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<!-- enabled logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<!-- jdbc driver for postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12.jre7</version>
<scope>runtime</scope>
</dependency>
<!-- database pooling connection -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.2</version>
</dependency>
<!-- hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>6.3.3</version>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12.jre7</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
<!-- other plugins -->
</plugins>
</build>
</project>
package com.maryanto.dimas.bootcamp.example.repository;
import java.util.List;
import java.util.Optional;
public interface ReadRepository<T, PK> {
Optional<T> findById(PK value);
List<T> findAll();
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassWIthCheckDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithCheckConstraints;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.UUID;
@Slf4j
public class TestClassWIthCheckConstraint extends TestCase {
private Session session;
private ClassWIthCheckDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassWIthCheckDao(session);
}
@Test
public void testInsertValid() {
ClassWithCheckConstraints check = new ClassWithCheckConstraints();
check.setId(UUID.randomUUID().toString());
check.setName("IPS 2");
check.setYear(2001);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.session.beginTransaction();
this.dao.save(check);
this.session.getTransaction().commit();
}
@Test
public void testInsertInValid() {
ClassWithCheckConstraints check = new ClassWithCheckConstraints();
check.setId(UUID.randomUUID().toString());
check.setName("IPS 1");
check.setYear(1993);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.session.beginTransaction();
this.dao.save(check);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassWIthSequanceGeneratorDao;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassWIthSequanceGeneratorDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithSequanceGenerator;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithSequanceGenerator;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.UUID;
@Slf4j
public class TestClassWIthSequanceGenerator extends TestCase {
private Session session;
private ClassWIthSequanceGeneratorDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassWIthSequanceGeneratorDao(session);
}
@Test
public void testInsertValid() {
ClassWithSequanceGenerator check = new ClassWithSequanceGenerator();
// check.setId(null); // TODO set to null
check.setName("IPS 2");
check.setYear(2001);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.session.beginTransaction();
check = this.dao.save(check);
log.info("inserted value: {}", check);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassWIthCheckDao;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassWIthUniqueDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithCheckConstraints;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithUniqueConstraints;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDateTime;
import java.util.UUID;
@Slf4j
public class TestClassWIthUniqueConstraint extends TestCase {
private Session session;
private ClassWIthUniqueDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassWIthUniqueDao(session);
}
@Test
public void testInsertValid() {
ClassWithUniqueConstraints check = new ClassWithUniqueConstraints();
check.setId(UUID.randomUUID().toString());
check.setName("IPS 2");
check.setYear(2001);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.session.beginTransaction();
this.dao.save(check);
this.session.getTransaction().commit();
}
@Test
public void testInsertInValid() {
this.session.beginTransaction();
ClassWithUniqueConstraints check = new ClassWithUniqueConstraints();
check.setId(UUID.randomUUID().toString());
check.setName("IPS 1");
check.setYear(1993);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.dao.save(check);
check = new ClassWithUniqueConstraints();
check.setId(UUID.randomUUID().toString());
check.setName("IPS 1");
check.setYear(1993);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.dao.save(check);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassWIthUuidGeneratorDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.ClassWithUuidGenerator;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDateTime;
@Slf4j
public class TestClassWIthUuidGenerator extends TestCase {
private Session session;
private ClassWIthUuidGeneratorDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassWIthUuidGeneratorDao(session);
}
@Test
public void testInsertValid() {
ClassWithUuidGenerator check = new ClassWithUuidGenerator();
// check.setId(null); // TODO set to null
check.setName("IPS 2");
check.setYear(2001);
check.setCreatedBy("admin");
check.setCreatedDateTime(LocalDateTime.now());
this.session.beginTransaction();
check = this.dao.save(check);
log.info("inserted value: {}", check);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.entity.Mahasiswa;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Slf4j
public class TestDeleteMahasiswa extends TestCase {
private Session session;
private MahasiswaDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new MahasiswaDao(session);
}
@Test
public void testDeleteMahasiswa() {
this.session.beginTransaction();
Mahasiswa mahasiswa = this.session.get(Mahasiswa.class, 1L);
this.dao.remove(mahasiswa);
// commit
this.session.getTransaction().commit();
log.info("mahasiswa was delete: {}", mahasiswa);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.collection;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.dao.MahasiswaElementCollectionAsTypeDao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.AlamatEmbeddable;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsType;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
@Slf4j
public class TestElementCollectionAsType extends TestCase {
private Session session;
private MahasiswaElementCollectionAsTypeDao mahasiswaDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mahasiswaDao = new MahasiswaElementCollectionAsTypeDao(session);
}
@Test
public void testSaveMahasiswa() {
Transaction trx = this.session.beginTransaction();
MahasiswaElementCollectionAsType dimasMaryanto = MahasiswaElementCollectionAsType.builder()
.name("Dimas Maryanto")
.nim("10511148")
.addresses(Arrays.asList(
AlamatEmbeddable.builder()
.provinsi("Jawa Barat")
.kota("Kab. Bandung")
.kecamatan("Cinunuk")
.kelurahan("Cileunyi")
.namaJalan("Jl. Bukit Indah NO B8")
.rw(16)
.rt(7)
.kodePos(40526)
.build(),
AlamatEmbeddable.builder()
.provinsi("DKI Jakarta")
.kota("Jakarta Selatan")
.kecamatan("Cipete")
.kelurahan("Melawai")
.rw(10)
.rt(1)
.namaJalan("Jl. Damai Buntu")
.kodePos(42105)
.build()
))
.build();
dimasMaryanto = this.mahasiswaDao.save(dimasMaryanto);
trx.commit();
log.info("mahasiswa: {}", dimasMaryanto);
}
@Test
public void testFindById() {
Transaction trx = this.session.beginTransaction();
Optional<MahasiswaElementCollectionAsType> optional = this.mahasiswaDao.findById(14L);
assertTrue("mahasiswa is present ", optional.isPresent());
MahasiswaElementCollectionAsType dimasMaryanto = optional.get();
log.info("mahasiswa: {}", dimasMaryanto);
log.info("alamat: {}", dimasMaryanto.getAddresses());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.collection;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.dao.MahasiswaElementCollectionAsValueDao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsValue;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
@Slf4j
public class TestElementCollectionAsValue extends TestCase {
private Session session;
private MahasiswaElementCollectionAsValueDao mahasiswaDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mahasiswaDao = new MahasiswaElementCollectionAsValueDao(session);
}
@Test
public void testSaveMahasiswa() {
Transaction trx = this.session.beginTransaction();
MahasiswaElementCollectionAsValue dimasMaryanto = MahasiswaElementCollectionAsValue.builder()
.name("Dimas Maryanto")
.nim("10511148")
.address("Bandung")
.hobies(Arrays.asList("Gaming", "Programing", "Movies", "Sharing")).build();
dimasMaryanto = this.mahasiswaDao.save(dimasMaryanto);
trx.commit();
log.info("mahasiswa: {}", dimasMaryanto);
}
@Test
public void testFindById() {
Transaction trx = this.session.beginTransaction();
Optional<MahasiswaElementCollectionAsValue> optional = this.mahasiswaDao.findById(11L);
assertTrue("mahasiswa is present ", optional.isPresent());
MahasiswaElementCollectionAsValue dimasMaryanto = optional.get();
log.info("mahasiswa: {}", dimasMaryanto);
log.info("hobies: {}", dimasMaryanto.getHobies());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.company;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.dao.EmployeeEnumOrdinalDao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumOrdinal;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Optional;
@Slf4j
@Ignore
public class TestEmployeeEnumOrdianal extends TestCase {
private Session session;
private EmployeeEnumOrdinalDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new EmployeeEnumOrdinalDao(session);
}
@Test
public void testInsertValid() {
EmployeeEnumOrdinal ordinal = EmployeeEnumOrdinal.builder()
.name("Dimas Maryanto")
.status(EmployeeStatus.LEAVE)
.birthDate(LocalDate.of(1993, 3, 1))
.build();
this.session.beginTransaction();
ordinal = this.dao.save(ordinal);
this.session.getTransaction().commit();
Optional<EmployeeEnumOrdinal> employeeOptional = this.dao.findById(ordinal.getId());
assertTrue("employee is present", employeeOptional.isPresent());
log.info("employee: {}", employeeOptional.get());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.company;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.dao.EmployeeEnumStringDao;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumOrdinal;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Optional;
@Slf4j
@Ignore
public class TestEmployeeEnumString extends TestCase {
private Session session;
private EmployeeEnumStringDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new EmployeeEnumStringDao(session);
}
@Test
public void testInsertValid() {
EmployeeEnumString ordinal = EmployeeEnumString.builder()
.name("Dimas Maryanto")
.status(EmployeeStatus.LEAVE)
.birthDate(LocalDate.of(1993, 3, 1))
.build();
this.session.beginTransaction();
ordinal = this.dao.save(ordinal);
this.session.getTransaction().commit();
Optional<EmployeeEnumString> employeeOptional = this.dao.findById(ordinal.getId());
assertTrue("employee is present", employeeOptional.isPresent());
log.info("employee: {}", employeeOptional.get());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassRoomIdClassDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.ClassRoomMappingIdClass;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.KeyClassRoomIdClass;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Optional;
@Slf4j
@Ignore
public class TestFindByIdClassRoomIdClass extends TestCase {
private Session session;
private ClassRoomIdClassDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassRoomIdClassDao(session);
}
@Test
public void testFindById() {
KeyClassRoomIdClass pk = KeyClassRoomIdClass.builder()
.classId("si-01")
.year(2011)
.build();
this.session.beginTransaction();
// save data and then return auto generated id
Optional<ClassRoomMappingIdClass> classRoomOptional = this.dao.findById(pk);
assertTrue("classroom is present", classRoomOptional.isPresent());
log.info("classroom: {}", classRoomOptional.orElse(null));
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.entity.Mahasiswa;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Slf4j
public class TestFindByIdMahasiswa extends TestCase {
private Session session;
private MahasiswaDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new MahasiswaDao(session);
}
@Test
public void testFindById() {
this.session.beginTransaction();
Optional<Mahasiswa> mahasiswaOptional = this.dao.findById(1L);
assertTrue("object mahasiswa not null", mahasiswaOptional.isPresent());
log.info("mahasiswa by id: {}", mahasiswaOptional.orElse(null));
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLAggregationFunctionDao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.AggregateFunctionModel;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
@Slf4j
public class TestHQLAggregateFunction extends TestCase {
private Session session;
private HQLAggregationFunctionDao aggregateDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.aggregateDao = new HQLAggregationFunctionDao(session);
}
@Test
public void testFunctionAggregate() {
this.session.beginTransaction();
AggregateFunctionModel model = this.aggregateDao.aggregateFunctions();
assertNotNull("model not null", model);
log.info("data: {}", model);
}
@Test
public void testCountData() {
this.session.beginTransaction();
Long result = this.aggregateDao.countData();
assertNotNull("model not null", result);
log.info("data: {}", result);
}
@Test
public void testSumGajiKaryawan() {
this.session.beginTransaction();
BigDecimal result = this.aggregateDao.sumGajiKaryawan();
assertNotNull("model not null", result);
log.info("data: {}", result);
}
@Test
public void testRataRataGajiKaryawan() {
this.session.beginTransaction();
Double result = this.aggregateDao.avgGajiKarwayan();
assertNotNull("model not null", result);
log.info("data: {}", result);
}
@Test
public void testNilaiMinAndMaxGajiKaryawan() {
this.session.beginTransaction();
Object[] result = this.aggregateDao.minAndMaxGajiKarywan();
assertNotNull("model not null", result);
log.info("data: {min: {}, max: {}}", result[0], result[1]);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLArithmeticDao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.AritmaticModel;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
@Slf4j
public class TestHQLArithmetic extends TestCase {
private Session session;
private HQLArithmeticDao arithmeticDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.arithmeticDao = new HQLArithmeticDao(session);
}
@Test
public void testHitungSalaryEmployeeDalamSetahun() {
List<AritmaticModel> list = this.arithmeticDao
.hitungSalaryEmployeeDalamSetahun();
assertNotNull("list not null", list);
log.info("data: {}", list);
}
@Test
public void testHitungTotalSalarySemuaEmployeeDalamSetahun() {
BigDecimal expectedSalary = new BigDecimal(16_500_000).multiply(new BigDecimal(12));
BigDecimal bigDecimal = this.arithmeticDao
.hitungTotalSalarySemuaEmployeeDalamSetahun();
assertNotNull("salary not null", bigDecimal);
assertEquals("total salary equal",
expectedSalary.setScale(0),
bigDecimal.setScale(0));
log.info("total salary: {}", bigDecimal);
}
@Test
public void testHCariKaryawanYangSalaryDalamSetahunDiatas40Juta() {
List<EmployeeParentChildEntity> list = this.arithmeticDao
.cariKaryawanYangSalaryDalamSetahunDiatas(new BigDecimal(40_000_000));
assertNotNull("list not null", list);
assertEquals("jumlah employee yang salary setahunnya diatas 40 juta", 2, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLBetweenPredicateDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
@Slf4j
public class TestHQLBetweenPredicate extends TestCase {
private Session session;
private HQLBetweenPredicateDao betweenDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.betweenDao = new HQLBetweenPredicateDao(session);
}
@Test
public void testBetweenNumber() {
List<EmployeeParentChildEntity> list = this.betweenDao.findSalaryBetween(
new BigDecimal(3_000_000),
new BigDecimal(5_000_000));
assertEquals("list size", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testBetweenDate() {
List<EmployeeEnumString> list = this.betweenDao.findBirthDateBetween(
LocalDate.of(1992, 1, 2),
LocalDate.of(1993, 3, 2));
assertEquals("list size", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testBetweenCharacter(){
List<EmployeeParentChildEntity> list = this.betweenDao.findFirstCharacterBetween("a", "d");
assertEquals("list size", 1, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLCaseWhenExpresionDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
@Slf4j
public class TestHQLCaseWhenExpresion extends TestCase {
private Session session;
private HQLCaseWhenExpresionDao caseWhenDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.caseWhenDao = new HQLCaseWhenExpresionDao(session);
}
@Test
public void testSimpleExpresion() {
String employeeWithManager = this.caseWhenDao.simpleCaseWhenExpresion("1515ba52-3c78-4baa-bb67-d3aa0c32b351");
assertNotNull("not null", employeeWithManager);
log.info("data: {}", employeeWithManager);
String employeeWithoutManager = this.caseWhenDao.simpleCaseWhenExpresion("aee1795f-816b-4a4b-a8ef-4429fe3069c1");
assertNotNull("not null", employeeWithoutManager);
log.info("data: {}", employeeWithoutManager);
}
@Test
public void testMultipleCondition() {
String employeeWithManager = this.caseWhenDao.multipleConditionCaseWhenExpresion("1515ba52-3c78-4baa-bb67-d3aa0c32b351");
assertNotNull("not null", employeeWithManager);
log.info("data: {}", employeeWithManager);
String employeeWithoutManager = this.caseWhenDao.multipleConditionCaseWhenExpresion("aee1795f-816b-4a4b-a8ef-4429fe3069c1");
assertNotNull("not null", employeeWithoutManager);
log.info("data: {}", employeeWithoutManager);
}
@Test
public void testNestedCondition() {
String employeeWithManager = this.caseWhenDao.nestedCaseWhenExpresion("1515ba52-3c78-4baa-bb67-d3aa0c32b351");
assertNotNull("not null", employeeWithManager);
log.info("data: {}", employeeWithManager);
String employeeWithoutManager = this.caseWhenDao.nestedCaseWhenExpresion("aee1795f-816b-4a4b-a8ef-4429fe3069c1");
assertNotNull("not null", employeeWithoutManager);
log.info("data: {}", employeeWithoutManager);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLCoalesceAndNullIfDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
@Slf4j
public class TestHQLCoalesceAndNullIF extends TestCase {
private Session session;
private HQLCoalesceAndNullIfDao nullOperationDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.nullOperationDao = new HQLCoalesceAndNullIfDao(session);
}
@Test
public void testCoalesceFunction() {
String result = this.nullOperationDao.coalesceFunction(1l);
assertNotNull("penerbit id 1 not null", result);
log.info("data: {}", result);
result = this.nullOperationDao.coalesceFunction(2l);
assertNotNull("penerbit id 2 not null", result);
log.info("data: {}", result);
result = this.nullOperationDao.coalesceFunction(3l);
assertNotNull("penerbit id 3 not null", result);
log.info("data: {}", result);
result = this.nullOperationDao.coalesceFunction(4l);
assertNotNull("penerbit id 4 not null", result);
log.info("data: {}", result);
}
@Test
public void testNullIfFunction(){
String result = this.nullOperationDao.nullIfFunction(1l);
assertNotNull("penerbit id 1 not null", result);
log.info("data: {}", result);
result = this.nullOperationDao.nullIfFunction(2l);
assertNull("penerbit id 2 not null", result);
log.info("data: {}", result);
result = this.nullOperationDao.nullIfFunction(3l);
assertNull("penerbit id 3 null", result);
log.info("data: {}", result);
result = this.nullOperationDao.nullIfFunction(4l);
assertNull("penerbit id 4 null", result);
log.info("data: {}", result);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLCombinePredicateDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class TestHQLCombinePredicate extends TestCase {
private Session session;
private HQLCombinePredicateDao combineDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.combineDao = new HQLCombinePredicateDao(session);
}
@Test
public void testAndOperator() {
List<EmployeeParentChildEntity> data = this.combineDao.findBySalaryHigherThanAndJobName(
new BigDecimal(3_100_000), "Software Engineer");
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("data: {}", collect);
assertEquals("jumlah data", 3, data.size());
}
@Test
public void testOrOperator() {
List<EmployeeParentChildEntity> data = this.combineDao.findBySalaryHigherThanOrJobName(
new BigDecimal(3_100_000), "Software Engineer");
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("data: {}", collect);
assertEquals("jumlah data", 8, data.size());
}
@Test
public void testOrAndOperator() {
List<EmployeeParentChildEntity> data = this.combineDao.findBySalaryHigherThanAndJobNameOrManagerIsNotNull(
new BigDecimal(3_100_000), "Software Engineer");
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("data: {}", collect);
assertEquals("jumlah data", 6, data.size());
}
@Test
public void testOrAndWithPriorityOperator() {
List<EmployeeParentChildEntity> data = this.combineDao.findBySalaryHigherThanOrJobNameAndManagerIsNotNullPriority(
new BigDecimal(3_100_000), "Software Engineer");
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("data: {}", collect);
assertEquals("jumlah data", 7, data.size());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLConcatnationDao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.ConcatnationModel;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLConcatnation extends TestCase {
private Session session;
private HQLConcatnationDao concatDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.concatDao = new HQLConcatnationDao(session);
}
@Test
public void testFunctionConcatByJpa() {
List<ConcatnationModel> list = this.concatDao.concatFunctionJpa();
assertNotNull("list not null", list);
log.info("data: {}", list);
}
@Test
public void testFunctionConcatByHQL() {
List<ConcatnationModel> list = this.concatDao.concatHQL();
assertNotNull("list not null", list);
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLDistinctAsEntityDao;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLDistinctAsProjectionsDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLDistinctAsEntity extends TestCase {
private Session session;
private HQLDistinctAsEntityDao distinctDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.distinctDao = new HQLDistinctAsEntityDao(session);
}
@Test
public void testDistinctData() {
List<KelasEntity> list = this.distinctDao.findKelasByListMahasiswa();
assertNotNull("list status not null", list);
assertEquals("jumlah list status", 3, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLDistinctAsProjectionsDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLDistinctAsProjection extends TestCase {
private Session session;
private HQLDistinctAsProjectionsDao distinctDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.distinctDao = new HQLDistinctAsProjectionsDao(session);
}
@Test
public void testDistinctData() {
List<EmployeeStatus> list = this.distinctDao.findEmployeeStatusOnUsedByEmployees();
assertNotNull("list status not null", list);
assertEquals("jumlah list status", 3, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsType;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsValue;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToManyEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLEmptyCollectionPredicateDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLEmptyCollectionPredicates extends TestCase {
private Session session;
private HQLEmptyCollectionPredicateDao emptyCollectionDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.emptyCollectionDao = new HQLEmptyCollectionPredicateDao(session);
}
@Test
public void testMethodAsType() {
List<MahasiswaElementCollectionAsType> list = this.emptyCollectionDao.emptyCollectionAsType();
assertEquals("list is empty", 0, list.size());
log.info("list is empty: {}", list);
list = this.emptyCollectionDao.notEmptyCollectionAsType();
assertEquals("list is not empty", 1, list.size());
log.info("list is not empty: {}", list);
}
@Test
public void testMethodAsValue() {
List<MahasiswaElementCollectionAsValue> list = this.emptyCollectionDao.emptyCollectionAsValue();
assertEquals("list is empty", 1, list.size());
log.info("list is empty: {}", list);
list = this.emptyCollectionDao.notEmptyCollectionAsValue();
assertEquals("list is not empty", 1, list.size());
log.info("list is not empty: {}", list);
}
@Test
public void testMethodAsEntity() {
List<MahasiswaOneToManyEntity> list = this.emptyCollectionDao.emptyCollectionAsEntity();
assertEquals("list is empty", 1, list.size());
log.info("list is empty: {}", list);
list = this.emptyCollectionDao.notEmptyCollectionAsEntity();
assertEquals("list is not empty", 1, list.size());
log.info("list is not empty: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLGroupByDao;
import com.maryanto.dimas.bootcamp.example.query.hql.dto.GroupByModel;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
@Slf4j
public class TestHQLGroupByDao extends TestCase {
private Session session;
private HQLGroupByDao groupByDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.groupByDao = new HQLGroupByDao(session);
}
@Test
public void testGroupBy(){
List<GroupByModel> data = this.groupByDao.findGroupByJob();
log.info("data: {}", data);
}
@Test
public void testGroupByWithHaving(){
List<GroupByModel> data = this.groupByDao.findGroupByJobWithHaving(new BigDecimal(5_000_000));
log.info("data: {}", data);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumString;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLInPredicateDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class TestHQLInPredicate extends TestCase {
private Session session;
private HQLInPredicateDao inDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.inDao = new HQLInPredicateDao(session);
}
@Test
public void testInPredicateAsString() {
List<EmployeeParentChildEntity> list = this.inDao.findJobIn(
Arrays.asList("Software Engineer", "Chief Technology Officer"));
assertEquals("in string", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testInPredicateAsDate() {
List<EmployeeEnumString> list = this.inDao.findBirthDateIn(
Arrays.asList(
LocalDate.of(1993, 3, 1),
LocalDate.of(1994, 1, 7),
LocalDate.of(2021, 1, 1))
);
assertEquals("in date", 3, list.size());
log.info("data: {}", list);
}
@Test
public void testInPredicateAsEnum() {
List<EmployeeEnumString> list = this.inDao.findStatusIn(
Arrays.asList(EmployeeStatus.LEAVE, EmployeeStatus.RESIGN));
assertEquals("in enum", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testInPredicateAsNumber(){
List<EmployeeParentChildEntity> list = this.inDao.findSalaryIn(Arrays.asList(
BigDecimal.ZERO,
new BigDecimal(3_000_000))
);
assertEquals("in number", 1, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLJoinExplicitDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLJoinExplicit extends TestCase {
private Session session;
private HQLJoinExplicitDao joinDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.joinDao = new HQLJoinExplicitDao(session);
}
@Test
public void testJoinExplicitWithKeywordOn() {
List<MahasiswaOneToOneEntity> listMahasiswa = this.joinDao.findByAlamatProvinsiKeywordOn("Jawa Barat");
assertNotNull("Mahasiswa not null", listMahasiswa);
assertEquals("Jumlah mahasiswa equal", 1, listMahasiswa.size());
log.info("data: {}", listMahasiswa);
}
@Test
public void testJoinExplicitWithKeywordWith() {
List<MahasiswaOneToOneEntity> listMahasiswa = this.joinDao.findByAlamatProvinsiKeywordWith("Jawa Barat");
assertNotNull("Mahasiswa not null", listMahasiswa);
assertEquals("Jumlah mahasiswa equal", 1, listMahasiswa.size());
log.info("data: {}", listMahasiswa);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLJoinImplicitDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLJoinImplicit extends TestCase {
private Session session;
private HQLJoinImplicitDao joinDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.joinDao = new HQLJoinImplicitDao(session);
}
@Test
public void testJoinImplicit() {
List<MahasiswaOneToOneEntity> listMahasiswa = this.joinDao.findByAlamatProvinsi("Jawa Barat");
assertNotNull("Mahasiswa not null", listMahasiswa);
assertEquals("Jumlah mahasiswa equal", listMahasiswa.size(), 1);
log.info("data: {}", listMahasiswa);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLLikePredicatesDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class TestHQLLikePredicate extends TestCase {
private Session session;
private HQLLikePredicatesDao likeDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.likeDao = new HQLLikePredicatesDao(session);
}
@Test
public void testWithoutExpresion() {
String predicate = "Dimas Maryanto";
List<EmployeeParentChildEntity> data = this.likeDao.likeOperator(predicate);
assertEquals("size data", 1, data.size());
EmployeeParentChildEntity empl = data.stream().findFirst().orElse(null);
assertNotNull("not null", empl);
assertEquals("nama ", predicate, empl.getName());
log.info("data: ", data);
}
@Test
public void testStringExpressionContainChar() {
String predicate = "%a%";
List<EmployeeParentChildEntity> list = this.likeDao.likeOperator(predicate);
assertEquals("size data", 3, list.size());
List<String> names = list.stream()
.map(data -> data.getName())
.collect(Collectors.toList());
log.info("data: {}", names);
}
@Test
public void testStringExpressionSecondCharIs() {
String predicate = "_i%";
List<EmployeeParentChildEntity> list = this.likeDao.likeOperator(predicate);
assertEquals("size data", 1, list.size());
List<String> names = list.stream()
.map(data -> data.getName())
.collect(Collectors.toList());
log.info("data: {}", names);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MataKuliahEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLMatakuliahCUDDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Optional;
@Slf4j
public class TestHQLMatakuliahCreateUpdateDelete extends TestCase {
private Session session;
private HQLMatakuliahCUDDao matakuliahDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.matakuliahDao = new HQLMatakuliahCUDDao(session);
}
@Test
public void testDeleteById() {
Transaction trx = this.session.beginTransaction();
MataKuliahEntity matakuliahBaru = MataKuliahEntity.builder()
.nama("matakuliah baru")
.sks(2)
.build();
matakuliahBaru = this.matakuliahDao.save(matakuliahBaru);
boolean result = this.matakuliahDao.removeById(matakuliahBaru.getId());
log.info("Data berhasil di hapus? {}", result);
trx.commit();
Optional<MataKuliahEntity> optional = this.matakuliahDao.findById(matakuliahBaru.getId());
assertFalse("matakuliah is present", optional.isPresent());
}
@Test
public void testUpdateData() {
Transaction trx = this.session.beginTransaction();
String namaMatakuliahLama = "Matakuliah lama";
String namaMatakuliahUpdated = "Matakuliah baru";
MataKuliahEntity matakuliahBaru = MataKuliahEntity.builder()
.nama(namaMatakuliahLama)
.sks(2)
.build();
matakuliahBaru = this.matakuliahDao.save(matakuliahBaru);
assertEquals("nama matakuliah sebelum di update", matakuliahBaru.getNama(), namaMatakuliahLama);
log.info("sebelum di updated: {}", matakuliahBaru);
MataKuliahEntity mataKuliahLama = matakuliahBaru;
mataKuliahLama.setNama(namaMatakuliahUpdated);
this.matakuliahDao.update(mataKuliahLama);
trx.commit();
Optional<MataKuliahEntity> optional = this.matakuliahDao.findById(matakuliahBaru.getId());
assertTrue("matakuliah is present", optional.isPresent());
matakuliahBaru = optional.get();
assertEquals("nama matakuliah seteleh di update", matakuliahBaru.getNama(), namaMatakuliahUpdated);
log.info("setelah di updated: {}", matakuliahBaru);
Transaction trx2 = this.session.beginTransaction();
this.matakuliahDao.removeById(matakuliahBaru.getId());
trx2.commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MataKuliahEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLMatakuliahReadDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
import java.util.Optional;
@Slf4j
public class TestHQLMatakuliahRead extends TestCase {
private Session session;
private HQLMatakuliahReadDao matakuliahDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.matakuliahDao = new HQLMatakuliahReadDao(session);
}
@Test
public void testFindAll() {
this.session.beginTransaction();
List<MataKuliahEntity> list = this.matakuliahDao.findAll();
log.info("data: {}", list);
assertNotNull("list not null", list);
assertEquals("list size equal", list.size(), 2);
}
@Test
public void testFindByIdWithIndex() {
this.session.beginTransaction();
Optional<MataKuliahEntity> optional = this.matakuliahDao.findById("79c06b62-e70c-41f3-b42d-3aa63ab8d366");
assertTrue("matakuliah is present", optional.isPresent());
MataKuliahEntity matakuliah = optional.get();
log.info("data: {}", matakuliah);
assertEquals("nama matakuliah sama", matakuliah.getNama(), "Pemograman Java 1");
}
@Test
public void testFindByNameWithNamedParameter() {
this.session.beginTransaction();
List<MataKuliahEntity> list = this.matakuliahDao.findByNamaNamedParameters("SKRIPSI");
log.info("data: {}", list);
assertNotNull("list not null", list);
assertEquals("list size equal", list.size(), 1);
}
@Test
public void testFindByNameAndSks() {
this.session.beginTransaction();
List<MataKuliahEntity> list = this.matakuliahDao.findByNamaAndSks("SKRIPSI", 6);
log.info("data: {}", list);
assertNotNull("list not null", list);
assertEquals("list size equal", list.size(), 1);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.simple.entity.kampus.Mahasiswa;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLNotPredicateDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class TestHQLNotPredicate extends TestCase {
private Session session;
private HQLNotPredicateDao notDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.notDao = new HQLNotPredicateDao(session);
}
@Test
public void testNegation() {
List<Mahasiswa> data = this.notDao.findByNotActive();
log.info("data: {}", data);
assertEquals("jumlah data", 1, data.size());
}
/**
* data: 1999-09-09 ada 2 data
*/
@Test
public void testNotIn() {
List<Mahasiswa> data = this.notDao.findByBirthDateNotIn(
Arrays.asList(
LocalDate.of(1999, 9, 8)
));
log.info("data: {}", data);
assertEquals("jumlah data", 2, data.size());
}
@Test
public void testNotNull() {
List<Mahasiswa> data = this.notDao.findByBioNotNull();
log.info("data: {}", data);
assertEquals("jumlah data", 0, data.size());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLNullLessPredicateDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLNullLessPredicate extends TestCase {
private Session session;
private HQLNullLessPredicateDao nullLessDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.nullLessDao = new HQLNullLessPredicateDao(session);
}
@Test
public void testOperatorIsNotNull() {
List<EmployeeParentChildEntity> list = this.nullLessDao.employeeHaveAManager();
assertEquals("list employee not null", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testOperatorIsNull() {
List<EmployeeParentChildEntity> list = this.nullLessDao.employeesWithoutManager();
assertEquals("list employee not null", 1, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLOffsetAndLimitDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class TestHQLOffsetAndLimit extends TestCase {
private Session session;
private HQLOffsetAndLimitDao offsetLimitDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.offsetLimitDao = new HQLOffsetAndLimitDao(session);
}
@Test
public void testOffsetData() {
List<EmployeeParentChildEntity> data = this.offsetLimitDao.offset(3);
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName).collect(Collectors.toList());
log.info("data: {size: {}, element: {}}", collect.size(), collect);
}
@Test
public void testLimitData() {
List<EmployeeParentChildEntity> data = this.offsetLimitDao.limit(4);
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName).collect(Collectors.toList());
log.info("data: {size: {}, element: {}}", collect.size(), collect);
}
@Test
public void testPaginate() {
List<EmployeeParentChildEntity> data = this.offsetLimitDao.offsetAndLimit(4, 5);
List<String> collect = data.stream().map(EmployeeParentChildEntity::getName).collect(Collectors.toList());
log.info("data: {size: {}, element: {}}", collect.size(), collect);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLOrderingDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class TestHQLOrdering extends TestCase {
private Session session;
private HQLOrderingDao orderDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.orderDao = new HQLOrderingDao(session);
}
@Test
public void testOrderBySalaryAsc(){
List<EmployeeParentChildEntity> data = this.orderDao.findAllSortBySalaryAsc();
List<BigDecimal> collect = data.stream().map(EmployeeParentChildEntity::getSalary)
.collect(Collectors.toList());
log.info("data: {}", collect);
}
@Test
public void testOrderBySalaryDesc(){
List<EmployeeParentChildEntity> data = this.orderDao.findAllSortBySalaryDesc();
List<BigDecimal> collect = data.stream().map(EmployeeParentChildEntity::getSalary)
.collect(Collectors.toList());
log.info("data: {}", collect);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaElementCollectionAsType;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLReadOnlyEntityDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Optional;
import java.util.UUID;
@Slf4j
public class TestHQLReadOnlyEntity extends TestCase {
private Session session;
private HQLReadOnlyEntityDao readOnlyDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.readOnlyDao = new HQLReadOnlyEntityDao(session);
}
@Test
public void testFindAndUpdatedAuto() {
Transaction trx = this.session.beginTransaction();
Optional<MahasiswaElementCollectionAsType> optional = this.readOnlyDao.findById(14L);
assertTrue("is pressent", optional.isPresent());
MahasiswaElementCollectionAsType empl = optional.get();
empl.setName(UUID.randomUUID().toString());
trx.commit();
}
@Test
public void testFindAndReadOnly() {
Transaction trx = this.session.beginTransaction();
Optional<MahasiswaElementCollectionAsType> optional = this.readOnlyDao.findByIdReadOnly(14L);
assertTrue("is pressent", optional.isPresent());
MahasiswaElementCollectionAsType empl = optional.get();
empl.setName(UUID.randomUUID().toString());
trx.commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilSingleTableEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLRelationalComparisonBooleanDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLRelataionComparisonBoolean extends TestCase {
private Session session;
private HQLRelationalComparisonBooleanDao booleanDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.booleanDao = new HQLRelationalComparisonBooleanDao(session);
}
@Test
public void testBoolean() {
List<MobilSingleTableEntity> list = this.booleanDao.findEqualByStatusAllWheelDrive(false);
assertEquals("equal", 1, list.size());
log.info("data: {}", list);
list = this.booleanDao.findEqualByStatusAllWheelDrive(null);
assertEquals("equal", 0, list.size());
log.info("data: {}", list);
list = this.booleanDao.findNegationByStatusAllWheelDrive(true);
assertEquals("equal", 1, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLRelationalComparisonDateAndTimeDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
import java.util.List;
@Slf4j
public class TestHQLRelationalComparisonDateAndTime extends TestCase {
private Session session;
private HQLRelationalComparisonDateAndTimeDao dateAndTimeDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dateAndTimeDao = new HQLRelationalComparisonDateAndTimeDao(session);
}
@Test
public void testEqualDate() {
List<MahasiswaOneToOneEntity> list = this.dateAndTimeDao
.findEqualByTanggalLahir(LocalDate.of(1993, 3, 1));
assertEquals("equal", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testNotEqualDate() {
List<MahasiswaOneToOneEntity> list = this.dateAndTimeDao
.findNotEqualByTanggalLahir(LocalDate.of(1993, 3, 1));
assertEquals("not equal", 0, list.size());
log.info("data: {}", list);
list = this.dateAndTimeDao
.findNotSameByTanggalLahir(LocalDate.of(1992, 3, 1));
assertEquals("not same", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testHigherDate() {
List<MahasiswaOneToOneEntity> list = this.dateAndTimeDao
.findHigherByTanggalLahir(LocalDate.of(1993, 3, 1));
assertEquals("higher", 0, list.size());
log.info("data: {}", list);
list = this.dateAndTimeDao
.findHigherThanByTanggalLahir(LocalDate.of(1993, 3, 1));
assertEquals("higher than", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testLowerDate() {
List<MahasiswaOneToOneEntity> list = this.dateAndTimeDao
.findLowerByTanggalLahir(LocalDate.of(1993, 3, 1));
assertEquals("higher", 0, list.size());
log.info("data: {}", list);
list = this.dateAndTimeDao
.findLowerThanByTanggalLahir(LocalDate.of(1993, 3, 1));
assertEquals("higher than", 2, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeEnumOrdinal;
import com.maryanto.dimas.bootcamp.example.mapping.enumeration.entity.EmployeeStatus;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLRelationalComparisonEnumDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLRelationalComparisonEnum extends TestCase {
private Session session;
private HQLRelationalComparisonEnumDao enumDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.enumDao = new HQLRelationalComparisonEnumDao(session);
}
@Test
public void testEqualEnumeration() {
List<EmployeeEnumOrdinal> list = this.enumDao.findEqualByEmployeeStatus(EmployeeStatus.LEAVE);
assertEquals("equal", 1, list.size());
log.info("data: {}", list);
}
@Test
public void testNotEqualEnumeration() {
List<EmployeeEnumOrdinal> list = this.enumDao.findNotEqualByEmployeeStatus(EmployeeStatus.LEAVE);
assertEquals("equal", 0, list.size());
log.info("data: {}", list);
list = this.enumDao.findNotSameByEmployeeStatus(EmployeeStatus.LEAVE);
assertEquals("equal", 0, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLRelationalComparisonNumberDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLRelationalComparisonNumber extends TestCase {
private Session session;
private HQLRelationalComparisonNumberDao numberDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.numberDao = new HQLRelationalComparisonNumberDao(session);
}
@Test
public void testEqualNumberComparison() {
List<KelasEntity> list = this.numberDao.findEqualByTahunAngkatan(2011);
assertEquals("equal", 4, list.size());
log.info("data: {}", list);
}
@Test
public void testNotEqualNumberComparison() {
List<KelasEntity> list = this.numberDao.findNotEqualByTahunAngkatan(2011);
assertEquals("not equal", 2, list.size());
log.info("data: {}", list);
list = this.numberDao.findNotSameByTahunAngkatan(2011);
assertEquals("not same", 2, list.size());
log.info("data: {}", list);
}
@Test
public void testHigherNumberComparison() {
List<KelasEntity> list = this.numberDao.findHigherByTahunAngkatan(2011);
assertEquals("higher", 2, list.size());
log.info("data: {}", list);
list = this.numberDao.findHigherThenByTahunAngkatan(2011);
assertEquals("higher than", 6, list.size());
log.info("data: {}", list);
}
@Test
public void testLowerNumberComparison() {
List<KelasEntity> list = this.numberDao.findLowerByTahunAngkatan(2012);
assertEquals("lower", 4, list.size());
log.info("data: {}", list);
list = this.numberDao.findLowerThanByTahunAngkatan(2012);
assertEquals("lower than", 5, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLRelationalComparisonStringDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
@Slf4j
public class TestHQLRelationalComparisonString extends TestCase {
private Session session;
private HQLRelationalComparisonStringDao stringDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.stringDao = new HQLRelationalComparisonStringDao(session);
}
@Test
public void testStringComparison() {
List<KelasEntity> list = this.stringDao.findEqualBy("IF-01");
assertEquals("equal operator", 3, list.size());
log.info("data: {}", list);
list = this.stringDao.findEqualBy(null);
assertEquals("equal operator", 0, list.size());
log.info("data: {}", list);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.query.hql;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import com.maryanto.dimas.bootcamp.example.query.hql.dao.HQLSubQueryQualifierDao;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class TestHQLSubqueryQualifier extends TestCase {
private Session session;
private HQLSubQueryQualifierDao subqueryDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.subqueryDao = new HQLSubQueryQualifierDao(session);
}
@Test
public void testInOperator() {
List<EmployeeParentChildEntity> data = this.subqueryDao.findEmployeesWhenSalaryInEmployeeJob("Software Engineer");
List<String> employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("data: {}", employeeNames);
assertEquals("jumlah data", 7, data.size());
}
@Test
public void testAllOperator() {
List<EmployeeParentChildEntity> data = this.subqueryDao.findEmployeesWhenSalaryEqualAllByAvgSalary("Software Engineer");
List<String> employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("= ALL: {}", employeeNames);
data = this.subqueryDao.findEmployeesWhenSalaryLowerAllByAvgSalary("Software Engineer");
employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("< ALL: {}", employeeNames);
data = this.subqueryDao.findEmployeesWhenSalaryHigherAllByAvgSalary("Software Engineer");
employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("> ALL: {}", employeeNames);
}
@Test
public void testAnyOperator() {
List<EmployeeParentChildEntity> data = this.subqueryDao.findEmployeesWhenSalaryEqualAnyByEmployeeJob("Software Engineer");
List<String> employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("= ANY: {}", employeeNames);
data = this.subqueryDao.findEmployeesWhenSalaryLowerAnyByEmployeeJob("Software Engineer");
employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("< ANY: {}", employeeNames);
data = this.subqueryDao.findEmployeesWhenSalaryHigherAnyByEmployeeJob("Software Engineer");
employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("> ANY: {}", employeeNames);
}
@Test
public void testSomeOperator() {
List<EmployeeParentChildEntity> data = this.subqueryDao.findEmployeesWhenSalaryEqualSomeByEmployeeJob("Software Engineer");
List<String> employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("= SOME: {}", employeeNames);
data = this.subqueryDao.findEmployeesWhenSalaryLowerSomeByEmployeeJob("Software Engineer");
employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("< SOME: {}", employeeNames);
data = this.subqueryDao.findEmployeesWhenSalaryHigherSomeByEmployeeJob("Software Engineer");
employeeNames = data.stream().map(EmployeeParentChildEntity::getName)
.collect(Collectors.toList());
log.info("> SOME: {}", employeeNames);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.inherintance;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao.KendaraanJoinTableDao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanJoinTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilJoinTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorJoinTableEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Optional;
@Slf4j
public class TestKendaraanJoinTable extends TestCase {
private Session session;
private KendaraanJoinTableDao kendaraanDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.kendaraanDao = new KendaraanJoinTableDao(session);
}
@Test
public void testSaveMotor() {
Transaction trx = this.session.beginTransaction();
KendaraanJoinTableEntity s1000rr = MotorJoinTableEntity.builder()
.nama("BMW S1000RR")
.cc(1000)
.jumlahCylinder(4)
.jumlahRoda(2)
.namaPabrikan("PT. BMW Motorrad")
.jenisRantai("Rantai")
.build();
s1000rr = this.kendaraanDao.save(s1000rr);
trx.commit();
Optional<MotorJoinTableEntity> motorOptional = this.kendaraanDao.findByMotorId(s1000rr.getId());
assertTrue("motor is present", motorOptional.isPresent());
MotorJoinTableEntity testFindById = motorOptional.get();
assertEquals("nama motor", testFindById.getNama(), s1000rr.getNama());
log.info("mobil: {}", testFindById);
}
@Test
public void testSaveMobil() {
Transaction trx = this.session.beginTransaction();
KendaraanJoinTableEntity hondaBrio = MobilJoinTableEntity.builder()
.nama("Honda BRIO")
.allWheelDrive(false)
.cc(1000)
.jumlahCylinder(4)
.jumlahKursi(4)
.jumlahRoda(4)
.namaPabrikan("PT. Honda Motor Company")
.build();
hondaBrio = this.kendaraanDao.save(hondaBrio);
trx.commit();
Optional<MobilJoinTableEntity> mobilOptional = this.kendaraanDao.findByMobilId(hondaBrio.getId());
assertTrue("mobil is present", mobilOptional.isPresent());
MobilJoinTableEntity testFindById = mobilOptional.get();
assertEquals("nama mobil", testFindById.getNama(), hondaBrio.getNama());
log.info("mobil: {}", testFindById);
}
@Test
public void testFindById() {
this.session.beginTransaction();
Optional<KendaraanJoinTableEntity> mobilOptional =
this.kendaraanDao.findById("04676b7f-1d09-4522-978d-4f3b379b2a5b");
assertTrue("general is present", mobilOptional.isPresent());
log.info("mobil: {}", mobilOptional.get());
}
@Test
public void testFindByMobilId() {
this.session.beginTransaction();
Optional<MobilJoinTableEntity> mobilOptional =
this.kendaraanDao.findByMobilId("04676b7f-1d09-4522-978d-4f3b379b2a5b");
assertTrue("mobil is present", mobilOptional.isPresent());
log.info("mobil: {}", mobilOptional.get());
}
@Test
public void testFindByMotorId() {
this.session.beginTransaction();
Optional<MotorJoinTableEntity> mobilOptional =
this.kendaraanDao.findByMotorId("04676b7f-1d09-4522-978d-4f3b379b2a5b");
assertTrue("motor is present", mobilOptional.isPresent());
log.info("motor: {}", mobilOptional.get());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.inherintance;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao.KendaraanSeparateTableDao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanSeparateTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilSeparateTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorSeparateTableEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Optional;
@Slf4j
public class TestKendaraanSeparateTable extends TestCase {
private Session session;
private KendaraanSeparateTableDao kendaraanDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.kendaraanDao = new KendaraanSeparateTableDao(session);
}
@Test
public void testSaveMotor() {
Transaction trx = this.session.beginTransaction();
KendaraanSeparateTableEntity s1000rr = MotorSeparateTableEntity.builder()
.nama("BMW S1000RR")
.cc(1000)
.jumlahCylinder(4)
.jumlahRoda(2)
.namaPabrikan("PT. BMW Motorrad")
.jenisRantai("Rantai")
.build();
s1000rr = this.kendaraanDao.save(s1000rr);
trx.commit();
Optional<MotorSeparateTableEntity> motorOptional = this.kendaraanDao.findByMotorId(s1000rr.getId());
assertTrue("motor is present", motorOptional.isPresent());
MotorSeparateTableEntity testFindById = motorOptional.get();
assertEquals("nama motor", testFindById.getNama(), s1000rr.getNama());
log.info("mobil: {}", testFindById);
}
@Test
public void testSaveMobil() {
Transaction trx = this.session.beginTransaction();
KendaraanSeparateTableEntity hondaBrio = MobilSeparateTableEntity.builder()
.nama("Honda BRIO")
.allWheelDrive(false)
.cc(1000)
.jumlahCylinder(4)
.jumlahKursi(4)
.jumlahRoda(4)
.namaPabrikan("PT. Honda Motor Company")
.build();
hondaBrio = this.kendaraanDao.save(hondaBrio);
trx.commit();
Optional<MobilSeparateTableEntity> mobilOptional = this.kendaraanDao.findByMobilId(hondaBrio.getId());
assertTrue("mobil is present", mobilOptional.isPresent());
MobilSeparateTableEntity testFindById = mobilOptional.get();
assertEquals("nama mobil", testFindById.getNama(), hondaBrio.getNama());
log.info("mobil: {}", testFindById);
}
@Test
public void testFindById() {
this.session.beginTransaction();
Optional<KendaraanSeparateTableEntity> generalOptional =
this.kendaraanDao.findById("a9845140-21e5-4397-869a-594d8dc8e5c5");
assertTrue("general is present", generalOptional.isPresent());
log.info("mobil: {}", generalOptional.get());
}
@Test
public void testFindByMobilId() {
this.session.beginTransaction();
Optional<MobilSeparateTableEntity> mobilOptional =
this.kendaraanDao.findByMobilId("a9845140-21e5-4397-869a-594d8dc8e5c5");
assertTrue("mobil is present", mobilOptional.isPresent());
log.info("mobil: {}", mobilOptional.get());
}
@Test
public void testFindByMotorId() {
this.session.beginTransaction();
Optional<MotorSeparateTableEntity> motorOptional =
this.kendaraanDao.findByMotorId("a9845140-21e5-4397-869a-594d8dc8e5c5");
assertTrue("motor is present", motorOptional.isPresent());
log.info("motor: {}", motorOptional.get());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.inherintance;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao.KendaraanSingleTableDao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanSingleTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilSingleTableEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorSingleTableEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Optional;
@Slf4j
public class TestKendaraanSingleTable extends TestCase {
private Session session;
private KendaraanSingleTableDao kendaraanDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.kendaraanDao = new KendaraanSingleTableDao(session);
}
@Test
public void testSaveMobil() {
Transaction trx = this.session.beginTransaction();
log.info("connected!");
KendaraanSingleTableEntity hondaBrio = MobilSingleTableEntity.builder()
.nama("Honda BRIO")
.allWheelDrive(false)
.cc(1000)
.jumlahCylinder(4)
.jumlahKursi(4)
.jumlahRoda(4)
.namaPabrikan("PT. Honda Motor Company")
.build();
hondaBrio = this.kendaraanDao.save(hondaBrio);
trx.commit();
Optional<MobilSingleTableEntity> mobilOptional = this.kendaraanDao.findByMobilId(hondaBrio.getId());
assertTrue("mobil is present", mobilOptional.isPresent());
MobilSingleTableEntity testFindById = mobilOptional.get();
assertEquals("nama mobil", testFindById.getNama(), hondaBrio.getNama());
log.info("mobil: {}", testFindById);
}
@Test
public void testSaveMotor() {
Transaction trx = this.session.beginTransaction();
log.info("connected!");
KendaraanSingleTableEntity s1000rr = MotorSingleTableEntity.builder()
.nama("BMW S1000RR")
.cc(1000)
.jumlahCylinder(4)
.jumlahRoda(2)
.namaPabrikan("PT. BMW Motorrad")
.jenisRantai("Rantai")
.build();
s1000rr = this.kendaraanDao.save(s1000rr);
trx.commit();
Optional<MotorSingleTableEntity> motorOptional = this.kendaraanDao.findByMotorId(s1000rr.getId());
assertTrue("motor is present", motorOptional.isPresent());
MotorSingleTableEntity testFindById = motorOptional.get();
assertEquals("nama motor", testFindById.getNama(), s1000rr.getNama());
log.info("mobil: {}", testFindById);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.inherintance;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao.KendaraanSingleTableDiscriminatorDao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.KendaraanSingleTableDiscriminatorEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilSingleTableDiscriminatorEntity;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MotorSingleTableDiscriminatorEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.util.Optional;
@Slf4j
public class TestKendaraanSingleTableDiscriminator extends TestCase {
private Session session;
private KendaraanSingleTableDiscriminatorDao kendaraanDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.kendaraanDao = new KendaraanSingleTableDiscriminatorDao(session);
}
@Test
public void testSaveMobil() {
Transaction trx = this.session.beginTransaction();
log.info("connected!");
KendaraanSingleTableDiscriminatorEntity hondaBrio = MobilSingleTableDiscriminatorEntity.builder()
.nama("Honda BRIO")
.allWheelDrive(false)
.cc(1000)
.jumlahCylinder(4)
.jumlahKursi(4)
.jumlahRoda(4)
.namaPabrikan("PT. Honda Motor Company")
.build();
hondaBrio = this.kendaraanDao.save(hondaBrio);
trx.commit();
Optional<MobilSingleTableDiscriminatorEntity> mobilOptional = this.kendaraanDao.findByMobilId(hondaBrio.getId());
assertTrue("mobil is present", mobilOptional.isPresent());
MobilSingleTableDiscriminatorEntity testFindById = mobilOptional.get();
assertEquals("nama mobil", testFindById.getNama(), hondaBrio.getNama());
log.info("mobil: {}", testFindById);
}
@Test
public void testSaveMotor() {
Transaction trx = this.session.beginTransaction();
log.info("connected!");
KendaraanSingleTableDiscriminatorEntity s1000rr = MotorSingleTableDiscriminatorEntity.builder()
.nama("BMW S1000RR")
.cc(1000)
.jumlahCylinder(4)
.jumlahRoda(2)
.namaPabrikan("PT. BMW Motorrad")
.jenisRantai("Rantai")
.build();
s1000rr = this.kendaraanDao.save(s1000rr);
trx.commit();
Optional<MotorSingleTableDiscriminatorEntity> motorOptional = this.kendaraanDao.findByMotorId(s1000rr.getId());
assertTrue("motor is present", motorOptional.isPresent());
MotorSingleTableDiscriminatorEntity testFindById = motorOptional.get();
assertEquals("nama motor", testFindById.getNama(), s1000rr.getNama());
log.info("mobil: {}", testFindById);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.embedded;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.dao.MahasiswaEmbeddedDao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.AlamatEmbeddable;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaEmbedded;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
@Slf4j
public class TestMahasiswaEmbedded extends TestCase {
private Session session;
private MahasiswaEmbeddedDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new MahasiswaEmbeddedDao(session);
}
@Test
public void testInsertValid() {
MahasiswaEmbedded mhs = MahasiswaEmbedded.builder()
.nim("15011148")
.nama("Dimas Maryanto")
.tahunMasuk(2011)
.tanggalLahir(LocalDate.of(1991, 3, 3))
.alamat(AlamatEmbeddable.builder()
.provinsi("Jawa Barat")
.kota("Kab. Bandung")
.kelurahan("Cinunuk")
.kecamatan("Cileuyi")
.rt(6)
.rw(18)
.kodePos(40526).build()
).build();
this.session.beginTransaction();
this.dao.save(mhs);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.embedded;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.dao.MahasiswaEmbeddedDao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.dao.MahasiswaEmbeddedOverrideAttributesDao;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.AlamatEmbeddable;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaEmbedded;
import com.maryanto.dimas.bootcamp.example.mapping.embedded.entity.MahasiswaEmbeddedOverrideAttributes;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
@Slf4j
public class TestMahasiswaEmbeddedOverrideAttribute extends TestCase {
private Session session;
private MahasiswaEmbeddedOverrideAttributesDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new MahasiswaEmbeddedOverrideAttributesDao(session);
}
@Test
public void testInsertValid() {
MahasiswaEmbeddedOverrideAttributes mhs = MahasiswaEmbeddedOverrideAttributes.builder()
.nim("15011148")
.nama("Dimas Maryanto")
.tahunMasuk(2011)
.tanggalLahir(LocalDate.of(1991, 3, 3))
.alamatRumah(AlamatEmbeddable.builder()
.provinsi("Jawa Barat")
.kota("Kab. Bandung")
.kelurahan("Cinunuk")
.kecamatan("Cileuyi")
.rt(6)
.rw(18)
.kodePos(40526)
.namaJalan("Jl. Bukit Indah No B8")
.build()
)
.alamatOrangTua(AlamatEmbeddable.builder()
.provinsi("Jawa Barat")
.kota("Kab. Bandung")
.kelurahan("Cinunuk")
.kecamatan("Cileuyi")
.rt(6)
.rw(18)
.kodePos(40526)
.namaJalan("Jl. Bukit Indah No B8")
.build()
).build();
this.session.beginTransaction();
this.dao.save(mhs);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.MahasiswaManyToManyEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.MataKuliahEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaManyToManyEntity;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MataKuliahEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@Ignore
@Slf4j
public class TestMahasiswaManyToManyEntity extends TestCase {
private Session session;
private MahasiswaManyToManyEntityDao mahasiswaDao;
private MataKuliahEntityDao matakuliahDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mahasiswaDao = new MahasiswaManyToManyEntityDao(session);
this.matakuliahDao = new MataKuliahEntityDao(session);
}
@Test
public void testSaveMahasiswa() {
this.session.beginTransaction();
MataKuliahEntity pemogramanJava = new MataKuliahEntity();
pemogramanJava.setSks(3);
pemogramanJava.setNama("Pemograman Java 1");
pemogramanJava = this.matakuliahDao.save(pemogramanJava);
MataKuliahEntity skripsi = MataKuliahEntity.builder()
.sks(6)
.nama("SKRIPSI")
.build();
skripsi = this.matakuliahDao.save(skripsi);
Set<MataKuliahEntity> ambilMatakuliah = new HashSet<>();
ambilMatakuliah.add(pemogramanJava);
ambilMatakuliah.add(skripsi);
MahasiswaManyToManyEntity dimas = MahasiswaManyToManyEntity.builder()
.nama("Dimas Maryanto")
.tahunMasuk(2012)
.nim("10512148")
.tanggalLahir(LocalDate.of(1993, 3, 1))
.listMatakuliah(ambilMatakuliah)
.build();
dimas = this.mahasiswaDao.save(dimas);
log.info("mahasiswa baru: {}", dimas);
MahasiswaManyToManyEntity yusuf = MahasiswaManyToManyEntity.builder()
.nama("Muhamad Yusuf")
.tahunMasuk(2012)
.nim("10512150")
.tanggalLahir(LocalDate.of(1992, 1, 1))
.listMatakuliah(ambilMatakuliah)
.build();
yusuf = this.mahasiswaDao.save(yusuf);
log.info("mahasiswa baru: {}", yusuf);
this.session.getTransaction().commit();
}
@Test
public void testFindMahasiswaId() {
this.session.beginTransaction();
Optional<MahasiswaManyToManyEntity> optional = this.mahasiswaDao.findById("24c3eb73-9857-4432-a3c7-d175fb0fc7dc");
assertTrue("mahasiswa not present!", optional.isPresent());
MahasiswaManyToManyEntity mahasiswa = optional.get();
log.info("mahasiswa: {}", mahasiswa);
log.info("list matakuliah {\nsize: {}, \ndata: {}\n}", mahasiswa.getListMatakuliah().size(), mahasiswa.getListMatakuliah());
}
@Test
public void testFindMatakuliahId() {
this.session.beginTransaction();
Optional<MataKuliahEntity> optional = this.matakuliahDao.findById("733be4ef-20fb-4d16-bbfe-b4b6c31ee8d3");
assertTrue("kelas not present!", optional.isPresent());
MataKuliahEntity kelas = optional.get();
log.info("kelas: {}", kelas);
log.info("list mahasiswa {\nsize: {}, \ndata: {}\n}",kelas.getListMahasiswa().size() ,kelas.getListMahasiswa());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.KelasEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.MahasiswaManyToOneEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.KelasEntity;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaManyToOneEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Optional;
@Ignore
@Slf4j
public class TestMahasiswaManyToOneEntity extends TestCase {
private Session session;
private MahasiswaManyToOneEntityDao mahasiswaDao;
private KelasEntityDao kelasDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mahasiswaDao = new MahasiswaManyToOneEntityDao(session);
this.kelasDao = new KelasEntityDao(session);
}
@Test
public void testSaveMahasiswa() {
this.session.beginTransaction();
KelasEntity is01 = KelasEntity.builder()
.nama("IS-01")
.angkatan(2011)
.programStudi("Informatika")
.build();
is01 = this.kelasDao.save(is01);
MahasiswaManyToOneEntity dimas = MahasiswaManyToOneEntity.builder()
.kelas(is01)
.nama("Dimas Maryanto")
.tahunMasuk(2012)
.nim("10512148")
.tanggalLahir(LocalDate.of(1993, 3, 1))
.build();
dimas = this.mahasiswaDao.save(dimas);
log.info("mahasiswa baru: {}", dimas);
MahasiswaManyToOneEntity yusuf = MahasiswaManyToOneEntity.builder()
.kelas(is01)
.nama("Muhamad Yusuf")
.tahunMasuk(2012)
.nim("10512150")
.tanggalLahir(LocalDate.of(1992, 1, 1))
.build();
yusuf = this.mahasiswaDao.save(yusuf);
log.info("mahasiswa baru: {}", yusuf);
this.session.getTransaction().commit();
}
@Test
public void testFindMahasiswaId() {
this.session.beginTransaction();
Optional<MahasiswaManyToOneEntity> optional = this.mahasiswaDao.findById("a36b7e84-c41a-4ff0-a693-f0053d7d31c9");
assertTrue("mahasiswa not present!", optional.isPresent());
log.info("mahasiswa: {}", optional.orElse(null));
}
@Test
public void testFindKelasId() {
this.session.beginTransaction();
Optional<KelasEntity> optional = this.kelasDao.findById("5f5e61ea-a46c-4ffe-b05a-8831232b29af");
assertTrue("kelas not present!", optional.isPresent());
KelasEntity kelas = optional.get();
log.info("kelas: {}", kelas);
log.info("list mahasiswa: {}", kelas.getListMahasiswa());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.AlamatEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.MahasiswaOneToManyEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.AlamatEntity;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToManyEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
import java.util.Arrays;
@Slf4j
public class TestMahasiswaOneToManyEntity extends TestCase {
private Session session;
private MahasiswaOneToManyEntityDao mahasiswaDao;
private AlamatEntityDao alamatDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mahasiswaDao = new MahasiswaOneToManyEntityDao(session);
this.alamatDao = new AlamatEntityDao(session);
}
@Test
public void testSaveMahasiswa() {
this.session.beginTransaction();
AlamatEntity rumahDimas = AlamatEntity.builder().provinsi("Jawa Barat")
.kecamatan("Cinunuk")
.kelurahan("Cileunyi")
.kodePos(40526)
.kota("Kab. Bandung")
.namaJalan("Jl Bukit indah B8")
.rt(6)
.rw(18)
.build();
rumahDimas = this.alamatDao.save(rumahDimas);
AlamatEntity rumahDomisili = AlamatEntity.builder().provinsi("Jawa Barat")
.kecamatan("Cinunuk")
.kelurahan("Cileunyi")
.kodePos(40526)
.kota("Kab. Bandung")
.namaJalan("Jl Bukit indah B8 A")
.rt(6)
.rw(18)
.build();
rumahDomisili = this.alamatDao.save(rumahDomisili);
MahasiswaOneToManyEntity dimas = MahasiswaOneToManyEntity.builder()
.nama("Dimas Maryanto")
.nim("10511148")
.tahunMasuk(2011)
.tanggalLahir(LocalDate.of(1993, 3, 1))
.listAlamat(Arrays.asList(rumahDimas, rumahDomisili))
.build();
dimas = this.mahasiswaDao.save(dimas);
log.info("mahasiswa baru: {}", dimas);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.AlamatEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.dao.MahasiswaOneToOneEntityDao;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.AlamatEntity;
import com.maryanto.dimas.bootcamp.example.mapping.jointable.entity.MahasiswaOneToOneEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
import java.time.LocalDate;
@Slf4j
public class TestMahasiswaOneToOneEntityOneToOne extends TestCase {
private Session session;
private MahasiswaOneToOneEntityDao mahasiswaDao;
private AlamatEntityDao alamatDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mahasiswaDao = new MahasiswaOneToOneEntityDao(session);
this.alamatDao = new AlamatEntityDao(session);
}
@Test
public void testSaveMahasiswa() {
this.session.beginTransaction();
AlamatEntity rumahDimas = AlamatEntity.builder().provinsi("Jawa Barat")
.kecamatan("Cinunuk")
.kelurahan("Cileunyi")
.kodePos(40526)
.kota("Kab. Bandung")
.namaJalan("Jl Bukit indah")
.rt(6)
.rw(18)
.build();
rumahDimas = this.alamatDao.save(rumahDimas);
MahasiswaOneToOneEntity dimas = MahasiswaOneToOneEntity.builder()
.nama("Dimas Maryanto")
.nim("10511148")
.tahunMasuk(2011)
.tanggalLahir(LocalDate.of(1993, 3, 1))
.alamat(rumahDimas)
.build();
dimas = this.mahasiswaDao.save(dimas);
log.info("mahasiswa baru: {}", dimas);
this.session.getTransaction().commit();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.inherintance;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao.MobilMappedSuperClassDao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.dao.MotorMappedSuperClassDao;
import com.maryanto.dimas.bootcamp.example.mapping.inherintance.entity.MobilMappedSuperclass;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Optional;
@Ignore
@Slf4j
public class TestMappedSuperClass extends TestCase {
private Session session;
private MobilMappedSuperClassDao mobilDao;
private MotorMappedSuperClassDao motorDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.mobilDao = new MobilMappedSuperClassDao(session);
this.motorDao = new MotorMappedSuperClassDao(session);
}
@Test
public void testSaveMobil() {
MobilMappedSuperclass hondaBrio = MobilMappedSuperclass.builder()
.nama("Honda BRIO")
.allWheelDrive(false)
.cc(1000)
.jumlahCylinder(4)
.jumlahKursi(4)
.jumlahRoda(4)
.namaPabrikan("PT. Honda Motor Company")
.build();
Transaction trx = this.session.beginTransaction();
hondaBrio = this.mobilDao.save(hondaBrio);
trx.commit();
Optional<MobilMappedSuperclass> optional = this.mobilDao.findById(hondaBrio.getId());
assertTrue("mobil is present", optional.isPresent());
hondaBrio = optional.get();
log.info("mobil: {}", hondaBrio);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Test;
@Slf4j
public class TestOpeningConnectionHibernate extends TestCase {
private Session session;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
}
@Test
public void testOpenConnection() {
this.session.beginTransaction();
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.mapping.parentchild;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.dao.EmployeeParentChildDao;
import com.maryanto.dimas.bootcamp.example.mapping.parentchild.entity.EmployeeParentChildEntity;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Optional;
@Slf4j
public class TestParentChildEmployee extends TestCase {
private Session session;
private EmployeeParentChildDao employeeDao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.employeeDao = new EmployeeParentChildDao(session);
}
@Test
public void testSave() {
Transaction trx = this.session.beginTransaction();
EmployeeParentChildEntity manager = EmployeeParentChildEntity.builder()
.name("Hari Sapto Adi")
.job("Chief Technology Officer")
.address("Cicalengka Raya")
.salary(new BigDecimal(10_000_000))
.build();
manager = this.employeeDao.save(manager);
EmployeeParentChildEntity employee1 = EmployeeParentChildEntity.builder()
.name("Dimas Maryanto")
.job("Principal Software Engineer")
.salary(new BigDecimal(3_500_000))
.address("Cinunuk")
.manager(manager)
.build();
employee1 = this.employeeDao.save(employee1);
EmployeeParentChildEntity employee2 = EmployeeParentChildEntity.builder()
.name("Muhamad Yusuf")
.job("Software Engineer")
.salary(new BigDecimal(3_000_000))
.address("Ujung Berung")
.manager(manager)
.build();
employee2 = this.employeeDao.save(employee2);
trx.commit();
}
@Test
public void testFindByIdWithListEmployee() {
this.session.beginTransaction();
Optional<EmployeeParentChildEntity> optional = this.employeeDao.findById("a00c94f9-d9f8-40fe-8007-c325d7ea4bc9");
assertTrue("employee is present", optional.isPresent());
EmployeeParentChildEntity employee = optional.get();
log.info("karyawan: {}", employee);
log.info("daftar karyawan yang pimpin manager {}: \n{}",
employee.getName(), employee.getEmployees());
}
@Test
public void testFindByIdWithManager() {
this.session.beginTransaction();
Optional<EmployeeParentChildEntity> optional = this.employeeDao.findById("a00c94f9-d9f8-40fe-8007-c325d7ea4bc9");
assertTrue("employee is present", optional.isPresent());
EmployeeParentChildEntity employee = optional.get();
log.info("karyawan: {}", employee);
log.info("karyawan dengan nama {} managernya adalah: {}",
employee.getName(), employee.getManager());
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassRoomEmbeddedDao;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.MahasiswaDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.ClassRoomEmbeddedMapping;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.KeyClassRoomEmbeddedId;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.KeyClassRoomIdClass;
import com.maryanto.dimas.bootcamp.example.simple.entity.kampus.Mahasiswa;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Slf4j
@Ignore
public class TestSaveClassRoomEmbedded extends TestCase {
private Session session;
private ClassRoomEmbeddedDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassRoomEmbeddedDao(session);
}
@Test
public void testSaveMahasiswa() {
ClassRoomEmbeddedMapping classRoom = ClassRoomEmbeddedMapping.builder()
.pk(KeyClassRoomEmbeddedId.builder()
.classId("si-ii")
.year(2011)
.build()
).name("SI - II")
.description("System Informasi - II")
.programStudy("IF")
.build();
this.session.beginTransaction();
// save data and then return auto generated id
classRoom = this.dao.save(classRoom);
// commit
this.session.getTransaction().commit();
log.info("classroom saved: {}", classRoom);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test.kampus;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassRoomEmbeddedDao;
import com.maryanto.dimas.bootcamp.example.simple.dao.kampus.ClassRoomIdClassDao;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.ClassRoomEmbeddedMapping;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.embedded.KeyClassRoomEmbeddedId;
import com.maryanto.dimas.bootcamp.example.simple.entity.compose.primarykey.idclass.ClassRoomMappingIdClass;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.Ignore;
import org.junit.Test;
@Slf4j
@Ignore
public class TestSaveClassRoomIdClass extends TestCase {
private Session session;
private ClassRoomIdClassDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new ClassRoomIdClassDao(session);
}
@Test
public void testSaveMahasiswa() {
ClassRoomMappingIdClass classRoom = ClassRoomMappingIdClass.builder()
.classId("si-01")
.year(2011)
.name("SI - II")
.description("System Informasi - II")
.programStudy("IF")
.build();
this.session.beginTransaction();
// save data and then return auto generated id
classRoom = this.dao.save(classRoom);
// commit
this.session.getTransaction().commit();
log.info("classroom saved: {}", classRoom);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.entity.Mahasiswa;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Slf4j
public class TestSaveMahasiswa extends TestCase {
private Session session;
private MahasiswaDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new MahasiswaDao(session);
}
@Test
public void testSaveMahasiswa() {
// init value
Mahasiswa mahasiswa = new Mahasiswa();
mahasiswa.setKode(1L);
mahasiswa.setNim("10511148");
mahasiswa.setNama("Dimas Maryanto");
mahasiswa.setActive(true);
mahasiswa.setCreatedBy("admin");
mahasiswa.setCreatedDate(LocalDateTime.now());
mahasiswa.setTglLahir(LocalDate.of(1999, 9, 9));
mahasiswa.setThnMasuk(2015);
this.session.beginTransaction();
// save data and then return auto generated id
mahasiswa = this.dao.save(mahasiswa);
// commit
this.session.getTransaction().commit();
log.info("mahasiswa saved: {}", mahasiswa);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
package com.maryanto.dimas.bootcamp.test;
import com.maryanto.dimas.bootcamp.example.config.HibernateConfiguration;
import com.maryanto.dimas.bootcamp.example.entity.Mahasiswa;
import junit.framework.TestCase;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Slf4j
public class TestUpdateMahasiswa extends TestCase {
private Session session;
private MahasiswaDao dao;
@Override
protected void setUp() throws Exception {
log.info("init hibernate session");
this.session = HibernateConfiguration.getSession();
this.dao = new MahasiswaDao(session);
}
@Test
public void testUpdateMahasiswa() {
// init value
Mahasiswa mahasiswa = new Mahasiswa();
mahasiswa.setKode(1L);
mahasiswa.setNim("10511150");
mahasiswa.setNama("Dimas Maryanto (updated)");
mahasiswa.setActive(true);
mahasiswa.setCreatedBy("admin");
mahasiswa.setCreatedDate(LocalDateTime.now());
mahasiswa.setTglLahir(LocalDate.of(1999, 9, 9));
mahasiswa.setThnMasuk(2014);
this.session.beginTransaction();
mahasiswa = this.dao.update(mahasiswa);
// commit
this.session.getTransaction().commit();
log.info("mahasiswa was updated: {}", mahasiswa);
}
@Override
protected void tearDown() throws Exception {
log.info("destroy hibernate session!");
this.session.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment