mybatis动态SQL语句
1 动态增加,对象有哪个字段/属性就添加哪个字段。关键标签<sql><trim><include><if>
2 动态更新,对象有哪个字段/属性就更新哪个字段。关键标签<set><if>
3 动态查找,对象有哪个字段/属性就根据哪个字段进行查找。关键标签<where><if>
4 集合属性,关键词 in, 那个字段在某一个集合中,关键标签<foreach>。注意: 如果参数类型是List,则必须在collecion中指定为list, 如果是数据组,则必须在collection属性中指定为 array.
例子:
开发流程:
1)引jar文件,参考之前的mybatis开发流程,增删改查
2)实体类Student,
package com.huitong.entity; public class Student { private Integer sid; private String sname; private String sgender; private Short sage; private Double ssalary; public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSgender() { return sgender; } public void setSgender(String sgender) { this.sgender = sgender; } public short getSage() { return sage; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public Double getSsalary() { return ssalary; } public void setSsalary(Double ssalary) { this.ssalary = ssalary; } public void setSage(Short sage) { this.sage = sage; } @Override public String toString() { return sid + ":"+sname + ":" + sgender + ":" + sage + ":" + ssalary; } }
3)映射文件StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.huitong.entity.Student"> <resultMap type="com.huitong.entity.Student" id="studentMap"> <id column="id" property="sid" /> <result column="name" property="sname"/> <result column="gender" property="sgender"/> <result column="age" property="sage"/> <result column="salary" property="ssalary"/> </resultMap> <sql id="key2"> <trim suffixOverrides=","> <if test="sname != null">name,</if> <if test="sgender != null">gender,</if> <if test="sage != null">age,</if> <if test="ssalary != null">salary,</if> </trim> </sql> <sql id="value2"> <trim suffixOverrides=","> <if test="sname != null">#{sname},</if> <if test="sgender != null">#{sgender},</if> <if test="sage != null">#{sage},</if> <if test="ssalary != null">#{ssalary},</if> </trim> </sql> <sql id="key"> <trim suffixOverrides=","> <if test="pname != null">name,</if> <if test="pgender != null">gender,</if> <if test="page != null">age,</if> <if test="psalary != null">salary,</if> </trim> </sql> <sql id="value"> <trim suffixOverrides=","> <if test="pname != null">#{pname},</if> <if test="pgender != null">#{pgender},</if> <if test="page != null">#{page},</if> <if test="psalary != null">#{psalary},</if> </trim> </sql> <insert id="dynamicInsert" parameterType="map"> INSERT INTO t_student(<include refid="key"></include>) VALUES(<include refid="value"></include>); </insert> <insert id="dynamicInsert2" parameterType="com.huitong.entity.Student"> INSERT INTO t_student(<include refid="key2"></include>) VALUES(<include refid="value2"></include>); </insert> <delete id="dynamicDelete" parameterType="list"> </delete> <select id="dynamicGetListByIds" parameterType="list" resultMap="studentMap"> SELECT id,NAME,gender,age,salary FROM t_student where id in <foreach collection="list" close=")" item="id" open="(" separator=","> #{id} </foreach> </select> <select id="dynamicGet" parameterType="map" resultMap="studentMap"> SELECT id,NAME,gender,age,salary FROM t_student <where> <if test="pid!=null">id=#{pid}</if> <if test="pname!=null">and name=#{pname}</if> <if test="pgender!=null">and gender=#{pgender}</if> </where> </select> <select id="dynamicGetm2" parameterType="com.huitong.entity.Student" resultMap="studentMap"> SELECT id,NAME,gender,age,salary FROM t_student <where> <if test="sid!=null">id=#{sid}</if> <if test="sname!=null">and name=#{sname}</if> <if test="sgender!=null">and gender=#{sgender}</if> <if test="sage!=null">and age=#{sage}</if> <if test="ssalary!=null">and salary=#{ssalary}</if> </where> </select> <update id="dynamicUpdate" parameterType="com.huitong.entity.Student"> UPDATE t_student <set> <if test="sname!=null">name=#{sname},</if> <if test="sgender!=null">gender=#{sgender},</if> <if test="sage!=null">age=#{sage},</if> <if test="ssalary!=null">salary=#{ssalary}</if> </set> WHERE id=#{sid} </update> </mapper>
4)mybatis配置文件mabits.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="mysql"> <environment id="mysql"> <transactionManager type="jdbc"> </transactionManager> <dataSource type="pooled"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///day14?useSSL=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/huitong/entity/StudentMapper.xml"/> </mappers> </configuration>
5)工具类,获取sqlSession,关闭sqlSession
package com.huitong.util; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MybatisUtil { private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); private static SqlSessionFactory sqlSessionFactory ; static { try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static SqlSession getSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession==null){ sqlSession = sqlSessionFactory.openSession(); threadLocal.set(sqlSession); } return sqlSession; } public static void closeSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession!=null){ sqlSession.close(); threadLocal.remove(); } } }
6)Dao类StudentDao
package com.huitong.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import com.huitong.entity.Student; import com.huitong.util.MybatisUtil; public class StudentDao { public void dynamicInsert(String name, String gender, Short age, Double salary) throws Exception{ SqlSession sqlSession = MybatisUtil.getSqlSession(); Map<String, Object> map = new HashMap<String, Object>(); map.put("pname", name); map.put("pgender", gender); map.put("page", age); map.put("psalary", salary); try { sqlSession.insert(Student.class.getName() + ".dynamicInsert", map); sqlSession.commit(); } catch(Exception e) { e.printStackTrace(); sqlSession.rollback(); } finally { MybatisUtil.closeSqlSession(); } } public void dynamicInsert2(Student stu) throws Exception{ SqlSession sqlSession = MybatisUtil.getSqlSession(); try { sqlSession.insert(Student.class.getName() + ".dynamicInsert2", stu); sqlSession.commit(); } catch(Exception e) { e.printStackTrace(); sqlSession.rollback(); throw new RuntimeException(e); } finally { MybatisUtil.closeSqlSession(); } } public void dynamicDelete(List<Integer> list) throws Exception{ SqlSession sqlSession; try { sqlSession = MybatisUtil.getSqlSession(); } catch(Exception e) { } finally { } } public List<Student> dynamicGetListByIds(List<Integer> ids) throws Exception{ SqlSession sqlSession; try { sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList(Student.class.getName() + ".dynamicGetListByIds", ids); } catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } finally { MybatisUtil.closeSqlSession(); } } public List<Student> dynamicGet(Integer id, String name, String gender) throws Exception{ Map<String, Object> map = new HashMap<String, Object>(); map.put("pid", id); map.put("pname", name); map.put("pgender", gender); SqlSession sqlSession; try { sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList(Student.class.getName() + ".dynamicGet", map); } catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); }finally{ MybatisUtil.closeSqlSession(); } } public List<Student> dynamicGetm2(Student stu) throws Exception{ SqlSession sqlSession; try { sqlSession = MybatisUtil.getSqlSession(); return sqlSession.selectList(Student.class.getName() + ".dynamicGetm2", stu); } catch(Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { MybatisUtil.closeSqlSession(); } } public void dynamicUpdate(Student stu)throws Exception{ SqlSession sqlSession=null; try { sqlSession = MybatisUtil.getSqlSession(); sqlSession.update(Student.class.getName() + ".dynamicUpdate", stu); sqlSession.commit(); } catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw new RuntimeException(e); } finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) { StudentDao studentDao = new StudentDao(); Student student = new Student(); student.setSid(2); student.setSgender("男"); student.setSage((short)14); try { studentDao.dynamicUpdate(student); System.out.println("update success"); } catch (Exception e) { e.printStackTrace(); } } }
学习过程中,难免出错。如果您在阅读过程中遇到不太明白,或者有疑问。欢迎指正...联系邮箱crazyCodeLove@163.com
如果觉得有用,想赞助一下请移步赞助页面:赞助一下