Hibernate Can not insert joined table - java

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;
}
}

Related

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'

hibernate two way mapping insert and delete beginner

Today I did some experiments with hibernate. Unfortunately it seems if I’m misunderstanding something about the sessions.
I have three entities (book “buch”, user “benutzer” and rent “leihstellung”).
Each book knows about the rents, it’s concerned by. Each rent knows about the associated book. Furthermore each rent knows about the fitting user and of course each user knows the associated rents.
I explicitly want to have this two way mappings.
Now I wrote a small tester which inserts some data. The insert progress works as expected. After inserting some data I would like to delete a user.
If I do this before the commit, hibernate gives me an error, because the user will be reinserted be the rents it belongs to (that even happens, if I manually delete the user from this rents). Here I don’t really understand why that happens.
Everything works fine, if I do a session.close and open a new session for deleting the user.
I guess, that there is a smarter way to do this within one session. But unfortunately I don’t know how this can be done.
Any explanation is welcome.
public class Worker implements Iworker{
private Sessiongetter sg;
private MainMenu mm;
public void work(File datei)
{
sg = new Sessiongetter();
Session session = sg.getSesseion();
WlBuchart wlBuchart = new WlBuchart(1, "Sachbuch");
Buch buch = new Buch("test", "ich", 1);
buch.setWlBuchart(wlBuchart);
Buch buch2 = new Buch("versuch", "du",2);
buch2.setWlBuchart(wlBuchart);
session.beginTransaction();
session.save(wlBuchart);
session.save(buch);
session.save(buch2);
Benutzer benutzer = new Benutzer("hans", "dampf", "Lehrer", "versuch");
session.save(benutzer);
Leihstellung leihstellung = new Leihstellung(benutzer, buch);
Leihstellung leihstellung2 = new Leihstellung(benutzer, buch2);
session.save(leihstellung);
session.save(leihstellung2);
benutzer.addLeihstellung(leihstellung);
benutzer.addLeihstellung(leihstellung2);
session.update(benutzer);
buch.addLeihstellung(leihstellung);
buch2.addLeihstellung(leihstellung2);
session.update(buch);
session.update(buch2);
session.remove(benutzer);
session.flush();
session.getTransaction().commit();
session.close();
System.out.println("fertig");
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.Session;
#Entity
#Table(name="benutzer")
public class Benutzer {
#Column(nullable=false)
private String vorname, nachname, gruppe;
#Id
private String kennung;
private boolean admin;
#Column(nullable=true)
private String kennwort;
#OneToMany(cascade=CascadeType.ALL, mappedBy="benutzer")
private List<Leihstellung>leihstellungs;
public String getKennwort() {
return kennwort;
}
public void setKennwort(String kennwort) {
this.kennwort = kennwort;
}
public Benutzer(String vorname, String nachname, String gruppe, String kennung) {
this.vorname=vorname;
this.nachname=nachname;
this.gruppe=gruppe;
this.kennung=kennung;
this.leihstellungs= new ArrayList<>();
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
public String getVorname() {
return vorname;
}
public String getNachname() {
return nachname;
}
public String getGruppe() {
return gruppe;
}
public String getKennung() {
return kennung;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
public int compare(Benutzer other)
{
if (this.getNachname().compareTo(other.getNachname())!=0)
{
return this.getNachname().compareTo(other.getNachname());
}
return this.getVorname().compareTo(other.getVorname());
}
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.ManyToAny;
#Entity
#Table(name="buch")
public class Buch {
#Column(nullable=false)
private String titel;
private String autor;
#ManyToOne
private WlBuchart wlBuchart;
#OneToMany(cascade=CascadeType.ALL, mappedBy="buch")
private List<Leihstellung>leihstellungs;
public WlBuchart getWlBuchart() {
return wlBuchart;
}
public void setWlBuchart(WlBuchart wlBuchart) {
this.wlBuchart = wlBuchart;
}
#Id
private int nummer;
public Buch(String titel, String autor,int nummer) {
this.titel=titel;
this.autor=autor;
this.nummer=nummer;
leihstellungs = new ArrayList<>();
}
public Buch() {
// TODO Auto-generated constructor stub
}
public String getTitel() {
return titel;
}
public String getAutor() {
return autor;
}
public int getNummer() {
return nummer;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
}
package code.logik;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="leihstellung")
public class Leihstellung {
#ManyToOne
private Benutzer benutzer;
#Id #GeneratedValue
private int id;
#Column(nullable=false)
private LocalDate von;
private LocalDate bis;
#ManyToOne
private Buch buch;
public Leihstellung(Benutzer benutzer, Buch buch) {
this.benutzer=benutzer;
this.buch=buch;
this.von = LocalDate.now();
}
public Leihstellung() {
// TODO Auto-generated constructor stub
}
public void setAbgegeben()
{
bis = LocalDate.now();
}
public Benutzer getBenutzer() {
return benutzer;
}
public int getId() {
return id;
}
public LocalDate getVon() {
return von;
}
public LocalDate getBis() {
return bis;
}
public Buch getBuch() {
return buch;
}
}
Found the solution myself. I had to delete the references from the connected rents and books.
Now everything works find.

Hibernate Batch Processing insert 1000000 records

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();
}
}

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.

ManyToMany relation with jointable

Category EJB
package session;
import com.Entity.Category;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Item EJB
package session;
import com.Entity.Item;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class saveItemBean implements saveItemRemote {
#PersistenceContext
private EntityManager em;
public void saveItem(Item itm) {
em.persist(itm);
}
public void persist(Object object) {
em.persist(object);
}
}
Servlet for save Item
package src;
import com.Entity.Item;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.CategoryFacadeRemote;
import session.saveItemRemote;
public class saveItemAndIemCategory extends HttpServlet {
#EJB
private saveItemRemote saveItemBean;
#EJB
private CategoryFacadeRemote categoryFacadeBean;
processRequest(HttpServletRequest request, HttpServletResponse response) {
try {
Item itm = new Item();
itm.setName("HelloNew");
saveItemBean.saveItem(itm);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Item Entity Bean
package com.Entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity
#Table(name = "item")
#NamedQueries({#NamedQuery(name = "Item.findAll", query = "SELECT i FROM Item i"), #NamedQuery(name = "Item.findByItemId", query = "SELECT i FROM Item i WHERE i.itemId = :itemId"), #NamedQuery(name = "Item.findByName", query = "SELECT i FROM Item i WHERE i.name = :name")})
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "item_id")
private Integer itemId;
#Basic(optional = false)
#Column(name = "name")
private String name;
#ManyToMany
#JoinTable(name = "item_cat",
joinColumns = {#JoinColumn(name = "item_id", referencedColumnName = "item_id")},
inverseJoinColumns = {#JoinColumn(name = "cat_id", referencedColumnName = "cat_id")})
private List<Category> categoryCollection;
public Item() {
}
public Item(Integer itemId) {
this.itemId = itemId;
}
public Item(Integer itemId, String name) {
this.itemId = itemId;
this.name = name;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Category> getCategoryCollection() {
return categoryCollection;
}
public void setCategoryCollection(List<Category> categoryCollection) {
this.categoryCollection = categoryCollection;
}
}
I am trying to persist data using these coding but only Category and Item tables are getting field (Category coding are missing here those are fine) my assosiative table item_cat is not getting saving data.
If you have an intermediate join table, you need to use the #JoinTable annotation:
#JoinTable(name="item_cat", joinColumns={ #JoinColumn(name="item_id") }, inverseJoinColumns={ #JoinColumn(name="category_id") })
Make sure you are setting the entities in both sides before persisting them. Something like this:
Item itm = new Item();
itm.setName("NewItem");
Category cat = new Category();
cat.setName("NewCategory");
itm.getCategoryCollection().add(cat);
cat.getItemCollection().add(itm);
It would be very helpful if you post you Category model.

Categories

Resources