在hibernate中保存值类型集合

时间:2016-12-20 17:24:56

标签: java hibernate collections

如何使用注释 - List的字符串List<String>来保存hibernate中的值类型集合,例如:

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id; 
      private Set<History> history;
}

这里是值类型:

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;
}
}

任何人都可以举例说明hibernate注释吗?

2 个答案:

答案 0 :(得分:1)

对于具有集合值类型的实体,我们需要创建一个单独的表来保存此集合,因为该实体的单行将具有此集合的多个值。在集合值属性上使用@ElementCollection和@CollectionTable注释。

@ElementCollection
@CollectionTable(name = "STUDENT_HISTORY", joinColumns = {@JoinColumn(name = STUDENT_ID) }) 
@Column(name="HISTORY") 
private Set<History> history;

该表将在HISTORY列中保存集合值,并使用STUDENT_ID列作为连接列,该列将是学生ID的外键。

以下是使用原生Hibernate的完整示例(我的意思是没有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>

项目结构:

enter image description here

DB中的结果:

enter image description here

enter image description here

答案 1 :(得分:1)

试试这个应该有效。

@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;

......

}