一、使用count()聚合函數
當需要查詢數據是否存在時,一般會使用count函數,統計其個數,用法如下:
select count(1) from t_sys_user where username = "zhangsan"
在java中判斷數量是否大於0即可:
int num = userDao.countUser(params); if ( num > 0 ) { //存在時... } else { //不存在時... }
二、使用limit 1
select 1 from t_sys_user where username = 'zhangsan' limit 1
如果存在,則返回1,如果不存在,則返回null,在java中判斷是否為空即可。
這種方式讓數據庫查詢時遇到一條就返回,無需再繼續查找還有多少條,提高了查詢的效率。
mapper.xml
<select id="checkExist" resultType="Integer"> select 1 from t_sys_user where username = #{name} limit 1 </select>
dao接口
public interface UserDao extends Mapper<User> { Integer checkExist(@Param("name") String name); }
測試類
@RunWith(SpringRunner.class) @SpringBootTest(classes = MySpringBootApplication.class) public class MapperTest { @Resource private UserDao userDao; @Test public void test() { String name = "zhangsan1"; Integer exist = userDao.checkExist(name); if (null != exist) { System.out.println("存在"); } else { System.out.println("不存在"); } } }