I have got a Query. (It's my full DAO method)
#Override
public void addUserRole(UserRole userRole) {
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
String query = "insert into 'user_roles'('role','username') values(%s,%s)";
Session session = this.sessionFactory.getCurrentSession();
List roleAdd = session.createQuery(String.format(query, "'ROLE_USER'", "'acid'")).list();
tx.commit();
}
And it gives me an exception
type Exception report message Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateQueryException: expecting IDENT, found ''user_roles'' near line 1, column 13
[insert into 'user_roles'('role','username') values('ROLE_USER','acid')]; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT, found ''user_roles'' near line 1, column 13
[insert into 'user_roles'('role','username') values('ROLE_USER','acid')] description The server encountered an internal error that prevented it from fulfilling this request.
Here's what your method should look like:
#Override
public void addUserRole(UserRole userRole) {
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
String query = "insert into 'user_roles'('role','username') values(%s,%s)";
Session session = this.sessionFactory.getCurrentSession();
int resultCount = session.createSQLQuery(String.format(query, "'ROLE_USER'", "'acid'")).executeUpdate();
tx.commit();
}
Related
I am trying to create a remote service containing JPQL but I am getting this error for the simplest query.
In my authentication service:
#Override
public Users checkDatabase(String email) {
Query query = entityManager.createQuery("SELECT u from Users u WHERE u.nom = :email", Users.class)
.setParameter("email", email);
Users user = (Users) query.getSingleResult();
return user;
}
and my client code looks like:
String jndiName = "Petroca-ear/Petroca-ejb/AuthenticationServices!com.esprit.services.AuthenticationServicesRemote";
Context context = new InitialContext();
AuthenticationServicesRemote proxy = (AuthenticationServicesRemote) context.lookup(jndiName);
System.out.println(proxy.checkEmail("test#s"));
Users user = (Users) proxy.checkDatabase("peter");
while executing this, I am getting this error:
false
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.String
at org.jboss.ejb.client.remoting.ProtocolMessageHandler.readAttachments(ProtocolMessageHandler.java:55)
at org.jboss.ejb.client.remoting.InvocationExceptionResponseHandler$MethodInvocationExceptionResultProducer.getResult(InvocationExceptionResponseHandler.java:82)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:276)
at org.jboss.ejb.client.EJBObjectInterceptor.handleInvocationResult(EJBObjectInterceptor.java:64)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:290)
at org.jboss.ejb.client.EJBHomeInterceptor.handleInvocationResult(EJBHomeInterceptor.java:88)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:290)
at org.jboss.ejb.client.TransactionInterceptor.handleInvocationResult(TransactionInterceptor.java:46)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:290)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocationResult(ReceiverInterceptor.java:129)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:265)
at org.jboss.ejb.client.EJBClientInvocationContext.awaitResponse(EJBClientInvocationContext.java:453)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:202)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy2.checkDatabase(Unknown Source)
at TEST.testPetroca.main(testPetroca.java:23)
public static int add_Book(String title, String auth_name, String publisher, String genre) {
Transaction tx = session.beginTransaction();
Query query = session.createQuery
("INSERT INTO Book(title,auth_name,publisher,genre)"
+ "SELECT "+title+", "+auth_name+", "+publisher+", "+genre);
tx.commit();
return query.executeUpdate();
and this error
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalStateException: No data type for node:
org.hibernate.hql.internal.ast.tree.IdentNode +-[IDENT] IdentNode:
'q' {originalText=q}...
'q' is JTextField data
insert 'q' to 'title'
... Help would BE appreciated..
Just do it
public static void addBook(String title, String authName, String publisher, String genre) {
session.save(new Book(title, authName, publisher, genre));
}
Obviously, you should wrap that method with session/transaction control code.
And, please, always use Java Naming Convention!
auth_name, add_Book are incorrect names — use authName, addBook instead.
I think the answer of #v.ladynev is good but you can also try like this :
public static void addBook(String title, String authName, String publisher, String genre) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
// create book Object
Book book = new Book();
book.setTitle(title);
book.setAuthName(authName);
book.setPublisher(publisher);
book.setGenre(genre);
try {
tx = session.beginTransaction();
// Save the book to database
session.save(book);
tx.commit();
}catch(Exception e){
if (tx!=null) {
tx.rollback();}
e.printStackTrace();
}finally{
// close your session
session.close();
}
}
Use at least the Bean class to code "cleanly". We use the query only in special cases, otherwise we must at most avoid it in the code or use at least bundle resources.
Anything else checks that in your Book bean class you havesetAuthName and not setAuth_Name.
I'm trying to use ResultSetExtractor to send a SQL statement to the database, but the method is getting stuck at the line l.setId(resultSet.getInt("Id"));.
This is my error message:
"message": "PreparedStatementCallback; uncategorized SQLException for
SQL [SELECT Cities.Name FROM cities INNER JOIN Notes on Cities.Id = Notes.CitiesId WHERE Notes.CitiesId = ? AND Notes.id = ?]; SQL state [S0022]; error code [0]; Column 'Id' not
found.; nested exception is java.sql.SQLException: Column 'Id' not
found.",
The Cities table has 3 columns named Id, Name, and Code. I checked my SQL statement in Workbench and it is correct. What's wrong with my code?
public List<Cities> GetCity(String CityId, String NoteId) {
final String sql = "SELECT Cities.Name FROM cities INNER JOIN Notes on Cities.Id = Notes.CitiesId WHERE Notes.CitiesId = ? AND Notes.id = ?";
final List<Cities> cityList = jdbcTemplate.query(sql, new ResultSetExtractor<List<Cities>>() {
#Override
public List<Cities> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
List<Cities> list = new ArrayList<Cities>();
while (resultSet.next()) {
Cities l = new Cities();
l.setId(resultSet.getInt("Id"));
l.setName(resultSet.getString("Name"));
l.setCode(resultSet.getString("Code"));
list.add(l);
}
System.out.println(list);
return list;
}
}, CityId, NoteId);
return cityList;
}
I am working on a Spring-MVC appplication with Hibernate and PostgreSQL in which these days we are experiencing a very strange problem. Sometimes when an object is being persisted, I am returning it's ID from the DAO layer to the service layer. This ID is then being broadcasted via our PUSH framework, after which point the object is retrieved by a call. At this point I am getting a NPE, although the object is saved, primary-key ID is non-zero, session is also flushed before returning the ID. What might be going wrong?
Example :
#Override
public void addNestedGroupNoteComment(String commentText, int noteId, int commentId){
int saveId = this.groupNoteHistoryDAO.addGroupNoteComment(groupNoteHistory, noteId);
if(saveId!=0) {
notification.setCommentId(saveId);
this.chatService.sendNotification(notification, groupMembers.getMemberid());
}
DAO method :
#Repository
#Transactional
public class GroupNoteHistoryDAOImpl implements GroupNoteHistoryDAO {
private final SessionFactory sessionFactory;
#Autowired
public GroupNoteHistoryDAOImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public int addGroupNoteComment(GroupNoteHistory noteHistory, int noteId) {
Session session = this.sessionFactory.getCurrentSession();
GroupNotes notes = (GroupNotes) session.get(GroupNotes.class, noteId);
if(notes!=null) {
notes.getGroupNoteHistorySet().add(noteHistory);
noteHistory.setMhistory(notes);
int saveId = (Integer) session.save(noteHistory);
session.flush();
return saveId;
}
}
}
Now, after broadcasting the ID, this method is called :
#Override
public GroupNoteHistory getGroupNoteHistoryById(int historyId) {
GroupNoteHistory groupNoteHistory = this.groupNoteHistoryDAO.getGroupNoteHistoryById(historyId);
// Above object is many times null, tried System.out, it was with non-zero values.
}
DAO method :
#Override
public GroupNoteHistory getGroupNoteHistoryById(int historyId) {
Session session = this.sessionFactory.getCurrentSession();
return (GroupNoteHistory) session.get(GroupNoteHistory.class, historyId);
}
Any thoughts?
Update
Error log :
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
root cause
java.lang.NullPointerException
com.project_name.spring.service.GroupNoteHistoryServiceImpl.getGroupNoteHistoryById(GroupNoteHistoryServiceImpl.java:156)
sun.reflect.GeneratedMethodAccessor647.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
Here int saveId = this.groupNoteHistoryDAO.addGroupNoteComment(groupNoteHistory, noteId); you already have a GroupeNoteHistory.
After this you manipulate it and save it
noteHistory.setMhistory(notes);
int saveId = (Integer) session.save(noteHistory);
session.flush();
return saveId;`
So you must check if the GroupNoteHistory already exists and is not null before using it. That's why you get a NPE.
Finally this worked for me :
#Override
public int addGroupNoteComment(GroupNoteHistory noteHistory, int noteId) {
Session session = this.sessionFactory.openSession();
try {
session.beginTransaction();
GroupNotes notes = (GroupNotes) session.get(GroupNotes.class, noteId);
if(notes!=null) {
notes.getGroupNoteHistorySet().add(noteHistory);
noteHistory.setMhistory(notes);
session.save(noteHistory);
session.flush();
session.getTransaction().commit();
return noteHistory.getMhistoryid();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
session.close();
}
return 0;
}
I've a problem using Hibernate, after executing one of my queries I get the following Log messages and the program stops to work:
20:36:48,805 TRACE ThreadLocalSessionContext:344 - allowing proxied method [createQuery] to proceed to real session
4608 [main] TRACE org.hibernate.context.ThreadLocalSessionContext - allowing proxied method [createQuery] to proceed to real session
20:36:48,806 TRACE QueryPlanCache:128 - located HQL query plan in cache (from Propertylist where typedlistId = ?)
4609 [main] TRACE org.hibernate.engine.query.QueryPlanCache - located HQL query plan in cache (from Propertylist where typedlistId = ?)
In practice I have a small method where I call:
public List<Zielobjekt> gibZielobjekte() {
List<Zielobjekt> zielobjekte = new ArrayList<Zielobjekt>();
Session session = _sessionFactory.getCurrentSession();
session.beginTransaction();
for(Informationsverbund iv : gibInformationsverbuende() /*Behind this method is a Hibernate query, it works fine.*/ )
{
Set<Celement> zobjekte = gibBaumelementeFuerVater(session, iv.getOriginalId());
LOGGER.info("Insgesamt " + zobjekte.size() + " ZO gefunden.");
for(Celement element : zobjekte)
{
Set<Propertylist> eigenschaften = gibEigenschaftsliste(session, element); /*Behind this Method is a Hibernate Query, here the Program stops to work.*/
//HERE THE PROGRAM STOPS WORKING
...
}
}
session.getTransaction().commit();
return zielobjekte;
}
The method called, where the program stops working is:
private Set<Propertylist> gibEigenschaftsliste(Session session, Celement element)
{
try
{
return new HashSet(session.createQuery(
"from Propertylist where typedlistId = ?")
.setInteger(0, element.getEntityId())
.list());
}
catch (HibernateException e)
{
e.printStackTrace();
return null;
}
}