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.
Related
I'm facing some problem with displaying COUNT of a variable while querying a MySQL database. I have made a variable with annotation #Transient so that it's not included in the DB. But, I'm getting error while posting data in the same table in the DB, since while posting, there is no field count, count is only used to get COUNT(u_type). Is there any way with which I can display COUNT of a variable when I do a GET call (using SQL query) and no need to post it. TIA.
Class:
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.annotation.Transient;
#Entity // This tells Hibernate to make a table out of this class
public class UserClickData {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String u_search_term;
private String u_sysid;
private String u_type;
#Transient
private long count;
public UserClickData(String u_type, long Count) { //, long count
this.u_type = u_type;
this.count=count;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count=count;
}
public int getSys_id() {
return sys_id;
}
public void setSys_id(int sys_id) {
this.sys_id = sys_id;
}
public String getU_search_term() {
return u_search_term;
}
public void setU_search_term(String u_search_term) {
this.u_search_term = u_search_term;
}
public String getU_type() {
return u_type;
}
public void setU_type(String u_type) {
this.u_type = u_type;
}
}
Projection:
public interface UserClickProjection {
String getU_type();
long getCount();
}
DAO Code:
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.abc.datacollection.entity.UserClickData;
import com.abc.datacollection.entity.UserClickProjection;
import com.abc.datacollection.entity.UserProjection;
public interface UserClickDataRepository extends CrudRepository<UserClickData, Integer> {
public static final String FIND_QUERY =
"select new com.abc.datacollection.entity.UserClickData(user.u_type, COUNT(u_type)) from UserClickData user GROUP BY user.u_type ORDER BY COUNT(user.u_type) DESC";
#Query(value = FIND_QUERY)
//public List<UserProjection> getAllRequestResponseRecords();
List<UserClickProjection> findAllProjectedBy();
}
Controller:
#CrossOrigin(origins = "*")
#GetMapping(path="/all")
public #ResponseBody List<UserClickProjection> getAllUserClickDataRecords() {
return userClickDataRepository.findAllProjectedBy();
}
Import javax.persistence.Transient instead of org.springframework.data.annotation.Transient
I have made a spring boot application connected to an angular front end. When the user enters a value into attendance id and hits submit on the form, this calls a method that updates the current value in the database using a HTTP PUT request.
However, the value is not being update despite break points showing the new value is being received and updated.
I am new to spring boot so any help is appreciated.
package com.example.demo.Attendance;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.transaction.Transactional;
import com.example.demo.AttendancePK.AttendancePK;
import com.example.demo.AttendanceType.AttendanceType;
import com.example.demo.LessonRun.LessonRun;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Transactional
#Entity
public class Attendance {
#EmbeddedId
private AttendancePK id;
#ManyToOne
#JoinColumn(name="attendance_type", insertable = false, updatable=false)
private AttendanceType attendanceType;
#ManyToOne
#JsonIgnore
#JoinColumn(name="lesson_run_id", insertable = false, updatable=false)
private LessonRun lessonRun;
public LessonRun getLessonRun() {
return lessonRun;
}
public void setLessonRun(LessonRun lessonRun) {
this.lessonRun = lessonRun;
}
public AttendanceType getAttendanceType() {
return attendanceType;
}
public void setAttendanceType(AttendanceType attendanceType) {
this.attendanceType = attendanceType;
}
public Attendance(AttendancePK id, AttendanceType attendanceType, LessonRun lessonRun) {
super();
this.id = id;
this.attendanceType = attendanceType;
this.lessonRun = lessonRun;
}
public Attendance() {
}
public AttendancePK getId() {
return id;
}
public void setId(AttendancePK id) {
this.id = id;
}
}
My controller
#RequestMapping(value="/attendance/{attendanceId}/student/{studentId}/lessonrun/{lessonRunId}",method = RequestMethod.PUT)
public void updateAttendance(#PathVariable int attendanceId, #PathVariable int studentId, #PathVariable int lessonRunId, #RequestBody int attendanceTypeId) {
AttendancePK id = new AttendancePK(attendanceId, studentId,lessonRunId);
Attendance attendanceInDB = attendanceService.getAttendancebyId(id);
// attendanceInDB.setAttendanceType(int.getAttendanceType());
attendanceService.updateAttendance(attendanceInDB, attendanceTypeId);
}
My Service
package com.example.demo.Attendance;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.AttendancePK.AttendancePK;
import com.example.demo.AttendanceType.AttendanceType;
import com.example.demo.AttendanceType.AttendanceTypeRepository;
#Service
public class AttendanceService {
#Autowired
private AttendanceRepository attendanceRepository;
#Autowired
private AttendanceTypeRepository attendanceTypeRepository;
public List<Attendance> getAllAttendanceRecs() {
List<Attendance> attendanceList = new ArrayList<>();
attendanceRepository.findAll().forEach(attendanceList::add);
return attendanceList;
}
public Attendance getAttendancebyId(AttendancePK id) {
Optional<Attendance> optionalAttendance = attendanceRepository.findById(id);
if (optionalAttendance.isPresent()) {
return optionalAttendance.get();
}
return null;
}
public void updateAttendance(Attendance attendanceInDB, int attendanceTypeId) {
Optional<AttendanceType> attendanceType = attendanceTypeRepository.findById(attendanceTypeId);
if (attendanceType.isPresent()) {
attendanceInDB.setAttendanceType(attendanceType.get());
attendanceRepository.save(attendanceInDB);
}
}
}
the breakpoint results show the value is updated shown here
but MySQL database doesn't reflect this
I have a class (Vehicles) and I implemented CRUD operations. Delete works, update works, just create doesn't work.
What can I put instead of this create code?
P.S.: I use Eclipse
AND THIS IS FormMasini.java where I take from Vehicule.java dates and it will show in a JSF Form. The error appears at this line: this.vehicul = new Vehicul();
package vehiculeFeaa;
import java.util.List;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
#Entity
#Table(name = "VEHICUL")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "VEHICUL_TYPE")
public abstract class Vehicul {
#TableGenerator(name = "VEHICUL_GEN", table = "ID_GEN", pkColumnName = "GEN_NUME", valueColumnName = "GEN_VALOARE", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.TABLE, generator = "VEHICUL_GEN")
private int idVehicul;
private String producator;
public int getIdVehicul() {
return idVehicul;
}
public void setIdVehicul(int idVehicul) {
this.idVehicul = idVehicul;
}
public String getProducator() {
return producator;
}
public void setProducator(String producator) {
this.producator = producator;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
public List<Vehicul> get(int i) {
// TODO Auto-generated method stub
return null;
}
}
package masinifeaa;
import java.util.ArrayList;
import java.util.List;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import vehiculeFeaa.Vehicul;
public class FormMasini {
private Vehicul vehicul;
private List<Vehicul>vehicule=new ArrayList<Vehicul>();
public Vehicul getVehicul() {
return vehicul;
}
public void setVehicul(Vehicul vehicul) {
this.vehicul = vehicul;
}
public List<Vehicul> getVehicule() {
return vehicule;
}
public void setVehicule(List<Vehicul> vehicule) {
this.vehicule = vehicule;
}
private EntityManager em;
#SuppressWarnings("unchecked")
public FormMasini() {
EntityManagerFactory emf=
Persistence.createEntityManagerFactory("FirmeJPA");
em=emf.createEntityManager();
this.vehicule= em.createQuery("SELECT v FROM Vehicul v")
.getResultList();
if(!this.vehicule.isEmpty())
vehicul=this.vehicule.get(0);
}
public void backVehicul(ActionEvent evt) {
Integer idxCurent = this.vehicule.indexOf(vehicul);
if(idxCurent > 0)
this.vehicul=this.vehicule.get(idxCurent-1);
}
public void nextVehicul(ActionEvent evt) {
Integer idxCurent = this.vehicule.indexOf(vehicul);
if((idxCurent + 1) < this.vehicule.size())
this.vehicul=this.vehicule.get(idxCurent + 1);
}
//Implementez actiunile CRUD
public void deleteVehicul(ActionEvent evt) {
this.vehicule.remove(this.vehicul);
if(this.em.contains(this.vehicul)) {
this.em.getTransaction().begin();
this.em.remove(this.vehicul);
this.em.getTransaction().commit();
}
if(!this.vehicule.isEmpty())
this.vehicul=this.vehicule.get(0);
else
this.vehicul=null;
}
public void saveVehicul(ActionEvent evt) {
this.em.getTransaction().begin();
this.em.persist(this.vehicul);
this.em.getTransaction().commit();
}
public void abandonVehicul(ActionEvent evt) {
if(this.em.contains(this.vehicul))
this.em.refresh(this.vehicul);
}
public void createVehicul(ActionEvent evt) {
this.vehicul = new Vehicul();
this.vehicul.setidVehicul(999);
this.vehicul.setNume("New car");
this.vehicule.add(this.vehicul);
}
Nothing related to JSF or something else. You just can't instantiate a abstract class, thats basic java.
These are my pojo class
Orderdetail.java
package online.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "orderdetail")
public class OrderDetail {
#Id
#Column(name="order_detail_id")
private int order_detail_id;
#Column(name="bill")
private float bill;
#ManyToOne
#JoinColumn(name = "p_id" )
private Product p_id;
#ManyToOne
#JoinColumn(name = "o_id" )
private Order o_id;
public int getOrder_detail_id() {
return order_detail_id;
}
public void setOrder_detail_id(int order_detail_id) {
this.order_detail_id = order_detail_id;
}
public float getBill() {
return bill;
}
public void setBill(float bill) {
this.bill = bill;
}
public Product getP_id() {
return p_id;
}
public void setP_id(Product p_id) {
this.p_id = p_id;
}
public Order getO_id() {
return o_id;
}
public void setO_id(Order o_id) {
this.o_id = o_id;
}
}
My Order.java
package online.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "ordertable")
public class Order {
#Id
#Column(name = "order_id")
private int order_id;
#OneToMany(mappedBy = "o_id",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<OrderDetail> orderdetail;
#ManyToOne
#JoinColumn(name = "u_id")
private UserDetail u_id;
public UserDetail getU_id() {
return u_id;
}
public void setU_id(UserDetail u_id) {
this.u_id = u_id;
}
#Column(name = "date")
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#Column(name = "totalbill")
private Float totalbill;
public Float getTotalbill() {
return totalbill;
}
public void setTotalbill(Float totalbill) {
this.totalbill = totalbill;
}
public List<OrderDetail> getOrderdetail() {
return orderdetail;
}
public void setOrderdetail(List<OrderDetail> orderdetail) {
this.orderdetail = orderdetail;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
When ever I am trying to save order class I want my orderdetail class also get saved but when I am trying to save the List in order,Is is not getting saved and there is not error provided by hibernate that can help...
Thanks for the help
when i am trying to to persist the order class
Hibernate: select orderdetai_.order_detail_id, orderdetai_.bill as bill7_, orderdetai_.o_id as o3_7_, orderdetai_.p_id as p4_7_ from orderdetail orderdetai_ where orderdetai_.order_detail_id=?
This what I am getting output.
This is my code which save the class
#Override
public boolean payment(String username, Integer ordernumber, Date date,
Float totalbill, List<Integer> list) {
Session session = sessionFactory.openSession();
Transaction tranction = session.beginTransaction();
try {
Query query = session
.createQuery("from UserDetail where user_username = :username");
query.setParameter("username", username);
List<UserDetail> userdetaillist = query.list();
UserDetail userdetail = userdetaillist.get(0);
query = session
.createQuery("from ProductDetail where product_detail_id in(:list)");
query.setParameterList("list", list);
List<ProductDetail> productdetail = query.list();
Order order = new Order();
order.setOrder_id(ordernumber);
order.setDate(date);
order.setU_id(userdetail);
order.setTotalbill(totalbill);
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = new OrderDetail();
for (ProductDetail pro : productdetail) {
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
System.out.print("totalbill" + totalbill);
System.out.println(orderdetail);
order.setOrderdetail(orderdetail);
session.save(order);
tranction.commit();
return true;
} catch (Exception e) {
tranction.rollback();
e.getStackTrace();
}
return false;
}
I think ordetail has to be created inside the for.. You are modifying the same object for each productdetail. Should be like this:
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = null;
for (ProductDetail pro : productdetail) {
ordetail = new OrderDetail();
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
Hey I have recheck my pojo class and I found out the mistake I have done. I have made change and it work properly now.
I was not setting the the id for Orderdetail table. It was auto increment in database.
So it was giving me error ""
So I have made change in orderdetail iD
"#GeneratedValue(strategy=GenerationType.AUTO)" So now It is working fine cause now hibernate know that the id will get value from database.
Thanks for the help and for your time
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.