简体   繁体   English

休眠HQL查询选择

[英]hibernate HQL Query select

i wanna transfer this code SQL to HQL i try this code but it dosn't work 我想将此代码SQL传输到HQL,请尝试使用此代码,但它不起作用

public Admin connect(String login, String password)
{
SessionFactory sessionFactory =createSessionFactory();
Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();
  Admin admin=(Admin) session.createQuery(from admin where login_admin='"+login+"' and password_admin='"+password+"');
    session.getTransaction().commit();

    return admin;

my class 我的课

public class Admin extends personne implements java.io.Serializable {
private String loginAdmin;
private String passwordAdmin;}

sorry for my bad english 对不起,我的英语不好

Hibernate will Convert your HQL to SQL.And you can write HQL query as given below to get a particular object(or record). Hibernate会将您的HQL转换为SQL。您可以按照以下说明编写HQL查询,以获取特定的对象(或记录)。 createQuery() expects HQL query not SQL query. createQuery()期望HQL查询而不是SQL查询。 If your class is like this 如果你的班是这样的

class Admin{
String loginAdmin;
String passwordAdmin;
}

Change your SQL query to HQL as given below 如下所示将您的SQL查询更改为HQL

Admin admin=(Admin) session.createQuery
(from Admin where loginAdmin='"+login+"' and passwordAdmin='"+password+"').uniqueResult();

You can refer uniqueResult() method here 您可以在此处引用uniqueResult()方法

In order to call sql queries call session.createSQLQuery(sql query here); 为了调用sql查询,请调用session.createSQLQuery(此处为sql query); So your code is wrong. 因此,您的代码是错误的。

In order to call HQL queries call: 为了呼叫HQL查询,请呼叫:

session.createQuery("from Admin where loginAdmin='"+login+"' and passwordAdmin='"+password+"'"); 

This is assuming the class is Admin with properties login and password 这是假设该类是具有属性登录名和密码的Admin。

Use the following code: 使用以下代码:

Query query = session.createQuery("from Admin where loginAdmin= :login and password = :passwordAdmin");
query.setParameter("login", login);
query.setParameter("password", password );
Admin admin = (Admin)query.uniqueResult();

Creating the HQL query (or any other type of DB query that is) by concatenating Strings is a bad idea since that way you are opening up your system to SQL injections! 通过串联字符串来创建HQL查询(或任何其他类型的数据库查询)是一个坏主意,因为那样会向SQL注入开放系统!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM