Reputation: 901
How can I save collection of value type in hibernate with annotations - List
of String List<String>
or for example:
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
private Set<History> history;
}
and here is value type:
public class History {
private String someAttribute;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((entry == null) ? 0 : entry.hashCode());
result = prime * result + ((entryDate == null) ? 0 : entryDate.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
History other = (History) obj;
if (entry == null) {
if (other.entry != null)
return false;
} else if (!entry.equals(other.entry))
return false;
if (entryDate == null) {
if (other.entryDate != null)
return false;
} else if (!entryDate.equals(other.entryDate))
return false;
return true;
}
}
Can anyone give some example with hibernate annotations?
Upvotes: 0
Views: 1745
Reputation: 238
For an entity to have collection value type, we need to create a separate table to hold this collection as single row of the entity will have multiple values of for this collection. Use @ElementCollection and @CollectionTable annotations on the collection value attribute.
@ElementCollection
@CollectionTable(name = "STUDENT_HISTORY", joinColumns = {@JoinColumn(name = STUDENT_ID) })
@Column(name="HISTORY")
private Set<History> history;
The table will hold the collection values in the column HISTORY and uses STUDENT_ID column as the join column which will be the foreign key to the ID of student.
Below is a complete example using native Hibernate (I mean without the JPA):
Student.java
package domain.app.data;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
@Entity
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ElementCollection
@CollectionTable(name="STUDENT_HISTORY", joinColumns={@JoinColumn(name="STUDENT_ID", referencedColumnName="ID")})
@Column(name="HISTORY")
private Set<History> history = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<History> getHistory() {
return history;
}
public void setHistory(Set<History> history) {
this.history = history;
}
@Override
public String toString() {
return "Student [id=" + id + ", history=" + history + "]";
}
}
History.java
package domain.app.data;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class History {
@Column(name="HISTORY")
private String someAttribute;
public String getSomeAttribute() {
return someAttribute;
}
public void setSomeAttribute(String someAttribute) {
this.someAttribute = someAttribute;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((someAttribute == null) ? 0 : someAttribute.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
History other = (History) obj;
if (someAttribute == null) {
if (other.someAttribute != null)
return false;
} else if (!someAttribute.equals(other.someAttribute))
return false;
return true;
}
}
HibernateUtil.java
package domain.app.data.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import domain.app.data.Student;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().build();
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Student.class);
return configuration.buildSessionFactory(serviceRegistry);
}
public static SessionFactory getSession() {
return sessionFactory;
}
}
Application.java
package domain.app;
import org.hibernate.Session;
import domain.app.data.History;
import domain.app.data.Student;
import domain.app.data.util.HibernateUtil;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSession().openSession();
session.getTransaction().begin();
Student student = new Student();
History history1 = new History();
history1.setSomeAttribute("Volunteer since 2016");
History history2 = new History();
history2.setSomeAttribute("Football team member");
student.getHistory().add(history1);
student.getHistory().add(history2);
session.save(student);
session.getTransaction().commit();
session.close();
}
}
hibernate.properties
hibernate.connection.username=admin
hibernate.connection.password=password
hibernate.connection.url=jdbc:h2:~/h2db/test
hibernate.connection.driver_class=org.h2.Driver
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration debug="false" scan="true" scanPeriod="30 minutes">
<appender name="Console-Appender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%gray(%d{yyyy-MM-dd HH:mm:ss.SSS}) %highlight(%5p) %gray(---) %magenta([%15.15t]) %cyan(%-40.40c{1}) %black(:) %m%n%xEx</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="Console-Appender" />
</root>
</configuration>
pom.xml
<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>stackoverflow</groupId>
<artifactId>SO-41248001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.5.Final</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
</project>
Project Structure:
Result in DB:
Upvotes: 2
Reputation: 1802
try this it should work.
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@ElementCollection
private Collection Set<History> history;
}
@Embeddable
public class History {
private String someAttribute;
......
}
Upvotes: 1