mybatis example 使用AND 和OR 联合查询

本文介绍如何使用MyBatis进行AND和OR条件的联合查询。通过创建多个查询标准并使用or方法将它们组合起来,可以实现复杂的查询需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mybatis example 使用AND 和OR 联合查询

ViewPsmsgconsultExample example=new ViewPsmsgconsultExample();  
ViewPsmsgconsultExample.Criteria criteria=example.createCriteria();  
criteria.andToidEqualTo(mctid);  
criteria.andStatusEqualTo("0");  
          
ViewPsmsgconsultExample.Criteria criteria2=example.createCriteria();  
criteria2.andToidEqualTo(mctid);  
criteria2.andLaststatusEqualTo("0");  
example.or(criteria2);  
psmsgconsultDao.countByExample(example);  

生成代码如下:

select count(*) from VIEW_PSMSGCONSULT WHERE ( TOID = ? and STATUS = ? ) or( TOID = ? and LASTSTATUS = ? )   

 

MyBatis is a popular Java-based persistence framework that provides support for object-relational mapping (ORM) and simplifies database access. It allows you to perform various types of queries, including association or join queries, to retrieve related data from multiple tables. In MyBatis, you can achieve association or join queries using the "resultMap" feature. Here's an example of how you can perform a simple association query: 1. Define the result map: ```xml <resultMap id="PersonResultMap" type="Person"> <id property="id" column="person_id" /> <result property="name" column="person_name" /> <association property="address" javaType="Address"> <id property="id" column="address_id" /> <result property="street" column="street" /> <result property="city" column="city" /> </association> </resultMap> ``` 2. Write the SQL query with JOIN: ```xml <select id="getPersonWithAddress" resultMap="PersonResultMap"> SELECT p.id AS person_id, p.name AS person_name, a.id AS address_id, a.street, a.city FROM person p JOIN address a ON p.address_id = a.id WHERE p.id = #{personId} </select> ``` 3. Use the defined resultMap in your mapper interface: ```java @Select("getPersonWithAddress") @ResultMap("PersonResultMap") Person getPersonWithAddress(int personId); ``` In this example, the query retrieves a person and their associated address by performing a join between the "person" and "address" tables. The result is mapped to the `Person` object using the defined resultMap. You can customize the association mapping based on your specific database schema and entity classes. MyBatis provides flexibility in handling various types of associations, including one-to-one, one-to-many, and many-to-many relationships.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值