简体   繁体   English

如何使用Hibernate保存复杂对象?

[英]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 我也有Java课程

@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 是否可以像这样保存(使用Hibernate Session的save()方法)Catalog对象

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

without writing SQL? 没有写SQL? And what I need to do with Genre and Type? 我需要做什么类型和类型? Should I set id of both instances? 我应该设置两个实例的ID吗?

UPD: 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) . 当然,您可以使用persist(Object obj)将生成的Object保存在数据库中。 Well, you should test the function in a JUnit Test. 那么,您应该在JUnit测试中测试该函数。 In the business code it should do your DAO. 在商业代码中,它应该做你的DAO。 No, all the Ids are generated, you don't need to set the id. 不,生成了所有ID,您不需要设置ID。 It is managed by Hibernate. 它由Hibernate管理。 For your example the UnitTest should look like: 对于您的示例,UnitTest应如下所示:

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) (当然你必须从EntityManagerFactory重命名PersistenceUnit测试。它应该与persistence.xml中命名的PersistenceUnit匹配)

Other interesting lecture: 其他有趣的讲座:

Hiberante Session Doc Hiberante会议文件

Small example (GitHub) 小例子(GitHub)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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