从实体创建数据库表

时间:2014-11-03 23:14:52

标签: java mysql hibernate jpa orm

在实体框架中是否处于类似代码的第​​一种方法? 我正在尝试从java类(MySQL)准备数据库表。我已经用JPA注释编写了java类,但我不知道现在要做什么(我使用的是IntelliJ)。在我的主要内容中我应该创建什么样的桌子?或者我应该使用一些工具吗?

我的一个课程看起来像这样:

@Entity
public class Item {

    @Id
    @GeneratedValue
    private long id;

    @Column
    private String text;

    @ManyToMany(mappedBy = "items")
    private Set<Container> containers = new HashSet<Container>();

    public long getId() {
        return id;
    }

    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }

    public Set<Container> getContainers() { return containers; }
}

4 个答案:

答案 0 :(得分:2)

您需要将hibernate.hbm2ddl.auto属性设置为值create。如果是这样,当您第一次运行应用程序时,将创建表。

答案 1 :(得分:2)

在hibernate.cfg.xml配置文件中,您可以设置一个名为hbm2ddl.auto的属性,告诉hibernate为您创建一个表:

<property name="hbm2ddl.auto">create</property>

首次运行应用程序时,您可以将属性设置为create,稍后您可以将其更改为update

请点击此链接了解更多详情:

Hibernate hbm2ddl.auto possible values and what they do?

答案 2 :(得分:0)

为了澄清:我使用的是JPA2,因此配置在 persistence.xml 中。对我有用的是:

<property name="hibernate.hbm2ddl.auto">create</property>

没有“休眠。”它没有用。

同样要启动它,我需要通过创建EntityManager来准备main函数,因为在创建它时会发生映射到db:

public static void main(String [] args){
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("NewPersistenceUnit"); //name of persistence unit here
    EntityManager entityManager = factory.createEntityManager();
}

答案 3 :(得分:0)

@OneToMany(mappedBy = "")
@Fetch(value = FetchMode.SUBSELECT)

@OneToMany(mappedBy = "")
@Fetch(value = FetchMode.SUBSELECT)

就我而言,我在主表中两次提到相同的OneToMany关系。因为我有两个关系。我在两种关系中使用过@Fetch(value = FetchMode.SUBSELECT)。这对我来说很好。