Unable to update row in MySQL using hibernate - java

public class UpdateEmployee extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out= response.getWriter();
EmployeeDetails emp = new EmployeeDetails();
SessionFactory fact=new Configuration().configure().buildSessionFactory();
Session ses = fact.openSession();
int emp_id = Integer.parseInt(request.getParameter("emp_id"));
int new_emp_id = Integer.parseInt(request.getParameter("new_emp_id"));
String emp_name = request.getParameter("name");
String emp_designation_id = request.getParameter("designationid");
String emp_skills = request.getParameter("skills");
String emp_department_id = request.getParameter("departmentid");
String emp_notes = request.getParameter("notes");
String emp_email = request.getParameter("email");
String emp_phone = request.getParameter("phone");
String emp_username = request.getParameter("username");
String emp_password = request.getParameter("password");
emp.setEmp_department_id(emp_department_id);
emp.setEmp_designation_id(emp_designation_id);
emp.setEmp_email(emp_email);
emp.setEmp_id(new_emp_id);
emp.setEmp_join_date(null);
emp.setEmp_name(emp_name);
emp.setEmp_notes(emp_notes);
emp.setEmp_password(emp_password);
emp.setEmp_phone(emp_phone);
emp.setEmp_skills(emp_skills);
emp.setEmp_username(emp_username);
Query query = ses.createQuery("update EmployeeDetails emp set emp_id=:new_emp_id,emp_name=:emp_name,emp_designation_id=:emp_designation_id,emp_skills=:emp_skills,emp_department_id=:emp_department_id,emp_notes=:emp_notes,emp_email=:emp_email,emp_phone=:emp_phone,emp_username=:emp_username,emp_password=:emp_password where emp_id=:emp_id");
query.setParameter(emp_id, emp_id);
query.setParameter(new_emp_id, new_emp_id);
query.setParameter(emp_name, emp_name);
query.setParameter(emp_designation_id, emp_designation_id);
query.setParameter(emp_skills, emp_skills);
query.setParameter(emp_department_id, emp_department_id);
query.setParameter(emp_notes, emp_notes);
query.setParameter(emp_email, emp_email);
query.setParameter(emp_username, emp_username);
query.setParameter(emp_password, emp_password);
int result = query.executeUpdate();
out.print(result);
}
}
My result when i try to update:
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:55)
org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:61)
org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:382)
org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:362)
com.unisys.servlets.UpdateEmployee.doPost(UpdateEmployee.java:59)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I'm new to hibernate. I've looked up lot of references, any sort of guidance regarding updation would be much appreciated.
I'm trying to update one value in the row using emp_id value and updating all the other columns in the database.

Yes, you are correct. But here the guy is mixed up the "Named" parameters with indexed parameter concepts.
query.setParameter("emp_id", emp_id);
query.setParameter("new_emp_id", new_emp_id);
query.setParameter("emp_name", emp_name);
query.setParameter("emp_designation_id", emp_designation_id);
query.setParameter("emp_skills", emp_skills);
query.setParameter("emp_department_id", emp_department_id);
query.setParameter("emp_notes", emp_notes);
query.setParameter("emp_email", emp_email);
query.setParameter("emp_username", emp_username);
query.setParameter("emp_password", emp_password);
query.setParameter("emp_phone", emp_phone);
int result = query.executeUpdate();
The main purpose of named parameter is we don't worry about the order and it is easily understandable and maintainable.

The java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based! is misleading.
In your JPQL query, you use this condition emp_phone=:emp_phone with the emp_phone parameter but the parameter value is never set in the query :
Query query = ses.createQuery(
"update EmployeeDetails emp set..emp_phone=:emp_phone");
query.setParameter(emp_id, emp_id);
query.setParameter(new_emp_id, new_emp_id);
query.setParameter(emp_name, emp_name);
query.setParameter(emp_designation_id, emp_designation_id);
query.setParameter(emp_skills, emp_skills);
query.setParameter(emp_department_id, emp_department_id);
query.setParameter(emp_notes, emp_notes);
query.setParameter(emp_email, emp_email);
query.setParameter(emp_username, emp_username);
query.setParameter(emp_password, emp_password);
int result = query.executeUpdate();
So, Hibernate throws an exception.

Related

Is there any way to write custom or native queries in Java JPA (DocumentDbRepository) while firing a query to azure-cosmosdb?

Connected to azure-cosmosdb and able to fire default queries like findAll() and findById(String Id). But I can't write a native query using #Query annotation as the code is not considering it. Always considering the name of the function in respository class/interface. I need a way to fire a custom or native query to azure-cosmos db. ?!
Tried with #Query annotation. But not working.
List<MonitoringSessions> findBySessionID(#Param("sessionID") String sessionID);
#Query(nativeQuery = true, value = "SELECT * FROM MonitoringSessions M WHERE M.sessionID like :sessionID")
List<MonitoringSessions> findSessions(#Param("sessionID") String sessionID);
findBySessionID() is working as expected. findSessions() is not working. Below root error came while running the code.
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findSessions found for type MonitoringSessions
Thanks for the response. I got what I exactly wanted from the below link. Credit goes to Author of the link page.
https://cosmosdb.github.io/labs/java/technical_deep_dive/03-querying_the_database_using_sql.html
public class Program {
private final ExecutorService executorService;
private final Scheduler scheduler;
private AsyncDocumentClient client;
private final String databaseName = "UniversityDatabase";
private final String collectionId = "StudentCollection";
private int numberOfDocuments;
public Program() {
// public constructor
executorService = Executors.newFixedThreadPool(100);
scheduler = Schedulers.from(executorService);
client = new AsyncDocumentClient.Builder().withServiceEndpoint("uri")
.withMasterKeyOrResourceToken("key")
.withConnectionPolicy(ConnectionPolicy.GetDefault()).withConsistencyLevel(ConsistencyLevel.Eventual)
.build();
}
public static void main(String[] args) throws InterruptedException, JSONException {
FeedOptions options = new FeedOptions();
// as this is a multi collection enable cross partition query
options.setEnableCrossPartitionQuery(true);
// note that setMaxItemCount sets the number of items to return in a single page
// result
options.setMaxItemCount(5);
String sql = "SELECT TOP 5 s.studentAlias FROM coll s WHERE s.enrollmentYear = 2018 ORDER BY s.studentAlias";
Program p = new Program();
Observable<FeedResponse<Document>> documentQueryObservable = p.client
.queryDocuments("dbs/" + p.databaseName + "/colls/" + p.collectionId, sql, options);
// observable to an iterator
Iterator<FeedResponse<Document>> it = documentQueryObservable.toBlocking().getIterator();
while (it.hasNext()) {
FeedResponse<Document> page = it.next();
List<Document> results = page.getResults();
// here we iterate over all the items in the page result
for (Object doc : results) {
System.out.println(doc);
}
}
}
}

call procedure with out parameters in hibernate3

I work with hibernate3 and didn't use JPA
I have a procedure in oracle which return 2 out parameter
For test I execute this procedure in oracle with this query.
declare
req_type number;
req_seq number;
begin
insert_req(1111,req_type,req_seq);
dbms_output.put_line('req_type='||req_type);
dbms_output.put_line('req_seq='||req_seq);
end;
Now I want to call this procedure using hibernate
I try with native query without success using this code :
public void insertReq(String numEmp) {
int req_type ;
int req_seq;
String sql = " insert_req(1111,:in1,:in2) ";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("in1", req_type);
query.setParameter("in2", req_seq);
List results = query.list();
System.out.println(req_type);
System.out.println(req_seq);
}
when I have a function I can run it using hibernate using this code as an example :
public void insertOrder(String numEmp) {
String query = "call insert_order(" + numEmp + ",50)";
SQLQuery sqlQuery = this.getSession().createSQLQuery(query);
sqlQuery.executeUpdate();
}
but the problem is how to call procedure with 2 out parameter using hibernate.
you have to use CallableStatement and registerOutParameter.
you can get a connection from your hibernate session and create the callablestatement.
hibernate does not provide a mecanism to deal with this (at least as i know).
i hope that helps.
Try this and let me know.
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.unwrap(Session.class);
session.doWork(new Work() {
#Override
public void execute(Connection con) throws SQLException {
// do something useful
try (CallableStatement stmt = con.prepareCall("{call my_sp()}")) {
stmt.execute();
}
}
});
em.close();
Best regards.

How to convert select-input content to string on sql query?

My html form has 2 select-input field which are sent via HTTP POST as json to my java webserver API and then to my postgresql. Im having a internal error and i believe that is because the select-input json output is like this "field":["value"]
How can i tell java to read the content inside the [ ]?
this is my query
String sqlQuery = "INSERT INTO neuromotora(nervonome,latencia,amplitudedistal,amplitudeprox,velocidade,ondaf,pacienteid,ladonervo)"
+ " VALUES(?,?,?,?,?,?,?,?) RETURNING neuromotoraid";
This is the http post method on my angular frontend
postData(params){
let headers = new Headers();
headers.append('Content-type','application/json');
return this.http.post(this.api,params,{
headers: headers
}).map(
(res:Response) => {return res.json();}
);
And this is the java web server post method
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Path("/neuromotora/")
public Response createNeuromotora(Neuromotora n) throws SQLException, ClassNotFoundException{
neuromotoraDAO dao = new neuromotoraDAO();
dao.insert(n);
return Response
}
And this is the neuromotora java
public class Neuromotora {
private int neuromotoraid;
private String latencia;
private String amplitudeDistal;
private String amplitutdeProx;
private String nervoNome;
private String ladoNervo;
private String ondaF;
private int pacienteid;
...getters and setters..
}
Insert method
public Long insert(Neuromotora oferta) throws SQLException, ClassNotFoundException{
Long id = null;
String sqlQuery = "INSERT INTO neuromotora(nervonome,latencia,amplitudedistal,amplitudeprox,velocidade,ondaf,pacienteid,ladonervo)"
+ " VALUES(?,?,?,?,?,?,?,?) RETURNING neuromotoraid";
try{
PreparedStatement stmt = this.con.getConnection().prepareStatement(sqlQuery);
stmt.setString(1,oferta.getNervoNome());
stmt.setString(2,oferta.getLatencia());
stmt.setString(3,oferta.getAmplitudeDistal());
stmt.setString(4,oferta.getAmplitutdeProx());
stmt.setString(5, oferta.getVelocidade());
stmt.setString(8, oferta.getOndaF());
stmt.setInt(6,oferta.getPacienteid());
stmt.setString(7,oferta.getLadoNervo());
ResultSet rs = stmt.executeQuery();
if(rs.next()){
id = rs.getLong("neuromotoraid");
}
this.con.commit();
}
catch(SQLException e){
this.con.rollback();
throw e;
}
return id;
}
Removing the the multiple="true" on the ion-select and adding size="1" worked for me, the input is no longer a json array.

Spring MVC - delete record from JSP table

I got table in JSP, which is table's mirror image from database (all records and columns are displayed), and next to each row I got button "delete" which deletes row from database by ID. But when I click "delete" button then nothing happens in database, it seems like selected row's ID is null, but at address bar selected ID is displayed. What am I doing wrong?
Controller:
#RequestMapping(value="/checkout.html", method = RequestMethod.POST)
public ModelAndView checkOut(Model model, #RequestParam(value = "id", required = false) String id) throws SQLException{
setAppContext();
clinicService.deletePatient(id);
List<Patient> patients = clinicService.getAllpatients();
model.addAttribute("patients", patients);
ModelAndView checkout = new ModelAndView("CheckOut");
return checkout;
}
DAO:
public void deletePatient(String id) throws SQLException {
String query = "delete FROM virtualclinic.patient WHERE idpatient=?";
Connection con = null;
PreparedStatement ps = null;
con = dataSource.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, id);
int out = ps.executeUpdate();
}
Service:
public void deletePatient(String id) throws SQLException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("clinicconfig.xml");
patientDAO = ctx.getBean("patientDAO", PatientDAOImpl.class);
patientDAO.deletePatient(id);
}
JSP file:
<c:forEach items="${patients}" var="patient">
<tr style="font-size: 10">
<td>${patient.id}</td>
<td>${patient.name}</td>
<td>${patient.lastName}</td>
<td>${patient.gender}</td>
<td>${patient.age}</td>
<td>${patient.phoneNumber}</td>
<td>${patient.address}</td>
<td>${patient.disease}</td>
<td>${patient.condition}</td>
<td>${patient.roomType}</td>
<td>${patient.roomNumber}</td>
<td>${patient.date}</td>
<td><form action="/VirtualClinic/checkout.html?selectedPatient=${patient.id}" method="post"><input type="submit" value="Delete"/></form></td>
</tr>
</c:forEach>
Error(?):
INFO: Mapped "{[/checkout.html],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView org.damian.controller.CheckOutController.infoPatient(org.springframework.ui.M odel) throws java.sql.SQLException
lut 17, 2016 3:16:57 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMa pping register
INFO: Mapped "{[/checkoutPatient.html],methods=[GET]}" onto public org.springframework.web.servlet.ModelAndView org.damian.controller.CheckOutController.checkOut(org.springframework.ui.Model,java.lang.String) throws java.sql.SQLException
Use and GET rather than a POST and because on the url you are using the parameter selectedPatient rather than your expected id - change either/or
Make your controller method get
#RequestMapping(value="/checkout.html", method = RequestMethod.GET)
public ModelAndView checkOut(Model model, #RequestParam(value = "selectedPatient", required = false) String id) throws SQLException{
setAppContext();
clinicService.deletePatient(id);
List<Patient> patients = clinicService.getAllpatients();
model.addAttribute("patients", patients);
ModelAndView checkout = new ModelAndView("CheckOut");
return checkout;
}
change your delete link as follow
<td>delete</td>
I dont see anyreason to make the request by post it is just one parameter, you dont need the form

Prevent Sql Injection (Java)

I want to secure my application from SQL Injection attacks.
First question: What is better way to do it?
The first method: I convert every request to json here:
public JsonObject requestToJson(HttpServletRequest request) throws UnsupportedEncodingException{
request.setCharacterEncoding("UTF-8");
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
return new JsonParser().parse(jb.toString()).getAsJsonObject();
}
If it is best way, to prevent it here, then second question: how to do it here?
The second method: It can be done by Hibernate level. Second question: how to do it?
Thanks this user: Elliott Frisch. He answered in comment.
JPARepository like this already prevented from SQL Injection:
public interface UserRepository extends JpaRepository<User, Integer> {
User findByPhoneNumber(String phoneNumber);
}
Just need to prevent if you using HQL:
String query1 = "select * from MyBean where id = "+ id;
String query2 = "select * from MyBean where id = :id";
Second one, will be secured.
Thanks, everyone.

Categories