命名查询或本机查询或查询哪一个在性能上更好?
以下哪一个更好(EJB 3 JPA)
Which one is better among following(EJB 3 JPA)
//查询
a)。 getEntityManager()。createQuery (从用户o中选择o);
a). getEntityManager().createQuery("select o from User o");
//命名查询在实体级别定义findAllUser
//Named Query where findAllUser is defined at Entity level
b)。 getEntityManager()。createNamedQuery (User.findAllUser); **
b). getEntityManager().createNamedQuery("User.findAllUser");**
//原生查询
c)。 getEntityManager()。createNativeQuery (SELECT * FROM TBLMUSER);
c). getEntityManager().createNativeQuery("SELECT * FROM TBLMUSER ");
请解释一下哪种方法更好?
Please explain me which approach is better in which case?.
-
createQuery()
它应该用于动态查询创建。
-
createQuery()
It should be used for dynamic query creation.
//Example dynamic query
StringBuilder builder = new StringBuilder("select e from Employee e");
if (empName != null) {
builder.append(" where e.name = ?");
}
getEntityManager().createQuery(builder.toString());
createNamedQuery()
它就像常量变量和可重用,你应该在常见的db调用中使用它;查找所有用户,按ID查找等。
createNamedQuery()
It is like constant variable and reusable, and you should use it in common db calls like; find all users, find by id, etc.
完全取决于底层数据库支持的sql脚本。
It totally depends on underlying database supported sql script.
当需要复杂查询且不支持JPQL语法时,它非常有用。
It is useful when a complex query is required and JPQL syntax not supported it.
但它可能会影响如果底层数据库从一个数据库更改为另一个数据库,则应用程序需要更多工作。例如,如果您的开发环境使用MySQL,并且您的生产环境使用的是Oracle。 + 如果超过单个结果,返回的结果绑定可能很复杂。
But it can impact your application and need more work, if the underlying database is changed from one to another. Example case like, if your development env is using MySQL, and your production env is using Oracle. + And returned result binding can be complex if more than single result.