I want to know if it's possible to create custom query for liferay default table like user, userGroup...
I looked at the example but they give examples that on the custom tables (guestbook table)
try this code
public List<User> getUserByRecentChat(long userId){
Session session=null;
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
try {
session = sessionFactory.openSession();
String sql = CustomSQLUtil.get(getClass(), "getUserByRecentChat");
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.setCacheable(false);
sqlQuery.addEntity("users_", UserImpl.class); // for user table
QueryPos pos = QueryPos.getInstance(sqlQuery);
pos.add(userId);
pos.add(userId);
return (List<User>) sqlQuery.list();
} catch (Exception e) {
e.printStackTrace();
} finally {
sessionFactory.closeSession(session);
}
return null;
}
Yes you can use Custom Query for Liferay Default Tables
Thanks
Related
I am using hibernate in my automation testing project, to execute a database 'clean-up routine' that is:
disabling constraints for all tables in the database
removing records by ID's that I stored when creating records used for my automation testing
enabling constraints for all tables in the database
Here is my pseudo code:
private SessionFactory sessionFactory;
private void initialize()
{
try
{
Configuration config = createHibernateConfiguration();
addAnnotatedClassesForClientDB(config);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(config.getProperties());
serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = config.buildSessionFactory(serviceRegistry);
}
catch (HibernateException e)
{
logger.error("Problem creating session factory!");
e.printStackTrace();
}
}
public Session openSession()
{
Session session = sessionFactory.openSession();
session.beginTransaction();
return session;
}
public void cleanClientDatabase()
{
Session session = openSession();
try
{
logger.info("Client DB cleaning started...");
String combinedQuery = // her comes my SQL query
Query query = session.createNativeQuery(combinedQuery);
query.executeUpdate();
closeSession(session);
}
catch (Exception e)
{
logger.error("Failed cleaning Client DB! " + e.getClass().getSimpleName());
e.printStackTrace();
session.getTransaction().rollback();
session.close();
}
}
Now from time to time, it sticks at query.executeUpdate(); in cleanClientDatabase() method and will hang there forever, until I manually kill transaction in Microsoft SQL Management studio by PID.
For some reason an exception is never thrown so I can't tell what is the error, I suspect some sort of lock, what can I do to avoid this issue and fix my code?
Thank you.
I'm using Hibernate 4.2.6 with Java DB
Here's my
RegisterationHelper.java
org.hibernate.Transaction tx = session.beginTransaction();
String uid = std.getUserid();
System.out.println(uid);
Query query = session.createQuery("FROM university.Student");
List<Student> student = query.list();
for(Iterator it= student.iterator(); it.hasNext();)
{
//some code....
{
try
{
tx = session.beginTransaction();
int rgstnum=0;
Query q = session.createQuery("Select max(registrationnumber)from Student");
List currentRegNo = q.list();
rgstnum=(Integer)currentRegNo.get(0)+1;
std.setRegistrationnumber(rgstnum);
sc.setRegistrationnumber(rgstnum);
Serializable objID=session.save(std);
session.saveOrUpdate(sc);
tx.commit();
}
catch(Exception e)
{
}
//priniting sc.getRegistrationnumber() showing null
//priniting sc.getCurseid() has data
and RegistrationForm.java
#ManagedBean
#RequestScoped
public class RegistrationForm {
public String submitAction() {
RegistrationHelper rghp = new RegistrationHelper();
Student std = new Student();
std.setFirstname(getFirstName().toString());
std.setLastname(getLastName().toString());
std.setGender(getGender().toString());
std.setDob(getDateofBirth());
std.setAddress(getAddress().toString());
std.setPhone(getContactNumber().toString());
std.setEmail(getEmailID().toString());
std.setUserid(getUserID().toString());
std.setPassword(getPassword().toString());
Studentcourse sc = new Studentcourse();
sc.setCourseid(getCourse().toString());
String msg = rghp.insertStudent(std, sc);
if(msg.equals("error"))
{
setUserIdError("User Id already exist");
setUserID("");
return "Registration";
}
else
{
return "Success";
}
}`
So I think there is problem only with query Query q = session.createQuery("Select max(registrationnumber)from Student"); that doesn't retrieving registrationumber cause I'm able to store data in Student table if removing code regarding StudentCourse and other thing is getting Info: nested transactions not supported in sever log.
So please if my query is wrong or something else.
I do not think there are problems in the query: the message nested transactions not supported refers to the fact that you open the transaction (session.beginTransaction()) twice, one at the beginning and then again within the cycle. Try to remove the second.
i write class to fetch data using hibernate query. when i get Session from EntityManager using
Session session=null;
sessionFactory=entityManager.unwrap(SessionFactory.class);
session=(Session) sessionFactory.getCurrentSession();
or
Session session = (Session) entityManager.getDelegate();
and session agin asking cast the session into EntityManager
public class BranchCustomRepositoryImpl implements BranchCustomRepository{
#PersistenceContext
private EntityManager entityManager;
private SessionFactory sessionFactory;
public Branch findByOrgOrgIdAndBranchId(String orgId, String branchId) {
//Session session=null;
//sessionFactory=entityManager.unwrap(SessionFactory.class);
//session=(Session) sessionFactory.getCurrentSession();
Session session = (Session) entityManager.getDelegate();
System.out.println("BranchCustomRepositoryImpl");
Long orgId2=Long.valueOf(orgId);
Long branchId2=Long.valueOf(branchId);
try{
Query query= (Query)((EntityManager) session).createQuery("from Branch b where b.org.orgId=:orgId AND b.branchId=:branchId");
query.setParameter("orgId", orgId2);
query.setParameter("branchId", branchId2);
return (Branch) query.uniqueResult();
}catch(Exception e){
System.out.println("Exception"+e.toString());
}finally{
try {
if(session!=null){
session.close();
System.out.println("session closed");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
it getting error like,
java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Long (n/a)]
if any one know how to use hibernate query in spring data jpa please help me
Since the type of persistent attribute orgId2 is Long, the corresponding
type argument should also be Long while creating the ParameterExpression. And consequently, because type of the ParameterExpression is Long, type of the parameter's value should also be Long as well. So do the following change when you setting query parameters.
Instead of your current lines such as below
query.setParameter("orgId", orgId2);
query.setParameter("branchId", branchId2);
Change it like below
query.setParameter("orgId", Long.valueOf(orgId2));
query.setParameter("branchId", Long.valueOf(branchId2));
i am want output name of columns from table of my database on MySql. I am use Rest on Java, maven, tomcat, hibernate.
this code not work:
personDao.java:
public List<Person> getHeaders() {
List<Person> persons = null;
Session session = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
persons = session.createQuery("SHOW FIELDS FROM person").list();
session.getTransaction().commit();
} catch (Exception ex) {
if (session != null) {
session.getTransaction().rollback();
}
} finally {
if (session != null) {
session.close();
}
}
return persons;
}
service.java:
#GET
#Path("/getHeaders")
#Produces(MediaType.APPLICATION_JSON)
public List<Person> getHeaders() {
return personDao.getHeaders();
}
Please help me, how output name of columns ?
You can use the information_schema database and then use a standard hibernate query definition. In the information schema you can use a query as:
select * from COLUMNS WHERE table_name='person';
You can see this post: Get column name of property mapped with Hibernate
((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
.getProperty("myProperty").getColumnIterator().next()).getName();
and Get table column names in Hibernate
How do I load a list of Strings for a brand new, empty, non-existent table in AppEngine? I tried to follow this example:
http://www.objectdb.com/java/jpa/query/jpql/select#Projection_of_Path_Expressions_
but it gives me an error:
Caused by: javax.persistence.PersistenceException: Class AdminUser for query has not been resolved. Check the query and any imports/aliases specification
Caused by: org.datanucleus.exceptions.ClassNotResolvedException: Class AdminUser for query has not been resolved. Check the query and any imports/aliases specification
Here is the code:
public java.util.List<String> getAdmin() {
EntityManager em = EMF.get().createEntityManager();
try {
TypedQuery<String> tq = em.createQuery("select au.email from AdminUser as au", String.class);
return tq.getResultList(); ///// <=== EXCEPTION
I don't actually want to use an AdminUser class. I only want the single column of Strings. It is not obvious how to create a new empty table on AppEngine.
GAE Datastore is a schemaless NoSQL database. There are no tables. Only entities that must have a kind, an id and can have an arbitrary set of properties.
You can use Datastore via JPA API, to give you nice typed Java classes instead of low-level untyped entities.
AppEngine does not support JPA raw primitive queries as in the example link. I had to use the DatastoreService API directly. Here is what I tried. Needs some cleaning as many of the things did not work, but this did.
public java.util.List<String> getAdmin() {
log.info("getAdmin()");
// AppEngine does not support strong consistency... will frequently return stale results. Setting read policy won't work.
// Construct a read policy for strong consistency
ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.STRONG);
// Set the read policy
DatastoreServiceConfig consistentConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy);
// Get Datastore service with the given configuration
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService(consistentConfig);
com.google.appengine.api.datastore.Query query = new com.google.appengine.api.datastore.Query("AdminUser");
// DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
java.util.List<Entity> events = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
ArrayList<String> al = new ArrayList<String>();
for(Entity entity: events) {
String s = entity.getProperty("email").toString();
al.add(s);
}
if(true) return al;
#SuppressWarnings("unused")
EntityManager em = EMF.get().createEntityManager();
try {
TypedQuery<String> tq = em.createQuery("select au.email from AdminUser as au", String.class);
return tq.getResultList();
} catch (ClassNotResolvedException | javax.persistence.PersistenceException cnre) {
// catch the exception because AppEngine DataStore has no way to create a new empty Entity table.
log.warning("AdminUser entity does not exist or is empty.");
return new java.util.ArrayList<String>();
} finally {
em.close();
}
// log.info("getAdmin(): al.size(): " + al.size());
}
public void setAdmin(java.util.List<String> admin) {
log.info("setAdmin(), admin.size():"+admin.size());
// delete all AdminUsers
com.google.appengine.api.datastore.Query query = new com.google.appengine.api.datastore.Query("AdminUser");
DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
java.util.List<Entity> events = datastoreService.prepare(query).asList(FetchOptions.Builder.withDefaults());
for(Entity entity: events) {
datastoreService.delete(entity.getKey());
}
// EntityManager em = EMF.get().createEntityManager();
// Query q = em.createQuery("delete from AdminUser");
// q.executeUpdate();
// DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();
for (String s: admin) {
log.info("creating AdminUser Entity...");
Entity e = new Entity("AdminUser");
e.setProperty("email", s);
datastoreService.put(e);
}
// Must wait for Datastore to actually write records. Ignores consistency even with strong consistency set.
// this doesn't even work sometimes...
//try { Thread.sleep(5000); } catch (InterruptedException e) {}
// EntityManager em = EMF.get().createEntityManager();
// for (String s: admin) {
// Entity e = new Entity("AdminUser");
// e.setProperty("email", s);
// em.persist(e);
// }
// em.close();
} // setAdmin()