W
W
woodhead2019-03-15 14:22:01
Java
woodhead, 2019-03-15 14:22:01

How to map an entity to multiple tables in Hibernate?

I'm trying to map an entity Studentto multiple tables: students, addresses, hobbies. The keys in tables addressesand hobbiesare also foreign and refer to the table 's primary key students. That is, the main table students, and the rest - auxiliary. Here are the class descriptions:
Student

package entity;    
import javax.persistence.*;

@Entity
@Table(name = "students")
@SecondaryTables({
        @SecondaryTable(name = "hobbies"),
        @SecondaryTable(name = "addresses"),
})
public class Student {
    @Id
    @Column(name = "student_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Column(table = "hobbies")
    private String hobby;

    @Column(table = "addresses")
    @Embedded
    private Address address;

    public Student(){}

    public Student(String name, String hobby, Address address){
        this.name = name;
        this.hobby = hobby;
        this.address = address;
    }
}

address
package entity;    
import javax.persistence.*;

@Embeddable
public class Address {

    @Column(name="street")
    private String street;

    public Address(){}

    public Address(String street){
        this.street = street;
    }
}

As a result, the String hobbyclass field Studentis displayed in a separate table hobbieswithout problems, but the Address addressdisplay fails. That is, the table addressesis created, and the foreign key is registered in it, but the data is not received (the table is empty). In addition, addressesthere is only one field in the table - student_id, and streetfor some reason the field is missing.
The data is created like this:
public static void main(String[] args) {
    StudentService service = new StudentService();
    try {
        Student student = service.create(
                new Student("Вася", "Лыжи", new Address("ул. Ленина"))
        );
        Student student2 = service.create(
                new Student("Петя", "Хоккей", new Address("ул. Фрунзе"))
        );
    } catch (DBException e){
        System.out.println("что-то пошло не так");
    }
    DBService.close();
}

This is the service layer:
package service;

import dao.*;
import exception.DBException;
import entity.Student;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import javax.persistence.NoResultException;

public class StudentService {

    public StudentService(){}

    public Student create(Student student) throws DBException {
        Transaction transaction = DBService.getTransaction();
        try {
            StudentDao studentDao = DaoFactory.getStudentDao();
            Long studentId = studentDao.create(student);
            student = studentDao.get(studentId);
            transaction.commit();
            return student;
        } catch (HibernateException | NoResultException | NullPointerException e) {
            DBService.transactionRollback(transaction);
            throw new DBException(e);
        }
    }
}

Why is the table addressesempty and how to make it so that it has the correct structure (there was a field street) and it is filled with data? There are no warnings or errors when executing (but there are no requests to insert data into the table addresses):
Hibernate: drop table addresses if exists
Hibernate: drop table hobbies if exists
Hibernate: drop table students if exists
Hibernate: create table addresses (student_id bigint not null, primary key (student_id))
Hibernate: create table hobbies (hobby varchar(255), student_id bigint not null, primary key (student_id))
Hibernate: create table students (student_id bigint generated by default as identity, street varchar(255), name varchar(255), primary key (student_id))
Hibernate: alter table addresses add constraint FKqq1nt3g94upydb2qt72xhnk7y foreign key (student_id) references students
Hibernate: alter table hobbies add constraint FKmcdfc4qw94xl2a8ak5kct6rys foreign key (student_id) references students
мар 15, 2019 5:43:34 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hiber[email protected]3d9f6567'
Hibernate: insert into students (student_id, street, name) values (null, ?, ?)
мар 15, 2019 5:43:34 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:./h2db]
Hibernate: insert into hobbies (hobby, student_id) values (?, ?)
Hibernate: select student_id from students where student_id =? for update
Hibernate: insert into students (student_id, street, name) values (null, ?, ?)
Hibernate: insert into hobbies (hobby, student_id) values (?, ?)
Hibernate: select student_id from students where student_id =? for update

Process finished with exit code 0

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yurii Nekrasov, 2019-03-21
@driversti

As far as I know, @Embedded indicates that this object will be stored in the parent table (at least in my project). That is, the street column will be located in the students table and will be filled in there. Check the data in the students table

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question