4

Is in hibernate something like code first approach from Entity Framework? I am trying to prepare database tables from java classes (MySQL). I have already prepared java classes with JPA annotations, but I am not sure what to do now (I am using IntelliJ). What should I have in my main to create thoose tables? Or should I use some tools?

One of my classes looks like this:

@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; }
}
Matt Mcdon
  • 185
  • 1
  • 1
  • 13
  • possible duplicate of [Does Hibernate create tables in the database automatically](http://stackoverflow.com/questions/4507142/does-hibernate-create-tables-in-the-database-automatically) – Xstian Nov 04 '14 at 10:10

4 Answers4

2

You need to set the hibernate.hbm2ddl.auto property with value create. If so, when you run the applications first time, the tables will be created.

siva636
  • 16,109
  • 23
  • 97
  • 135
2

In hibernate.cfg.xml configuration file you can set a property called hbm2ddl.auto that tells hibernate to create a table for you:

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

When you run your application for the first time then you can set the property to create and later you can change it to update.

Follow this link for more details:

Hibernate hbm2ddl.auto possible values and what they do?

Community
  • 1
  • 1
Chaitanya
  • 15,403
  • 35
  • 96
  • 137
1

For clarification: I was using JPA2, so configuration was in persistence.xml. What worked for me was setting:

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

without "hibernate." it was not working.

Also to start it I needed to prepare main function with creating EntityManager, because mapping to db happens when it is created:

public static void main(String [] args){
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("NewPersistenceUnit"); //name of persistence unit here
    EntityManager entityManager = factory.createEntityManager();
}
Matt Mcdon
  • 185
  • 1
  • 1
  • 13
0
@OneToMany(mappedBy = "")
@Fetch(value = FetchMode.SUBSELECT)

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

In my case, I have mentioned the same OneToMany relationship two times in a master table. Because I have two relationships. I have used @Fetch(value = FetchMode.SUBSELECT) in two relationships. This is working for me fine.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Thamil
  • 1