在休眠中保存值类型集合 [英] save value type collection in hibernate

查看:47
本文介绍了在休眠中保存值类型集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在休眠状态下使用注释保存值类型的集合-字符串 List< String> List 或例如:

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

这是值类型:

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?

推荐答案

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

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;

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

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.

以下是使用本地Hibernate的完整示例(我的意思是没有JPA):

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>

项目结构:

数据库结果:

这篇关于在休眠中保存值类型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆