One To Many
One To Many
java
package com.jpa;
import java.util.List;
import javax.persistence.*;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int s_id;
private String s_name;
@OneToMany
private List<Library> libs;
public Student() {
super();
}
public Student(int s_id, String s_name, List<Library> libs) {
super();
this.s_id = s_id;
this.s_name = s_name;
this.libs = libs;
}
Library.java
package com.jpa;
import javax.persistence.*;
//Example for ONE TO MANY
@Entity
public class Library {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int b_id;
private String b_name;
@ManyToOne
private Student stud;
public Library() {
super();
// TODO Auto-generated constructor stub
}
OnetoMany.java
package com.jpa;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.hibernate.Session;
em.getTransaction().begin();
em.persist(lib1);
em.persist(lib2);
em.persist(lib3);
st1.setLibs(list);
// st2.setLibs(list);
em.persist(st1);
em.getTransaction().commit();
Persistence.xml
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persi
stence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2
_1.xsd">
<persistence-unit name="Book">
<provider>org.hibernate.jpa.HibernatePersistenceProvi
der</provider>
<class>com.jpa.Student</class>
<class>com.jpa.Library</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/jpadb"/>
<property name="javax.persistence.jdbc.user"
value="root"/>
<property
name="javax.persistence.jdbc.password"
value="admin"/>
<property name="hibernate.show_sql"
value="true" />
<property name="hibernate.format_sql"
value="true" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
</persistence-unit>
</persistence>