I have to delete the last row from the database (created with MySQL) using .remove and .flush but it keeps telling me that the row is not deleted. I have tried to write it different ways yet I can't seemm to get it to work. Any help would be appreciated! Here is the code:
package com.vz.test.mbean;
import com.vz.test.db.Person;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#ManagedBean
#ViewScoped
public class AddPerson {
com.vz.test.db.Person person = null;
private int identification = 0;
private String name = "";
private String age = "";
private String telephone = "";
private String results="";
private java.util.List<Person> alst = new java.util.ArrayList<Person>();
public java.util.List<Person> getAlst() {
return alst;
}
public void setAlst(ArrayList<Person> alst) {
this.alst = alst;
}
public String getResults() {
return results;
}
public void setResults(String results) {
this.results = results;
}
#PersistenceContext(unitName = "WebApplication2PU")
private EntityManager em;
#Resource
private javax.transaction.UserTransaction utx;
public int getIdentification() {
return identification;
}
public void setIdentification(int identification) {
this.identification = identification;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public AddPerson() {
}
public void fetchPersonList(){
Query qu = em.createQuery("SELECT a FROM Person a");
alst= (java.util.List<Person>) q.getResultsList();
System.out.println("alst.size():"+ alst.size());
}
public void addRow() {
try {
System.out.println("I am in addRow");
com.vz.test.db.Person person = new com.vz.test.db.Person();
person.setName(name);
person.setAge(age);
person.setTelephone(telephone);
persist(person);
result="Row is added";
}
catch (Exception e) {
result="Row is NOT added";
}
}
public void deleteRow(){
try{
em.remove(person);
em.flush();
persist(person);
result="Row is deleted";
}
catch (Exception e){
result="Row is NOT deleted";
}
}
public void persist(Object object) {
try {
utx.begin();
em.persist(object);
utx.commit();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
throw new RuntimeException(e);
}
}
}
em.remove(person);
em.flush();
persist(person);
You first remove the entity and try to persist it afterwards. Wrap the remove call in a user transaction instead, that should solve the problem:
try {
if (person != null) {
utx.begin();
em.remove(person);
utx.commit();
result="Row is deleted";
} else {
System.out.println("The field 'person' is null. Can't remove anything");
}
}
catch (Exception e) {
// TODO add proper exception handling/logging
result="Row is NOT deleted";
}
Related
I am stuck in a Java program. My program is One To Many Right Outer Join. I am trying to figure where my error is, but I couldn't find it by myself.
I tried to solve it so many times, but nothing happened.
I tried to change the database column name, it didn't work. I tried to debug using Eclipse debugger, couldn't find any.
Details are attached below.
MainClass.java
package OneToManyRightJoin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/person","root","1234");
Statement st=con.createStatement();
java.sql.Statement st1=con.createStatement();
java.sql.Statement st2=con.createStatement();
String query1 ="SELECT * from person" ;
String query2 ="SELECT * from address" ;
ResultSet rs1=st1.executeQuery(query1);
ResultSet rs2=st2.executeQuery(query2);
//for address
List<Address> addrList = new ArrayList<Address>();
List<Person> personList = new ArrayList<Person>();
while(rs1.next())
{
//List<Address> addrList = new ArrayList<Address>();
Address a=new Address();
a.setPid(rs1.getInt("pid"));
a.setAid(rs1.getInt("Aid"));
a.setAddress1(rs1.getString("Ad1"));
a.setAddress2(rs1.getString("Ad2"));
addrList.add(a);
}
while(rs2.next())
{
Person p=new Person();
p.setPid(rs2.getInt("pid")) ;
p.setName(rs2.getString("name"));
personList.add(p);
}
//comparing 2 List(personList and addrList)
List matchedList=new ArrayList<List>();
for(int i=0;i<addrList.size();i++)
{
List innerPersonList = new ArrayList();
Address pkgInnerAddress = (Address)addrList.get(i);
for(int j=0;j<personList.size();j++)
{
if(addrList.get(i).getPid() == personList.get(j).getPid())
{
Person innerPerson = personList.get(j);
innerPersonList.add(innerPerson);
}
}
// add the list of matched addresses to person
pkgInnerAddress.setLst(innerPersonList);
matchedList.add(pkgInnerAddress);
}
System.out.println("Right Outer join details" +"\n");
for (int i=0; i<matchedList.size(); i++) {
Address a = (Address)matchedList.get(i);
System.out.println("\n" + "address details Id Ad1 Ad2 are "+a.getAid()+" "+a.getAddress1()+" "+a.getAddress2()+" "+a.getPid()+"\n");
for (int j=0; j<a.getLst().size(); j++) {
System.out.println(" Person Pid is " +a.getLst().get(j).getPid());
}
}
}
catch (SQLException e)
{
System.out.println(e);
}
catch(ClassNotFoundException e1)
{
System.out.println(e1);
}
}
}
Address.java
package OneToManyRightJoin;
import java.util.List;
public class Address {
int aid;
int Pid;
String Address1;
String Address2;
List<Person>lst;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public int getPid() {
return Pid;
}
public void setPid(int pid) {
Pid = pid;
}
public String getAddress1() {
return Address1;
}
public void setAddress1(String address1) {
Address1 = address1;
}
public String getAddress2() {
return Address2;
}
public void setAddress2(String address2) {
Address2 = address2;
}
public List<Person> getLst() {
return lst;
}
public void setLst(List<Person> lst) {
this.lst = lst;
}
}
Person.java
package OneToManyRightJoin;
public class Person
{
int pid;
String Name;
Person()
{
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
These are my database details images.
Address DB
Person DB
Error Details:
Error Details
You are facing error at this line :
a.setAid(rs1.getInt("Aid"));
The reason is you are setting the value of particular column in this scenario you are setting value of object a with Aid column. But SQL says that Aid column you are using which is not presented it means you doesn't have any column which has name Aid into your database table.
I'm new with Spring Boot.
I try to develop a simple CRUD app using Spring Boot for the backend.
I have some issues with the methods in JPA repository.
Only one method works, the others return all data, as findAll() does.
when I try http://localhost:8080/api/professeurs?nom=CHRAYAH it works and returns the correct row.
But when I try http://localhost:8080/api/professeurs?prenom=Yassine it returns all rows.
So, only profRepository.findByNom() works, but profRepository.findByPrenom() and other methods don't.
This is my code
ProfRepository
package com.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.model.Professeur;
#Repository
public interface ProfRepository extends JpaRepository<Professeur, Long> {
List<Professeur> findByNom(String name);
#Query("SELECT p FROM Prof p where p.prenom=?1")
List<Professeur> findByPrenom(String prenom);
List<Professeur> findByEmail(String email);
List<Professeur> findByNomContaining(String name);
}
Professeur.java (model)
package com.model;
import javax.persistence.*;
#Entity(name="Prof")
#Table(name = "professeurs")
public class Professeur {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "nom" )
private String nom;
#Column(name = "prenom")
private String prenom;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "cours")
private String cours;
public Professeur() {
}
public Professeur(String nom, String prenom, String email, String password, String cours) {
this.nom = nom;
this.prenom= prenom;
this.email = email;
this.password = password;
this.cours = cours;
}
public long getId() {
return id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCours() {
return this.cours;
}
public void setCours(String cours) {
this.cours = cours;
}
#Override
public String toString() {
return "Professeur [id=" + id + ", nom=" + nom+ ", prenom=" + prenom + ", cours=" + cours + ", email=" + email + "]";
}
}
ProfesseurController
package com.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.model.Professeur;
import com.repository.AppRepository;
import com.repository.ProfRepository;
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/api")
public class ProfesseurController {
#Autowired
ProfRepository profRepository;
#GetMapping("/professeurs")
public ResponseEntity<List<Professeur>> getAllProfs(#RequestParam(required = false) String nom) {
try {
List<Professeur> professeurs = new ArrayList<Professeur>();
if (nom == null)
profRepository.findAll().forEach(professeurs::add);
else
profRepository.findByNomContaining(nom).forEach(professeurs::add);
if (professeurs.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(professeurs, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#GetMapping("/professeurs/{id}")
public ResponseEntity<Professeur> getProfById(#PathVariable("id") long id) {
Optional<Professeur> profData = profRepository.findById(id);
if (profData.isPresent()) {
return new ResponseEntity<>(profData.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
#PostMapping("/professeurs")
public ResponseEntity<Professeur> createProf(#RequestBody Professeur professeur) {
try {
Professeur _professeur = profRepository
.save(new Professeur (professeur.getNom(), professeur.getPrenom(), professeur.getEmail(),professeur.getPassword(), professeur.getCours()));
return new ResponseEntity<>(_professeur, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#PutMapping("/professeurs/{id}")
public ResponseEntity<Professeur> updateProf(#PathVariable("id") long id, #RequestBody Professeur professeur) {
Optional<Professeur> profData = profRepository.findById(id);
if (profData.isPresent()) {
Professeur _professeur = profData.get();
_professeur.setNom(professeur.getNom());
_professeur.setPrenom(professeur.getPrenom());
_professeur.setEmail(professeur.getEmail());
_professeur.setPassword(professeur.getPassword());
_professeur.setCours(professeur.getCours());
return new ResponseEntity<>(profRepository.save(_professeur), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
#DeleteMapping("/professeurs/{id}")
public ResponseEntity<HttpStatus> deleteProf(#PathVariable("id") long id) {
try {
profRepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#DeleteMapping("/professeurs")
public ResponseEntity<HttpStatus> deleteAllEleves() {
try {
profRepository.deleteAll();
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#GetMapping("/professeurs/nom")
public ResponseEntity<List<Professeur>> findByNom(#PathVariable("nom") String nom) {
try {
List<Professeur> professeurs = profRepository.findByNom(nom);
if (professeurs .isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(professeurs , HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#GetMapping("/professeurs/email")
public ResponseEntity<List<Professeur>> findByEmail(#PathVariable("email") String email) {
try {
List<Professeur> professeurs = profRepository.findByEmail(email);
if (professeurs .isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(professeurs , HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#GetMapping("/professeurs/prenom")
public ResponseEntity<List<Professeur>> findByPrenom(#PathVariable("prenom") String prenom) {
try {
List<Professeur> professeurs = profRepository.findByPrenom(prenom);
if (professeurs .isEmpty()) {
System.out.println("pas de prof avec ce nom");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(professeurs , HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
I just found out that I should change #GetMapping("/professeurs/prenom") to #GetMapping("/professeurs/prenom/{prenom}")
I have a issue regarding one to many mapping in hibernate 4.x and I am using mysql5.6.
First Let show you my 2 entities,
first user entity,
package com.project.entities;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
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="UserBookingEntryTable")
public class UserBookingEntryClass {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int uid;
private String ubmobile_no;
private String ubname;
#OneToMany(cascade = {CascadeType.ALL},mappedBy="user")
private Collection<BookingServicesClass> bookings=new ArrayList<BookingServicesClass>();
public Collection<BookingServicesClass> getBookings() {
return bookings;
}
public void setBookings(Collection<BookingServicesClass> bookings) {
this.bookings = bookings;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUbmobile_no() {
return ubmobile_no;
}
public void setUbmobile_no(String ubmobile_no) {
this.ubmobile_no = ubmobile_no;
}
public String getUbname() {
return ubname;
}
public void setUbname(String ubname) {
this.ubname = ubname;
}
}
Second Entity -Booking Class
package com.project.entities;
import java.util.Date;
import javax.persistence.Entity;
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 = "BookingServiceTable")
public class BookingServicesClass {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int booking_id;
private String first_name;
private String last_name;
private String mobile;
private String location;
private String booking_address;
private String booking_type;
private String landmark;
private int booking_pincode;
private Date booking_date;
#ManyToOne
#JoinColumn(name="usid")
private UserBookingEntryClass user;
public Integer getBooking_id() {
return booking_id;
}
public void setBooking_id(Integer booking_id) {
this.booking_id = booking_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBooking_address() {
return booking_address;
}
public void setBooking_address(String booking_address) {
this.booking_address = booking_address;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public Integer getBooking_pincode() {
return booking_pincode;
}
public void setBooking_pincode(Integer booking_pincode) {
this.booking_pincode = booking_pincode;
}
public Date getBooking_date() {
return booking_date;
}
public void setBooking_date(Date booking_date) {
this.booking_date = booking_date;
}
public String getBooking_type() {
return booking_type;
}
public void setBooking_type(String booking_type) {
this.booking_type = booking_type;
}
public UserBookingEntryClass getUser() {
return user;
}
public void setUser(UserBookingEntryClass user) {
this.user = user;
}
}
// to add booking from a user:
public String addService(String fname, String lname, String mob,
String ser, String loc, String add, String lm, int pc, String bd) {
String res = "failure";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date convertedCurrentDate = null;
try {
convertedCurrentDate = sdf.parse(bd);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BookingServicesClass bs = new BookingServicesClass();
UserBookingEntryClass ubs = new UserBookingEntryClass();
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
System.out.println("dddd");
try {
**//userid is auto generated**
ubs.setUbmobile_no(mob);
ubs.setUbname((fname + " " + lname));
// bs.setBid(1);
bs.setFirst_name(fname);
bs.setLast_name(lname);
bs.setMobile(mob);
bs.setLocation(loc);
bs.setBooking_type(ser);
bs.setBooking_address(add);
bs.setLandmark(lm);
bs.setBooking_pincode(pc);
bs.setBooking_date(convertedCurrentDate);
bs.setUser(ubs);
session.save(ubs);
session.save(bs);
// Commit the transaction
session.getTransaction().commit();
/*session.close();*/
res = "success";
System.out.println("ajax");
} catch (Exception e) {
System.out.println(e);
session.getTransaction().rollback();
res = "failure";
// success=false;
}
return res;
}
Now the issue is that one user can do more than one booking.
So the code create a foreign key in booking table which is users key who is booking.
but when the one user books more than one booking the Unique constraint Error is given.
So i made the userid auto genrate which is not according to my needs,
becuase if same user books two booking then userid should be same but when i do this it gives me unique constraint error.
Please tell how should I implement it.
Thanks
First thing - id of User should not be auto generated, maybe the mobilenumber which will definitely be unique should be the identifier
Second thing - When you add the booking you will check if the user exists , if it exists add the booking to the user ,otherwise create the user and add the bookings, and then commit the user.
Try these and let me know.
BookingServicesClass booking = new BookingServicesClass ()
if(ubmobile_no!=null) {
UserBookingEntryClass user= session.get(UserBookingEntryClass .class, ubmobile_no);
if (user!= null) {
booking.setUser(user);
user.getBookings().add(booking);
} else {
//do nothing
}
}
Spring:version 3.2.9
Hibernate:version 4.2.19
BaseDaoImpl.java
public class BaseDaoImpl<T> implements BaseDao<T> {
public SessionFactory sessionFactory;
protected Class<T> entityClass;
#Override
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public BaseDaoImpl() {
Class c = getClass();
Type type = c.getGenericSuperclass();
if (type instanceof ParameterizedType) {
Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
this.entityClass = (Class<T>) parameterizedType[0];
}
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public boolean save(T entity) {
try {
getSession().save(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean delete(T entity) {
try {
getSession().delete(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean update(T entity) {
try {
getSession().update(entity);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#SuppressWarnings("unchecked")
#Override
public T get(Integer id) {
return (T) getSession().get(entityClass, id);
}
#SuppressWarnings("unchecked")
#Override
public List<T> findByIdSet(Integer[] ids) {
Criteria criteria=getSession().createCriteria(entityClass);
criteria.add(Restrictions.in("id", ids));
return (List<T>)criteria.list();
}
#SuppressWarnings("unchecked")
#Override
public List<T> findAllList() {
return getSession().createCriteria(entityClass).list();
}
#SuppressWarnings("unchecked")
#Override
public Pager findByPager(Pager pager) {
Criteria criteria=getSession().createCriteria(entityClass);
criteria.setProjection(Projections.rowCount());
int totalCount = ((Long) criteria.uniqueResult()).intValue();
pager.setTotalCount(totalCount);
criteria.setProjection(null);
pager.init();
criteria.setFirstResult((pager.getPageIndex()-1)*pager.getPageSize());
criteria.setMaxResults(pager.getPageSize());
List<T> te =(List<T>)criteria.list();
pager.setDatas((List<T>)criteria.list());
return pager;
}
}
Pager.java
import java.util.List;
public class Pager {
private int pageSize;
private int pageIndex;
private int totalCount;
private int totalPage;
private List<?> datas;
private boolean hasNextPage;
private boolean hasPreviousPage;
public void init(){
pageIndex=1;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<?> getDatas() {
return datas;
}
public void setDatas(List<?> datas) {
this.datas = datas;
}
public boolean isHasNextPage() {
return hasNextPage;
}
public void setHasNextPage(boolean hasNextPage) {
this.hasNextPage = hasNextPage;
}
public boolean isHasPreviousPage() {
return hasPreviousPage;
}
public void setHasPreviousPage(boolean hasPreviousPage) {
this.hasPreviousPage = hasPreviousPage;
}
}
Entity:Student.java
import java.util.Date;
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.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="student")
public class Student {
private int stu_id;
private String stu_name;
private String stu_password;
private Department department;
private Major major;
private String stu_sex;
private String stu_per_sig;
private String stu_head_img;
private Date stu_regist_time;
private String stu_attn_crs_ids;
private String stu_pw_question;
private String stu_pw_answer;
public Student() {
}
public Student(int stu_id, String stu_name, String stu_password,
Department department, Major major, String stu_sex,
String stu_per_sig, String stu_head_img, Date stu_regist_time,
String stu_attn_crs_ids, String stu_pw_question,
String stu_pw_answer) {
this.stu_id = stu_id;
this.stu_name = stu_name;
this.stu_password = stu_password;
this.department = department;
this.major = major;
this.stu_sex = stu_sex;
this.stu_per_sig = stu_per_sig;
this.stu_head_img = stu_head_img;
this.stu_regist_time = stu_regist_time;
this.stu_attn_crs_ids = stu_attn_crs_ids;
this.stu_pw_question = stu_pw_question;
this.stu_pw_answer = stu_pw_answer;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getStu_id() {
return stu_id;
}
public void setStu_id(int stu_id) {
this.stu_id = stu_id;
}
#Column(length=20,nullable=false)
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
#Column(length=20,nullable=false)
public String getStu_password() {
return stu_password;
}
public void setStu_password(String stu_password) {
this.stu_password = stu_password;
}
#Column(length=2,nullable=false)
public String getStu_sex() {
return stu_sex;
}
public void setStu_sex(String stu_sex) {
this.stu_sex = stu_sex;
}
#Column(length=255,nullable=true)
public String getStu_per_sig() {
return stu_per_sig;
}
public void setStu_per_sig(String stu_per_sig) {
this.stu_per_sig = stu_per_sig;
}
#Column(length=255,nullable=false)
public String getStu_head_img() {
return stu_head_img;
}
public void setStu_head_img(String stu_head_img) {
this.stu_head_img = stu_head_img;
}
#Temporal(value=TemporalType.TIMESTAMP)
#Column(nullable=false)
public Date getStu_regist_time() {
return stu_regist_time;
}
public void setStu_regist_time(Date stu_regist_time) {
this.stu_regist_time = stu_regist_time;
}
#Column(length=255,nullable=true)
public String getStu_attn_crs_ids() {
return stu_attn_crs_ids;
}
public void setStu_attn_crs_ids(String stu_attn_crs_ids) {
this.stu_attn_crs_ids = stu_attn_crs_ids;
}
#Column(length=64,nullable=false)
public String getStu_pw_question() {
return stu_pw_question;
}
public void setStu_pw_question(String stu_pw_question) {
this.stu_pw_question = stu_pw_question;
}
#Column(length=64,nullable=false)
public String getStu_pw_answer() {
return stu_pw_answer;
}
public void setStu_pw_answer(String stu_pw_answer) {
this.stu_pw_answer = stu_pw_answer;
}
#ManyToOne()
#JoinColumn(name="stu_dept_id",nullable=false)
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#ManyToOne()
#JoinColumn(name="stu_major_id",nullable=false)
public Major getMajor() {
return major;
}
public void setMajor(Major major) {
this.major = major;
}
}
I write BaseDaoImpl.java to implement the interface BaseDao.java
When I debug the project ,I found that the size of te list is 0 .
In findByPager method of BaseDaoImpl.java.
Why the method criteria.list() return a empty list?
Why is it not a List<Student> list ?
It puzzles me a long time.I'm a fresh man,who can help me to solve this problem.
The problem of your code is this line:
Criteria criteria=getSession().createCriteria(entityClass);
Because when you use criteria queries, you are building a query against a reference of a particular persistent class and your variable entityClass isn't.
protected Class<T> entityClass;
The correct way to build a criteria query is:
Criteria criteria=getSession().createCriteria(Entity.class);
Then you need to change that line of your code. You need to add the .class to your variable:
Criteria criteria=getSession().createCriteria(entityClass.class);
I share you some links about criteria queries.
https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Criteria.html
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
I hope this information helps you.
Good luck.
I am getting null from getters method when trying to save it in a list and calling the list in servlet. Please help me out to get rid of this. Thanks in advance.
I am adding first the getters and setters method code then DAO code and then servlet code.
package com.vechile.model;
public class DriverSearchResult {
private String Id;
private String Name;
private String Address;
private String City;
private String Contact;
private String Country;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
package com.vechile.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.vechile.model.Driver;
import com.vechile.model.DriverSearchResult;
import com.vechile.model.Searching;
import com.vechile.utils.DBConnection;
public class SearchDAO {
private String sql;
private ResultSet rs, rs1;
public boolean searchDriver(Searching searching) {
try {
sql = String.format("select * from adddriver where (%s) = '%s'",
searching.getInputList(), searching.getTxtField());
rs = DBConnection.executeQuery(sql);
if(rs.next()) {
DriverSearchResult setResult = new DriverSearchResult();
Integer id = new Integer(rs.getInt(1));
String stringID = id.toString();
setResult.setId(stringID);
setResult.setName(rs.getString(1));
setResult.setAddress(rs.getString(2));
setResult.setCity(rs.getString(3));
setResult.setContact(rs.getString(4));
setResult.setCountry(rs.getString(5));
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
public List<DriverSearchResult> getDriverResult(){
List<DriverSearchResult> returnList = new ArrayList<DriverSearchResult>();
DriverSearchResult getResult = new DriverSearchResult();
String id = getResult.getId();
String name = getResult.getName();
String address = getResult.getAddress();
String city = getResult.getCity();
String contact = getResult.getContact();
String country = getResult.getCountry();
returnList.add(getResult);
return returnList;
}
public boolean searchBooking(Searching searching) {
try {
sql = String.format(
"select * from booking where booking_id = '%s'",
searching.getBookingSearch());
rs1 = DBConnection.executeQuery(sql);
if (rs1.next()) {
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String input = request.getParameter("list");
String txtField = request.getParameter("txtField");
String op = request.getParameter("op");
String bSearch = request.getParameter("bookingSearch");
try{
if(op.equals("1")){
Searching search1 = new Searching();
search1.setInputList(input);
search1.setTxtField(txtField);
SearchDAO searchDAO = new SearchDAO();
boolean searchDriver = searchDAO.searchDriver(search1);
if(searchDriver){
DriverSearchResult searchResult = new DriverSearchResult();
System.out.println(searchResult.getId());
//response.sendRedirect("driversearchresult.jsp");
//response.sendRedirect("SearchOutPut.jsp?op=" + search1.getPassingValue());
}
else {
out.println("<html>");
out.println("<head>");
out.println("<script>");
out.println("alert('Record Not Found!')");
out.println("</script>");
out.println("<META HTTP-EQUIV= Refresh CONTENT=0;URL=SearchDriver.jsp>");
}
}
That happens because you fill DriverSearchResult object in the method searchDriver and then forget that object. Then in another method you create another instance of class DriverSearchResult and try to extract values from it without prior initialization. That's why it gives you nulls, since you never call setters on this newly created instance.
I guess you want to save DriverSearchResult instance created in searchDriver method and then use it in other methods instead of creating new one.
UPD:
I hope the idea is clear from the code snippet:
public class SearchDAO {
private List<DriverSearchResult> resultList = new ArrayList<>();
public boolean searchDriver(Searching searching) {
try {
// ...
if(rs.next()) {
DriverSearchResult setResult = new DriverSearchResult();
// ...
resultList.add(setResult); // <<<<<<<<<
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
public List<DriverSearchResult> getDriverResult(){
return resultList; // <<<<
}
}