1

Does @JoinTable really create and persist a table named "students_courses" in database? Or it only exists temporarily at run time and disappears after the application is shutdown?

@ManyToMany
@JoinTable(
  name="students_courses",
  joinColumns=@JoinColumn(name="student_id", referencedColumnName="id"),
  inverseJoinColumns=@JoinColumn(name="course_id", referencedColumnName="id"))
private List<Course> courses;
user697911
  • 10,043
  • 25
  • 95
  • 169
  • Do I need to manually create this "students_courses" table, or Hibernate will create it automatically when @JoinTable annotation is used? – user697911 Mar 03 '16 at 22:27

2 Answers2

1

The table must exist in the database, it is not temporary. Hibernate will create it for you if you have it configured to do so, otherwise you will need to create it some other way before this code will work.

digitaljoel
  • 26,265
  • 15
  • 89
  • 115
  • "Hibernate will create it for you if you have it configured to do so", how to configure Hibernate to do so? – user697911 Mar 04 '16 at 00:06
0

In you persistence.xml you must set property hbm2ddl.auto = create. (More information here Hibernate hbm2ddl.auto possible values and what they do?)

BUT be careful with this property. It will recreate you database every time from your entities if you set value "create-drop".

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

<persistence-unit name="NewPersistenceUnit">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <!-- ... other properties ... -->
        <property name="hbm2ddl.auto" value="create"/>
        <!-- ... other properties ... -->
    </properties>
</persistence-unit>

Also you can see this good issue Hibernate: Automatically creating/updating the db tables based on entity classes

Community
  • 1
  • 1
sanluck
  • 1,544
  • 1
  • 12
  • 22