简体   繁体   中英

How to save complex objects using Hibernate?

I have three table:

CREATE TABLE catalog (
    id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    type_id INT,
    genre_id INT,
    product_name VARCHAR(100),
    FOREIGN KEY ( genre_id ) REFERENCES genres ( genre_id ),
    FOREIGN KEY ( type_id ) REFERENCES types ( type_id )
);

CREATE TABLE genres (
    genre_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    genre_name VARCHAR(50)
);

CREATE TABLE types (
    type_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
    type_name VARCHAR(50)
);

Also I have Java classes

@Entity
@Table(name = "catalog", catalog = "media_store_db")
public class Catalog implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "product_name", length = 100)
    private String productName;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name = "genre_id", referencedColumnName = "genre_id")
    private Genre genre;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name = "type_id", referencedColumnName = "type_id")
    private Type type;


@Entity
@Table(name = "genres", catalog = "media_store_db")
public class Genre implements Serializable {

    @Id
    @Column(name = "genre_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

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

@Entity
@Table(name = "types", catalog = "media_store_db")
public class Type implements Serializable {

    @Id
    @Column(name = "type_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

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

Is it possible to save (using save() method of Hibernate Session) Catalog object like this

Catalog catalog = new Catalog();
catalog.setProductName("Product");
catalog.setGenre(new Genre());
catalog.setType(new Type());
save(catalog);

without writing SQL? And what I need to do with Genre and Type? Should I set id of both instances?

UPD:

This code works just fine

Catalog catalog = new Catalog();
catalog.setProductName("12 Years a Slave");
catalog.setGenre(genreRepository.get(Long.valueOf(1)));
catalog.setType(typeRepository.get(Long.valueOf(1)));
Session session = cfg.getSession();
Transaction tx = session.beginTransaction();
session.save(catalog);
tx.commit();
session.close();

Sure, you can persist the generated Object in the database using persist(Object obj) . Well, you should test the function in a JUnit Test. In the business code it should do your DAO. No, all the Ids are generated, you don't need to set the id. It is managed by Hibernate. For your example the UnitTest should look like:

public class DataGenerationTest {

private EntityManager em;

@Before 
public void init(){
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    em = emf.createEntityManager();
}

@Test
public void shouldAddSomeCatalogs(){
em.getTransaction().begin();

Catalog catalog = new Catalog();
catalog.setProductName("Proguct");
catalog.setGenre(new Genre());
catalog.setType(new Type());
em.persist(catalog);
    em.getTransaction().commit();
    em.close();
}
}

(Sure you have to rename the PersistenceUnit test from the EntityManagerFactory. It should match your named PersistenceUnit in the persistence.xml)

Other interesting lecture:

Hiberante Session Doc

Small example (GitHub)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM