I am trying to fetch session id of the user but the session id is coming as null. Below is the sample code I have used
RestAssured.baseURI="https://demo.com"
Response response = RestAssured.given().
header("Content-Type","application/json").header("connection","keep-alive").header("Accept-Encoding","gzp,deflate,br")
.body(" {n" +
""usename": "demo",n" +
""email": "demo#abc.com"n" +
"}")
.post("/login\r\n");
System.out.println(response.getSessionId());
System.out.println(response.getCookies());
I am expecting the session id and cookie of user logged in but I am getting value as null.
Related
I have a table called ad_session which logs user sessions. I am using Java to get a list of all successful sessions from that table. I then loop through that list to get the user for each session (which is a foreign key to the ad_user table). I then get the client that belongs to that user, and I add the client to a list. However, one of the users no longer exists, so my code stops running and it gives throws the following exception:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ADUser#76A5C22E6D2446A399AE9AD7C1DED0C7]
This is my original code:
List<Session> sessions = getAllSuccessfulSessionsInTable();
List<Client> clientsForThatDay = new ArrayList<>();
try {
for (Session session : sessions) {
//code fails when trying to get the non-existent user:
User user = session.getCreatedBy();
Client userClient = user.getClient();
clientsForThatDay.add(userClient);
}
} catch (Exception e) {
log.error("Error getting client from user: ", e);
}
I assumed that when getting a non-existent record, it would return null, so this is what I tried:
List<Session> sessions = getAllSuccessfulSessionsInTable();
List<Client> clientsForThatDay = new ArrayList<>();
//Create new user object to stand in place of the non-existent user
User deletedUser = new User();
deletedUser.setName("Deleted User");
//Create new client object to stand in place of the non-existent client
Client deletedUserClient = new Client();
deletedUserClient.setName("Unknown Client");
try {
for (Session session : sessions) {
//check is User is null, if it is, use the deletedUser object, otherwise, use the existing user
User user = session.getCreatedBy() == null ? deletedUser : session.getCreatedBy();
Client userClient = user.getName().equals("Deleted User") ? deletedUserClient : user.getClient();
clientsForThatDay.add(userClient);
}
} catch (Exception e) {
log.error("Error getting client from user: ", e);
}
However, it is not returning null, it's just throwing the exception and then stopping.
How can I get it to return null here so I can deal with the missing record without my code stopping?
Thanks in advance for any suggestions.
It seems that your database is missing a foreign key constraint.
This means that the table mapping User has a reference to a row in the table for Client that no longer exist.
This can only happen if a client has been deleted without updating the user table. The solution would be to add a foreign key constraint between the tables.
Keep in mind that if the data in your tables are not correct, when Hibernate loads the entity User, it will also believe there's a client. This means that User#getClient won't be null, and every place in the code where you have a check like user.getClient() == null is going to fail. A try-catch approach won't help you with this (unless you set the association to null in case of error, I guess).
The solutions I can think of:
Add the foreign key constraint (imho, the best solution)
Don't map the association, map client_id as an attribute and load the client using a second query or find (I would only do this if you cannot update the database)
class User {
#Column(name = "client_id")
Long clientId;
}
User user = ...
Client client = session.find(Client.class, user.getClientId());
You can load the client via session.find(Client.class, user.getClient().getId()) and set the association with the result:
User user = //...
Client client = session.find(Client.class, user.getClient().getId());
user.setClient(client);
Don't map the association at all in User, and run a native SQL query to load the client:
User user = ...
String sql = "select * from Client c join User u on c.id = u.client_id where u.id = :uid";
Client client = session.createNativeQuery(sql, Client.class)
.setParameter("uid", user.getId())
.getSingleResultOrNull();
You can pick what works best for you, but keep in mind that mapping an association without the foreign key constraint, will cause all sort of consistency issues.
I've decided to put option 3 only because, sometimes, people have some impossible situations at work, but I wouldn't recommend it.
I have two applications - Server that has connection with database and Client which doesn't. Server loads entity and sends it to Client. Client edits it and sends it back so that Server can update it. But... there are many Clients and many of them can edit that entity and want to update it with their own value but I want Server to update it only if it hasn't been updated since it had been send to Client. Namely: Clients try to set ticket's status to their own value but only if current status in database is the same that it was when that Client received it. Currently I have it like that:
public boolean changeStatus (Ticket ticket, short newStatus) {
short previousStatus = ticket.getStatus();
boolean result = false;
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
String sql = "UPDATE ticket SET status = :newStatus WHERE idTicket = :idTicket AND status = :previousStatus";
NativeQuery query = session.createSQLQuery(sql);
query.setParameter("idTicket", ticket.getIdTicket());
query.setParameter("newStatus", newStatus);
query.setParameter("previousStatus", previousStatus);
result = query.executeUpdate() == 1;
but sometimes I also want to set other atributes and check if other atributes hasn't changed and using that method would make it very ugly and I want it to be more object-oriented not plain sql. Any suggestions?
Forgot to mention that each Client has it's own Server thread that might try to update
I need a User entity that has a primary key ID and two unique not null (not primary) keys: email and username. Then I receive a username and an email and I need to retrieve a User entity that has either that received username or email.
I see that #NaturalId makes a column unique and not null. The problem is that when you have more than one #NaturalId, Hibernate creates a unique index on the pair (email, username), meaning that it won't be any rows with same pair (email, username) but it may appear one that has same email but different username.
Can it be solved with #NaturalId? If is possible how would I retrieve the entity matching either the received username or email but not necessarily both.
If it's not possible, would this be the optimal solution?
final Session session = HibernateUtil.openSession();
final CriteriaBuilder builder = session.getCriteriaBuilder();
final CriteriaQuery<User> criteria = builder.createQuery(User.class);
final Root<User> userRoot = criteria.from(User.class);
criteria.where(builder.equal(userRoot.get("username"), username));
/* How do I join the criteria for username and email using ||?
So that it gets me an entity that has that email or username. */
final User foundUser = session.createQuery(criteria).uniqueResult();
your query will like:
Session session = HibernateUtil.getSession();
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.disjunction()
.add(Restrictions.eq("username", value))
.add(Restrictions.eq("email", value)));
User user = (User)criteria.setMaxResults(1).uniqueResult();
Hql query :
Query query = session.createQuery("from User as s where s.username = :userInputValue or s.email =:userInputValue");
query.setParameter("userInputValue", userInputValue);
query.setMaxResults(1);
User user = (User) query.uniqueResult();
you can't get unique result with your given result, because as you have mentioned, it may possible we have 2 rows which one of them have a username like "Jom#test.com" and another row have email "Jom#test.com".
So it's possible scenario to not get unique value, for fix it you need make a 2 unique constraint of any of filed, basically you need 2 unique filed in one row.
How to get the value which being saved to database after
entityManager.persist
I am able to get the primary key value from database after calling persist not any other values.
E.g.
public void create(Project project) {
entityManager.persist(project);
System.out.println("Id -- " + project.getProjectId());
System.out.println("no -- " + project.getProjectNo());
}
From the above code I am able to get the newly inserted value from project.getProjectId, however not able to get project.getProjectNo
The reason why I am able to get projectId is because it is primary key?
How can I get the value of getProjectNo after persist?
Try refreshing the entity with the database to get the inserted trigger value.
public void create(Project project) {
entityManager.persist(project);
entityManager.getTransaction().commit();
project = entityManager.find(Project.class, project.getProjectId());
entityManager.refresh(project);
System.out.println("Id -- " + project.getProjectId());
System.out.println("no -- " + project.getProjectNo());
}
Documentation
I am developing web application using restful web service.
I have used hibernate and POJO to mysql communication.
I have database which has the user table and the primary is the empid.
For getting the single row, I have passed the empid from html page to the web service and return the json object to the html page(javascript is used for parsing).
I have used this one to get the single row from DB where empid=277; // Hardcoded here
new_user = (User) session.get(User.class, (long)277);
I want to retrieve record from other column like employeeid( NOT empid,empid is primary key)
select * user where employeeid="XX-123XD"
I have passed the employeeid from html page which is string.
I have written web service like
#POST
#Path("/getjson")
#Produces("application/json")
public JSONObject sendjson(String employeeid) {
Gson gsonobj = new Gson();
JSONObject jsonobj = null;
SessionFactory fact;
fact = new Configuration().configure().buildSessionFactory();
User new_user = null;
Session session = fact.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from user where employeeid= :employee");
query.setParameter("employee", employeeid);
//new_user = (User) session.get(User.class, (long)277);
new_user = (User) query.list();
try {
String jsonstr = gsonobj.toJson(new_user);
jsonobj = new JSONObject(jsonstr);
} catch (JSONException ex) {
Logger.getLogger(Authneticate.class.getName()).log(Level.SEVERE, null, ex);
}
return jsonobj;
}
But i get the error like,
type Exception report
message com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class org.codehaus.jettison.json.JSONObject, and Java type class org.codehaus.jettison.json.JSONObject, and MIME media type text/html; charset=utf-8 was not found
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class org.codehaus.jettison.json.JSONObject, and Java type class org.codehaus.jettison.json.JSONObject, and MIME media type text/html; charset=utf-8 was not found
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class org.codehaus.jettison.json.JSONObject, and Java type class org.codehaus.jettison.json.JSONObject, and MIME media type text/html; charset=utf-8 was not found
com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:561)
com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:517)
org.apache.jsp.HomeUser_jsp._jspService(HomeUser_jsp.java:91)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
If I removed Query statements, and uncomment the code then that block is
Session session = fact.getCurrentSession();
Transaction tx = session.beginTransaction();
//Query query = session.createQuery("from user where employeeid= :employee");
//query.setParameter("employee", employeeid);
new_user = (User) session.get(User.class, (long)277);
//new_user = (User) query.list();
then it works and gives the expected result for empid=277 which is primary key.
What I am doing wrong with Query.
And Is there any other way with hibernate to get data without primary key
like
`new_user = (User) session.get(User.class, employeeid);`
|
String(Not the primary key)
My jsp file which gets the JSON object is
<%
Client client = Client.create();
WebResource service = client.resource("http://localhost:8080/ITHelpdesk/webresources/hello/getjson");
String input = request.getParameter("username");
ClientResponse cliresponse = service.type("text/html").post(ClientResponse.class,input);
JSONObject jsonobj = cliresponse.getEntity(JSONObject.class);
%>
I have tried using using new_user = (User) query.uniqueResult();
Then also same error occurred JSONObject jsonobj = cliresponse.getEntity(JSONObject.class);
Thank you
Please use Query method uniqueResult().
Query query = session.createQuery("from user where employeeid= :employee");
query.setParameter("employee", employeeid);
new_user = (User) query. uniqueResult();
the client side exception you posted doesn't help, can you provide the server side exception stacktrace? we have to know what hibernate complaints
resolved,
instead of
Query query = session.createQuery("from user where employeeid= :employee");
query.setParameter("employee", employeeid);
I have added,
Query query = session.createQuery("from user where employeeid='" + employeeid + "'");
And it works fine