Mybatis_动态sql_1

网友投稿 240 2022-11-18

Mybatis_动态sql_1

文章目录

​​动态SQl​​

​​1. if​​​​2.choose​​​​3.foreach​​

动态SQl

1. if

select * from tbl_employ where id=#{id} and last_name like #{lastName} and email=#{email} and gender=#{gender}

这里的意思是如果id存在的话就按照id查找,如果不存在的话就看last_name是否存在,存在的话按照last_name查找,不存在的话看email是否存在不存在的话按照gender查找

test.java

public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); }

@Test public void test6() throws Exception{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployMapperDynamicSQL mapper = sqlSession.getMapper(EmployMapperDynamicSQL.class); Employee employee = new Employee(3,"%Z%","baidu.com",null); List employByConditionIf = mapper.getEmployByConditionIf(employee); for(Employee emp : employByConditionIf){ System.out.println(emp); } sqlSession.commit(); }finally { sqlSession.close(); } }

2.choose

select * from tbl_employ id = #{id} last_name like #{last_name} email = #{emial} gender = 0

意思为多重if的意思,跟上面的一个意思

test.java

@Test public void test1()throws Exception{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); EmployMapperDynamicSQL mapper = openSession.getMapper(EmployMapperDynamicSQL.class); List employ = mapper.getEmployByConditionChoose(new Employee(null, "%Z%", null, null)); for (Employee employee : employ) { System.out.println(employee); } openSession.close(); }

3.foreach

下面的为字符串拼接

这里的collection对应的是前面的@Param注解的值,item对应的下面的#{item},separator为分隔符,open和close为()开启和关闭。

test.java

@Test public void test2()throws Exception{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); EmployMapperDynamicSQL mapper = openSession.getMapper(EmployMapperDynamicSQL.class); List list = mapper.getEmployByConditionForeach(Arrays.asList(1, 2, 3)); for (Employee employee : list) { System.out.println(employee); } openSession.close(); }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java向数据库插入数据显示乱码的几种问题解决
下一篇:USB端口辐射EMI整改方案
相关文章

 发表评论

暂时没有评论,来抢沙发吧~