hibernate identifiers examples (#2977)

* hibernate identifiers examples

* fix conflict

* change to longstream

* change to format
This commit is contained in:
Loredana Crusoveanu 2017-11-10 13:33:52 +02:00 committed by Grzegorz Piwowarek
parent cfd3def015
commit c9aaa0d993
12 changed files with 414 additions and 0 deletions

View File

@ -2,8 +2,17 @@ package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.User;
import com.baeldung.hibernate.pojo.UserProfile;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
@ -33,6 +42,14 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Phone.class);
metadataSources.addAnnotatedClass(EntityDescription.class);
metadataSources.addAnnotatedClass(TemporalValues.class);
metadataSources.addAnnotatedClass(User.class);
metadataSources.addAnnotatedClass(Student.class);
metadataSources.addAnnotatedClass(Course.class);
metadataSources.addAnnotatedClass(Product.class);
metadataSources.addAnnotatedClass(OrderEntryPK.class);
metadataSources.addAnnotatedClass(OrderEntry.class);
metadataSources.addAnnotatedClass(OrderEntryIdClass.class);
metadataSources.addAnnotatedClass(UserProfile.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()

View File

@ -0,0 +1,27 @@
package com.baeldung.hibernate.pojo;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Course {
@Id
@GeneratedValue
private UUID courseId;
public UUID getCourseId() {
return courseId;
}
public void setCourseId(UUID courseId) {
this.courseId = courseId;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator="table-generator")
@TableGenerator (name="table-generator", table="dep_ids", pkColumnName="seq_id", valueColumnName="seq_value")
private long depId;
public long getDepId() {
return depId;
}
public void setDepId(long depId) {
this.depId = depId;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
@Entity
public class OrderEntry {
@EmbeddedId
private OrderEntryPK entryId;
public OrderEntryPK getEntryId() {
return entryId;
}
public void setEntryId(OrderEntryPK entryId) {
this.entryId = entryId;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
@Entity
@IdClass(OrderEntryPK.class)
public class OrderEntryIdClass {
@Id
private long orderId;
@Id
private long productId;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.hibernate.pojo;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Embeddable;
@Embeddable
public class OrderEntryPK implements Serializable {
private long orderId;
private long productId;
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderEntryPK pk = (OrderEntryPK) o;
return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
public class Product {
@Id
@GeneratedValue(generator = "prod-generator")
@GenericGenerator(name = "prod-generator", parameters = @Parameter(name = "prefix", value = "prod"), strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator")
private String prodId;
public String getProdId() {
return prodId;
}
public void setProdId(String prodId) {
this.prodId = prodId;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue (strategy = GenerationType.SEQUENCE)
private long studentId;
public long getStudentId() {
return studentId;
}
public void setStudent_id(long studentId) {
this.studentId = studentId;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence-generator")
@SequenceGenerator(name = "sequence-generator", sequenceName = "user_sequence", initialValue = 4)
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
@Entity
public class UserProfile {
@Id
private long profileId;
@OneToOne
@MapsId
private User user;
public long getProfileId() {
return profileId;
}
public void setProfileId(long profileId) {
this.profileId = profileId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.hibernate.pojo.generator;
import java.io.Serializable;
import java.util.Properties;
import java.util.stream.Stream;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
public class MyGenerator implements IdentifierGenerator, Configurable {
private String prefix;
@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
String query = String.format("select %s from %s",
session.getEntityPersister(obj.getClass().getName(), obj).getIdentifierPropertyName(),
obj.getClass().getSimpleName());
Stream<String> ids = session.createQuery(query).stream();
Long max = ids.map(o -> o.replace(prefix + "-", ""))
.mapToLong(Long::parseLong)
.max()
.orElse(0L);
return prefix + "-" + (max + 1);
}
@Override
public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
prefix = properties.getProperty("prefix");
}
}

View File

@ -0,0 +1,100 @@
package com.baeldung.hibernate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.hibernate.Transaction;
import java.io.IOException;
import org.hibernate.Session;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Course;
import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.Student;
import com.baeldung.hibernate.pojo.User;
import com.baeldung.hibernate.pojo.UserProfile;
public class IdentifiersIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory()
.openSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void whenSaveSimpleIdEntities_thenOk() {
Student student = new Student();
session.save(student);
User user = new User();
session.save(user);
assertThat(student.getStudentId()).isEqualTo(1L);
assertThat(user.getUserId()).isEqualTo(4L);
Course course = new Course();
session.save(course);
}
@Test
public void whenSaveCustomGeneratedId_thenOk() {
Product product = new Product();
session.save(product);
Product product2 = new Product();
session.save(product2);
assertThat(product2.getProdId()).isEqualTo("prod-2");
}
@Test
public void whenSaveCompositeIdEntity_thenOk() {
OrderEntryPK entryPK = new OrderEntryPK();
entryPK.setOrderId(1L);
entryPK.setProductId(30L);
OrderEntry entry = new OrderEntry();
entry.setEntryId(entryPK);
session.save(entry);
assertThat(entry.getEntryId()
.getOrderId()).isEqualTo(1L);
}
@Test
public void whenSaveIdClassEntity_thenOk() {
OrderEntryIdClass entry = new OrderEntryIdClass();
entry.setOrderId(1L);
entry.setProductId(30L);
session.save(entry);
assertThat(entry.getOrderId()).isEqualTo(1L);
}
@Test
public void whenSaveDerivedIdEntity_thenOk() {
User user = new User();
session.save(user);
UserProfile profile = new UserProfile();
profile.setUser(user);
session.save(profile);
assertThat(profile.getProfileId()).isEqualTo(user.getUserId());
}
}