Hibernate Batch Processing insert 1000000 records - java

When I am trying to insert 1000000 records in MySQL DB, I really have only 1000. What is wrong?
This is my hibernate.cfg.xml
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3307/hibernatedb
root
bervol13
1
50
org.hibernate.dialect.MySQLDialect
thread
org.hibernate.cache.NoCacheProvider</property> -->
false
org.hibernate.cache.EhCacheProvider
true
update
This is my Student:
package ua.berchik.vovchuk.dto;
import java.io.Serializable;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Cacheable
#Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
#Entity
#Table(name="STUDENT")
public class Student implements Serializable {
private static final long serialVersionUID = -6853928080190944025L;
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="STUDENT_NAME")
private String studName;
#Column(name="ROLE_NUMBER")
private int rollNumb;
#Column(name="COURSE")
private String course;
public Student(){}
public Student(String studName, int rollNumb, String course) {
super();
this.studName = studName;
this.rollNumb = rollNumb;
this.course = course;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudName() {
return studName;
}
public void setStudName(String studName) {
this.studName = studName;
}
public int getRollNumb() {
return rollNumb;
}
public void setRollNumb(int rollNumb) {
this.rollNumb = rollNumb;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String toString()
{
return "Id: "+this.id+" ROLL Number: "+this.rollNumb+"| Name: "+this.studName+"| Course: "+this.course;
}
}
This is my HibernateUtil:
package ua.berchik.vovchuk.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.common.annotationfactory.AnnotationFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static{
try{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch(Throwable th){
System.err.println("Initial SessionFactory creation failed"+th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
And this is my Main:
package ua.berchik.vovchuk.hibernate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.crypto.Data;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import ua.berchik.vovchuk.dto.FourWheeler;
import ua.berchik.vovchuk.dto.Student;
import ua.berchik.vovchuk.dto.TwoWheeler;
import ua.berchik.vovchuk.dto.User;
import ua.berchik.vovchuk.dto.UserDetails;
import ua.berchik.vovchuk.dto.Vehicle;
import ua.berchik.vovchuk.hibernate.util.HibernateUtil;
public class HiernateTest {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
for ( int i=0; i<1000000; i++ )
{
Student student = new Student("Name "+i, i, "Course "+i);
session.save(student);
if(i%50 == 0){
session.flush();
session.clear();
}
}
session.getTransaction().commit();
session.close();
}
}

Related

how to find students Bydate (findByDate)

I went to develop an application to manage students in a university, I am looking for how to find students in relation to a date entered for that I have developed the following code lines:
1- Model student.java
package com.avatar.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.JoinColumn;
#Entity
#Table(name = "Students")
public class Student{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String prenom;
private String numTel;
private String mail;
#Temporal(TemporalType.DATE)
private Date dateCurrent;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "student_techno",
joinColumns = { #JoinColumn(name = "student_id") },
inverseJoinColumns = { #JoinColumn(name = "techno_id") })
private Set<Techno> techno = new HashSet<>();
public Student() {
}
#SuppressWarnings("unchecked")
public Student(String nom, String prenom,String numTel, String mail, Date dateCurrent,
) {
super();
this.nom = nom;
this.prenom = prenom;
this.numTel = numTel;
this.mail = mail;
this.dateCurrent = dateCurrent;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNumTel() {
return numTel;
}
public void setNumTel(String numTel) {
this.numTel = numTel;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getdateCurrent() {
return dateCurrent;
}
public void setdateCurrent(Date dateCurrent) {
this.dateCurrent = dateCurrent;
}
#Override
public String toString() {
return "Student[nom=" + nom + ", prenom=" + prenom + ", numTel=" + numTel + ", mail="
+ mail + ", dateCurrent=" + dateCurrent+ "]";
}
}
2- Controller
package com.avatar.web;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.avatar.dao.StudentDao;
import com.avatar.model.Student;
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class StudentController {
#Autowired
StudentDao studentdao;
#GetMapping(value = "/all-students")
public List<Student> listeDesStudent() {
List<Student> students= studentdao.findAll();
if (students.isEmpty())
throw new ProductNotFoundException("No student is registered in the database");
return students;
}
#GetMapping(value = "/all-students/dateCurrent/{dateCurrent}")
public List<Student> viewStudent(#PathVariable("dateCurrent") #DateTimeFormat(pattern = "yyyy-MM-dd") Date dateCurrent) {
Calendar c = Calendar.getInstance();
c.setTime(dateCurrent);
c.add(Calendar.DATE, 1);
dateCurrent = c.getTime();
return studentdao.findByDate(dateCurrent);
}
#GetMapping(value = "/all-students /techno/{nomTechno}")
List<Student > viewStudent(#PathVariable("nomTechno") String nomTechno) {
return studentdao.findDistinctByTechnoNomTechno(nomTechno);
}
#PostMapping(value = "/add-student")
public Student addStudent(#RequestBody Student student) {
Student studentAdded= studentdao.save(Student);
return studentAdded;
}
}
3- DAO
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDate(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
4- applications.properties
server.port= 8080
# MySQL Properties
spring.jpa.show-sql = true
spring.datasource.url= jdbc:mysql://localhost:3306/avatar?serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=*****
spring.datasource.password=*****
# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
in my console i have:
Failed to create query for method public abstract java.util.List com.avatar.dao.StudentDao.findByDate(java.util.Date)! No property date found for type Student!
Please update DAO as per for below mentioned changes
If the field name is dateCurrent then findByDateCurrent.
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDateCurrent(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
You are missing field name, in Entity class it is not the date by dateCurrent, thus your JPA should be findByDateCurrent

Hibernate Exception:Could not execute statement, com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USERID' in 'field list'

package hibernate2;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="User1_Details")
public class UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;
#OneToMany(mappedBy="user")
private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Collection<Vehicle> getVehicle() {
return vehicle;
}
public void setVehicle(Collection<Vehicle> vehicle) {
this.vehicle = vehicle;
}
}
And i created a vehicle class
package hibernate2;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Vehicle {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int vehicle_Id;
private String vehicle_Name;
#ManyToOne
#JoinColumn(name="USER_ID")
private UserDetails user;
public UserDetails getUser() {
return user;
}
public void setUser(UserDetails user) {
this.user = user;
}
public int getVehicle_Id() {
return vehicle_Id;
}
public void setVehicle_Id(int vehicle_Id) {
this.vehicle_Id = vehicle_Id;
}
public String getVehicle_Name() {
return vehicle_Name;
}
public void setVehicle_Name(String vehicle_Name) {
this.vehicle_Name = vehicle_Name;
}
}
And The Following were my hiernate code or DAO class
package hibernate2;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Hibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserName("Ranjith");
Vehicle vehicle = new Vehicle();
vehicle.setVehicle_Name("Car");
Vehicle vehicle2 = new Vehicle();
vehicle2.setVehicle_Name("Jeep");
user.getVehicle().add(vehicle);
user.getVehicle().add(vehicle2);
vehicle.setUser(user);
vehicle2.setUser(user);
SessionFactory sessionfactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(user);
session.save(vehicle);
session.save(vehicle2);
session.getTransaction().commit();
session.close();
}
}
After Running this above class i get the following error
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USER_ID' in 'field list'

Getting Exception in thread "main" java.lang.NullPointerException for my hibernate program

Here is my StudentDetails class:
package com.gontuseries.hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="STUDENT_DETAILS")
public class StudentDetails {
#Id #GeneratedValue( generator= "newGenerator")
#GenericGenerator(name="newGenerator",strategy = "foreign", parameters = {
#Parameter(name="property",value="Student_Info")})
private int rollNo;
private int mobile_no;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name ="rollNo")
private Student_Info student=new Student_Info();
public Student_Info getStudent() {
return student;
}
public void setStudent(Student_Info student) {
this.student = student;
}
public int getMobile_no() {
return mobile_no;
}
public void setMobile_no(int mobile_no) {
this.mobile_no = mobile_no;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
Here is my Main class :
package com.gontuseries.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.*;
public class Main {
public static void main(String[] args)
{
Student_Info student=new Student_Info();
student.setName("Gontu_Rajesh");
StudentDetails sd=new StudentDetails();
sd.setMobile_no(455656);
sd.setStudent(student);
// student.setRollNo(3);
//Student_Info student2=new Student_Info();
//student2.setName("Gontu_Rajesh_new name");
SessionFactory sessionFactory= new
Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(sd);
//session.save(student2);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
And here is my Student_Info class :
package com.gontuseries.hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="STUDENT_INFORMATION")
public class Student_Info {
#Id #GeneratedValue(strategy = GenerationType.SEQUENCE)
private int rollNo;
private String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
After running Main class I am getting:
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:645)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4725)
at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:81)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:691)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:683)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:678)
at com.gontuseries.hibernate.Main.main(Main.java:26)
Any help would be appreciated.
You probably have the same/similar problem with this post:
java.lang.NullPointerException at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:521)
Try replacing this:
#GenericGenerator(name="newGenerator",strategy = "foreign", parameters = {
#Parameter(name="property",value="Student_Info")})
with this:
#GenericGenerator(name="newGenerator",strategy = "foreign", parameters = {
#Parameter(name="property",value="student")})
When using foreign strategy, remember to use the property name instead of the Entity name. The value should have been student instead of Student_Info.

Hibernate Can not insert joined table

I am working on hibernate. I have two entities: Project and Contact. These two entities have a one-to-many relationship. But, when I save a Project class, hibernate does not insert any record in Contact table(class) and just updates the Project table.
The business is;
There are lots of Projects. User select a project with double click which opens new jsp(got project id on that) and entering contact info and push Add button. What I am trying to do is the project that user selected is on db already. There is ok but I want to insert contact table with my contact info which include project_id. I am expecting from hibernate is update project table also insert contact table. But now reality is just updating project table only.
Here is structure of my classes: the main controller is Contact Controller.
Project.java:
package Model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="xxer_Projects_t")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int project_id;
#Column(name = "Project_number")
private String Project_number;
#Column(name = "Project_name")
private String Project_name;
#ManyToOne(fetch=FetchType.EAGER,cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
#JoinColumn(name = "constructor_id")
private Constructor constructor;
#OneToMany(fetch=FetchType.EAGER,mappedBy = "project",
cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
private List<Contact> contacts;
#OneToMany(fetch=FetchType.EAGER,mappedBy = "project",
cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
public List<Contact> getContacts() {
return contacts;
}
#OneToMany(fetch=FetchType.EAGER,mappedBy = "project",
cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public Project() {
// TODO Auto-generated constructor stub
}
public Project(String project_number, String project_name) {
Project_number = project_number;
Project_name = project_name;
}
public int getProject_id() {
return project_id;
}
public void setProject_id(int project_id) {
this.project_id = project_id;
}
public String getProject_number() {
return Project_number;
}
public void setProject_number(String project_number) {
Project_number = project_number;
}
public String getProject_name() {
return Project_name;
}
public void setProject_name(String project_name) {
Project_name = project_name;
}
public Constructor getConstructor() {
return constructor;
}
public void setConstructor(Constructor constructor) {
this.constructor = constructor;
}
}
Contact.java:
package Model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="xxer_contacts_t")
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name_surname;
private String email;
private String phone;
#ManyToOne(fetch=FetchType.EAGER,cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
#JoinColumn(name = "project_id")
private Project project;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName_surname() {
return name_surname;
}
public void setName_surname(String name_surname) {
this.name_surname = name_surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Project getProject_id() {
return project;
}
public void setProject_id(Project project_id) {
this.project = project_id;
}
public Contact() {
}
}
ContactController.java:
package Controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Dao.ConstructorDao;
import Dao.ContactDao;
import Dao.ProjectDao;
import Model.Constructor;
import Model.Contact;
import Model.Project;
/**
* Servlet implementation class ContactController
*/
#WebServlet("/ContactController")
public class ContactController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ContactController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int projectid = Integer.parseInt(request.getParameter("id"));
if (request.getParameter("Operation").equals("add")) {
String name = request.getParameter("NameSurname");
String email = request.getParameter("Email");
String phone = request.getParameter("Phone");
Project p = ProjectDao.getProjectById (projectid);
List <Contact> loc = new ArrayList<>();
Contact cont = new Contact();
cont.setName_surname(name);
cont.setEmail(email);
cont.setPhone(phone);
cont.setProject_id(p);
loc.add(cont);
p.setContacts(loc);
ProjectDao.insert(p);
/*
cont.setName_surname(name);
cont.setEmail(email);
cont.setPhone(phone);
cont.setProject_id(p);
ContactDao.Insert(cont);
*/
}
// List
List<Contact> ListOfContacts =ContactDao.getListofContacts(projectid);
request.setAttribute("ListOfContacts", ListOfContacts);
request.setAttribute("id", projectid);
RequestDispatcher dispacher = request.getRequestDispatcher("/ProjectContacts.jsp");
dispacher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
ProjectDao.java:
package Dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import Model.Constructor;
import Model.OfferType;
import Model.Project;
import _JSP.HibernateUtil;
public class ProjectDao {
public ProjectDao() {
// TODO Auto-generated constructor stub
}
/*
public static void main(String[] args) {
int id = 1;
Project p = new Project ("Proje3","TRIA Projesi");
insert(p);
}
*/
public static void insert(Project p) {
SessionFactory sf =HibernateUtil.getSessionFactory();
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
try {
session.beginTransaction();
//Constructor con = session.get(Constructor.class, consid);
//p.setConstructor(con);
//session.save(p);
//session.persist(p);
session.saveOrUpdate(p);
session.getTransaction().commit();
}
finally {
session.close();
System.out.println("Project Session Closed!!!!");
}
}
public static List<Project> getListofProjects() {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf =HibernateUtil.getSessionFactory();
Session session = sf.openSession();
//List <OfferType> ol = session.createCriteria(OfferType.class).list();
List <Project> ol =session.createQuery("from Project order by 1 desc").list();
session.close();
return ol;
}
public static Project getProjectById(int id) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
//List <OfferType> ol = session.createCriteria(OfferType.class).list();
Project p =session.get(Project.class,id);
session.close();
return p;
}
public static List<Constructor> LoadConsDropDown() {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
List <Constructor> listofcons = new ArrayList<Constructor>();
listofcons = session.createQuery("from Constructor order by name asc").list();
session.close();
return listofcons;
}
}
ContactDao.java:
package Dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import Model.Contact;
import Model.Project;
import _JSP.HibernateUtil;
public class ContactDao {
public ContactDao() {
// TODO Auto-generated constructor stub
}
public static void Insert(Contact c) throws SQLException {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf =HibernateUtil.getSessionFactory();
Session session = sf.openSession();
try {
session.beginTransaction();
//Constructor con = session.get(Constructor.class, consid);
//p.setConstructor(con);
session.save(c);
session.getTransaction().commit();
}
finally {
session.close();
System.out.println("Contact Session Closed!!!!");
}
}
public static List<Contact> getListofContacts(int id) {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf =HibernateUtil.getSessionFactory();
Session session = sf.openSession();
//List <OfferType> ol = session.createCriteria(OfferType.class).list();
//List <Contact> ol =session.createCriteria(Contact.class).list();
List <Contact> ol = session.createCriteria(Contact.class).createAlias("project", "p").add(Restrictions.eq("p.project_id", id)).list();
session.close();
return ol;
}
}

One To Many Relation in Hibernate / JPA

iam new to hibernate,iam using two classes which have person and section but iam able to relate them, iam getting like Exception in thread "main" org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: in.quadra.apps.Profile.Sections[in.quadra.apps.Section]
Person.java
package in.quadra.apps;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Profile")
public class Profile {
#Id
#GeneratedValue
#Column(name="Profile_ID")
private Long ProfileId;
#Column(name="Profile_NAME")
private String ProfileName;
#OneToMany(mappedBy="Profile")
private Set<Section> Sections;
public Long getProfileId() {
return ProfileId;
}
public void setProfileId(Long profileId) {
ProfileId = profileId;
}
public String getProfileName() {
return ProfileName;
}
public void setProfileName(String profileName) {
ProfileName = profileName;
}
public Set<Section> getSections() {
return Sections;
}
public void setSections(Set<Section> sections) {
Sections = sections;
}
}
Section.Java
package in.quadra.apps;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="Profile")
public class Profile {
#Id
#GeneratedValue
#Column(name="Profile_ID")
private Long ProfileId;
#Column(name="Profile_NAME")
private String ProfileName;
#OneToMany(mappedBy="Profile")
private Set<Section> Sections;
public Long getProfileId() {
return ProfileId;
}
public void setProfileId(Long profileId) {
ProfileId = profileId;
}
public String getProfileName() {
return ProfileName;
}
public void setProfileName(String profileName) {
ProfileName = profileName;
}
public Set<Section> getSections() {
return Sections;
}
public void setSections(Set<Section> sections) {
Sections = sections;
}
}
main.java
package in.quadra.apps;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main123 {
public static void main(String ar[]){
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
Profile p= new Profile();
p.setProfileName("Srikanth");
Section s1= new Section();
s1.setSectionName("Names");
s1.setProfileId(p);
Section s2= new Section();
s2.setProfileId(p);
s2.setSectionName("Address");
session.save(p);
// session.save(s1);
// session.save(s2);
session.getTransaction().commit();
session.close();
}
}
Probably missing #Entity on Section class.

Categories

Resources