实现按条件查询
第一步: 定义接口: public interface ICommonDaoT { ListT findCollectionByConditionNoPage(String codition,Object[] params, MapString, String orderby); } 第二步: 实现接口的类: Class entityClass = TUtils.getTClass(this.getClass());public cl
第一步:
定义接口:
public interface ICommonDao
List
}
第二步:
实现接口的类:
Class entityClass = TUtils.getTClass(this.getClass()); public class TUtils { /**泛型转换,目的获取子类传递父类的真实类型,也就是T所对应的类型*/ public static Class getTClass(Class entity) { ParameterizedType type = (ParameterizedType)entity.getGenericSuperclass(); Class entityClass = (Class) type.getActualTypeArguments()[0]; return entityClass; } }
/**指定查询条件查询对应的结果,返回List(不分页)*/ /** * FROM ElecText o WHERE 1=1 #Dao层 AND o.textName LIKE '%张%' #Service层 AND o.textRemark LIKE '%张%' #Service层 ORDER BY o.textDate ASC,o.textName DESC #Service层 */ public List<T> findCollectionByConditionNoPage(String condition, final Object[] params, Map<String, String> orderby) { //定义hql语句 String hql = "FROM "+entityClass.getSimpleName()+" o WHERE 1=1"; //定义排序语句 String orderbyHql = this.orderbyHql(orderby); //定义最终的语句 final String finalHql = hql + condition + orderbyHql; //执行语句一 //List<T> list = this.getHibernateTemplate().find(finalHql, params); //执行语句二 // SessionFactory sf = this.getHibernateTemplate().getSessionFactory(); // Session s = sf.getCurrentSession(); // Query query = s.createQuery(finalHql); // List<T> list = query.list(); //执行语句三 List<T> list = this.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(finalHql); if(params!=null && params.length>0){ for(int i=0;i<params.length;i++){ query.setParameter(i, params[i]); } } return query.list(); } }); return list; } /**组织排序的语句*/ /*ORDER BY o.textDate ASC,o.textName DESC*/ private String orderbyHql(Map<String, String> orderby) { StringBuffer buffer = new StringBuffer(""); if(orderby!=null && orderby.size()>0){ buffer.append(" order by "); for(Map.Entry<String, String> map:orderby.entrySet()){ buffer.append(map.getKey()+" "+map.getValue()+","); } //删除最后一个逗号 buffer.deleteCharAt(buffer.length()-1); } return buffer.toString(); }
下面是根据不同的业务来编写不同的代码。
第三步:
service接口:
public interface IElecTextService { public static final String SERVICE_NAME = "com.itheima.elec.service.impl.ElecTextServiceImpl"; List<ElecText> findCollectionByConditionNoPage(ElecText elecText); }
第四步:
service实现
/**指定查询条件查询对应的结果,返回List*/ /** * FROM ElecText o WHERE 1=1 #Dao层 AND o.textName LIKE '%张%' #Service层 AND o.textRemark LIKE '%张%' #Service层 ORDER BY o.textDate ASC,o.textName DESC #Service层 */ public List<ElecText> findCollectionByConditionNoPage(ElecText elecText) { //查询条件 String condition = ""; List<Object> paramsList = new ArrayList<Object>(); //判断是否添加查询条件 if(StringUtils.isNotBlank(elecText.getTextName())){ condition += " and o.textName like ?"; paramsList.add("%"+elecText.getTextName()+"%"); } if(StringUtils.isNotBlank(elecText.getTextRemark())){ condition += " and o.textRemark like ?"; paramsList.add("%"+elecText.getTextRemark()+"%"); } Object [] params = paramsList.toArray(); //排序语句(hql语句和sql语句的排序是有顺序的 Map<String, String> orderby = new LinkedHashMap<String, String>(); orderby.put("o.textDate", "asc"); orderby.put("o.textName", "desc"); //查询 List<ElecText> list = elecTextDao.findCollectionByConditionNoPage(condition,params,orderby); return list; }
第五步:
/**模拟Action,调用Service,指定查询条件查询对应的结果,返回List*/ @Test public void findCollectionByConditionNoPage(){ ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); IElecTextService elecTextService = (IElecTextService) ac.getBean(IElecTextService.SERVICE_NAME); ElecText elecText = new ElecText(); // elecText.setTextName("张"); // elecText.setTextRemark("张"); List<ElecText> list = elecTextService.findCollectionByConditionNoPage(elecText); if(list!=null && list.size()>0){ for(ElecText elecText2:list){ System.out.println(elecText2.getTextName()+" "+elecText2.getTextDate()+" "+elecText2.getTextRemark()); } } }
真正的action:
package com.itheima.elec.web.action; import java.util.List; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.itheima.elec.domain.ElecSystemDDL; import com.itheima.elec.service.IElecSystemDDLService; @SuppressWarnings("serial") @Controller("elecSystemDDLAction") @Scope(value="prototype") public class ElecSystemDDLAction extends BaseAction<ElecSystemDDL>{ ElecSystemDDL elecSystemDDL = this.getModel(); @Resource(name=IElecSystemDDLService.SERVICE_NAME) private IElecSystemDDLService elecSystemDDLService; public String home(){ List<ElecSystemDDL> list = elecSystemDDLService.findKeywordWithDistinct(); request.setAttribute("list", list); return "home"; } public String edit(){ //获取数据类型 String keyword = elecSystemDDL.getKeyword(); //1:使用数据类型作为查询条件,查询数据字典表,返回List<ElecSystemDDL> List<ElecSystemDDL> list = elecSystemDDLService.findSystemDDLListByKeyword(keyword); request.setAttribute("systemList", list); return "edit"; } }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Download the latest version of 12306 ticket booking app. It is a travel ticket purchasing software that everyone is very satisfied with. It is very convenient to go wherever you want. There are many ticket sources provided in the software. You only need to pass real-name authentication to purchase tickets online. All users You can easily buy travel tickets and air tickets and enjoy different discounts. You can also start booking reservations in advance to grab tickets. You can book hotels or special car transfers. With it, you can go where you want to go and buy tickets with one click. Traveling is simpler and more convenient, making everyone's travel experience more comfortable. Now the editor details it online Provides 12306 users with a way to view historical ticket purchase records. 1. Open Railway 12306, click My in the lower right corner, and click My Order 2. Click Paid on the order page. 3. On the paid page

How to check my academic qualifications on Xuexin.com? You can check your academic qualifications on Xuexin.com, but many users don’t know how to check their academic qualifications on Xuexin.com. Next, the editor brings you a graphic tutorial on how to check your academic qualifications on Xuexin.com. Interested users come and take a look! Xuexin.com usage tutorial: How to check your academic qualifications on Xuexin.com 1. Xuexin.com entrance: https://www.chsi.com.cn/ 2. Website query: Step 1: Click on the Xuexin.com address above to enter the homepage Click [Education Query]; Step 2: On the latest webpage, click [Query] as shown by the arrow in the figure below; Step 3: Then click [Login Academic Credit File] on the new page; Step 4: On the login page Enter the information and click [Login];

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

MySQL and PL/SQL are two different database management systems, representing the characteristics of relational databases and procedural languages respectively. This article will compare the similarities and differences between MySQL and PL/SQL, with specific code examples to illustrate. MySQL is a popular relational database management system that uses Structured Query Language (SQL) to manage and operate databases. PL/SQL is a procedural language unique to Oracle database and is used to write database objects such as stored procedures, triggers and functions. same

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application
