mybatis学习(36):动态sql-set

简介: mybatis学习(36):动态sql-set

image.png

image.png

image.pngimage.png

com.geyao.mybatis.mapper

BlogMapper类

package com.geyao.mybatis.mapper;

 

import java.util.List;

import java.util.Map;

 

import org.apache.ibatis.annotations.Param;

 

import com.geyao.mybatis.pojo.Blog;

 

public interface BlogMapper {

   Blog selectBlog(Integer id);

 

   Blog selectBlog2(Integer id);

 

   List<Blog> selectBlogByTitle(String title);

 

   List<Blog> selectBlogByTitle2(String title);

 

   List<Blog> selectBlogBySort(String column);

 

   List<Blog> selectBlogByPage(int offset,int pagesize);

 

   List<Blog> selectBlogByPage1(@Param(value="offset")int offset,@Param(value="pagesize")int pagesize);

 

   List<Blog> selectBlogByPage2(Map<String, Object>map);

 

   int insertBlog(Blog blog);

 

   int insertBlogMysql(Blog blog);

 

   int updateBlog(Blog blog);

 

   int deleteBlogById(Integer id);

 

   List<Blog> selectActiveBlogByTitle(String title);

 

   List<Blog> selectActiveBlogByTitleOrStyle(Blog blog);

 

   List<Blog> selectBlogByCondition(Blog blog);

 

}

BlogMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的

例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)

-->

<mapper namespace="com.geyao.mybatis.mapper.BlogMapper">

   <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复

   使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型

   resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回

   User类就是users表所对应的实体类

   -->

   <!--  

       根据id查询得到一个user对象

    -->

    <resultMap type="Blog" id="blogResultMap">

    <id column="id" property="id" jdbcType="INTEGER"></id>

        <result column="authod_id" property="authodId" jdbcType="INTEGER"/>

    </resultMap>

    <!-- crud -->

   <select id="selectBlog" parameterType="int"   resultType="Blog">

       select  

       id,

       title,

       authod_id as authodId,

       state,

       featured,

       style

        from Blog where id=#{id}

   </select>  

 

   <select id="selectBlog2" parameterType="int"  resultMap="blogResultMap">

         select *

        from Blog where id=#{id}

   </select>

 

   <select id="selectBlogByTitle" parameterType="String" resultMap="blogResultMap">

       select * from Blog where title like #{title}

   </select>

 

   <select id="selectBlogByTitle2" parameterType="String" resultMap="blogResultMap">

       select * from Blog where title like '${value}'

   </select>

 

    <select id="selectBlogBySort" parameterType="String" resultMap="blogResultMap">

       select * from Blog order by ${value}

   </select>

 

     <select id="selectBlogByPage"  resultMap="blogResultMap">

       select * from Blog limit #{0},#{1}

   </select>

 

    <select id="selectBlogByPage1"  resultMap="blogResultMap">

       select * from Blog limit #{offset},#{pagesize}

   </select>

    <select id="selectBlogByPage2"  resultMap="blogResultMap">

       select * from Blog limit #{offset},#{pagesize}

   </select>

 

    <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="id">

       INSERT INTO Blog(

 

       title,

       authod_id,

       state,

       featured,

       style

       )

       VALUES(

 

       #{title},

       #{authodId},

       #{state},

       #{featured},

       #{style}

       )

   </insert>

    <insert id="insertBlogOracle" parameterType="Blog" >

    <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">

        select seq.nextval as id from dual

    </selectKey>

       INSERT INTO Blog(

 

       title,

       authod_id,

       state,

       featured,

       style

       )

       VALUES(

 

       #{title},

       #{authodId},

       #{state},

       #{featured},

       #{style}

       )

   </insert>

 

 

    <insert id="insertBlogMysql" parameterType="Blog" >

    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">

        SELECT LAST_INSERT_ID()

    </selectKey>

       INSERT INTO Blog(

 

       title,

       authod_id,

       state,

       featured,

       style

       )

       VALUES(

 

       #{title},

       #{authodId},

       #{state},

       #{featured},

       #{style}

       )

   </insert>

   <update id="updateBlog" parameterType="Blog" >

   UPDATE  

   Blog

   SET

   title = #{title},

  authod_id = #{authodId},

   state = #{state},

   featured = #{featured},

style= #{ style}

   WHERE id = #{id}

   </update>

   <delete id="deleteBlogById" parameterType="int">

       delete from blog where id =#{id}

   </delete>

   <!-- 动态sql -->

   <select id="selectActiveBlogByTitle" parameterType="String" resultMap="blogResultMap">

       SELECT * FROM blog

       where state ='ACTIVE'

       <if test="value!=null and value !=''">

       AND title LIKE '%o%'

       </if>

   </select>

   <select id="selectActiveBlogByTitleOrStyle" parameterType="Blog" resultMap="blogResultMap">

   SELECT * FROM blog

       where state ='ACTIVE'

       <choose>

       <when test="title !=null and title !=''">

           and lower(title) like lower(#{title})

       </when>

       <when test="style !=null and style!=''">

 

       </when>

       <otherwise>

       and featured=true;

       </otherwise>

       </choose>

   </select>

   <select id="selectBlogByCondition" parameterType="Blog" resultMap="blogResultMap">

   select * from blog

   <where>

   <if test="state !=null and state !=''">

   state=#{state}

   </if>

   <if test="title !=null and title !=''">

   and lower(title) like lower(#{title})

   </if>

   <if test=" featured !=null">

  and featured = #{featured}

   </if>

   </where>

   </select>

</mapper>

com.geyao.mybatis.pojo

Blog类

package com.geyao.mybatis.pojo;

 

public class Blog {

   private Integer id;

   private String title;

   private int authodId;

   private String state;

   private Boolean featured;

   private String style;

 

   public Blog() {

       super();

     

       this.title="未命名";

       this.authodId=4;

       this.state="NOT";

       this.featured=false;

       this.style="red";    

   }

   public Integer getId() {

       return id;

   }

   public void setId(Integer id) {

       this.id = id;

   }

   public String getTitle() {

       return title;

   }

   public void setTitle(String title) {

       this.title = title;

   }

 

   public int getAuthodId() {

       return authodId;

   }

   public void setAuthodId(int authodId) {

       this.authodId = authodId;

   }

   public String getState() {

       return state;

   }

   public void setState(String state) {

       this.state = state;

   }

   public Boolean getFeatured() {

       return featured;

   }

   public void setFeatured(Boolean featured) {

       this.featured = featured;

   }

   public String getStyle() {

       return style;

   }

   public void setStyle(String style) {

       this.style = style;

   }

   @Override

   public String toString() {

       return "Blog [id=" + id + ", title=" + title + ", authodId=" + authodId + ", state=" + state + ", featured="

               + featured + ", style=" + style + "]\n";

   }

 

}

com.geyao.mybatis.util

MybatisUtil类

package com.geyao.mybatis.util;

 

import java.io.InputStream;

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 SqlSessionFactory sqlSessionFactory =null;

   static {

       try {

           InputStream in = Resources.getResourceAsStream("mybatis-config.xml");

           sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

   }

   private MyBatisUtil() {}

 

   public static SqlSession getSqlSession() {

       return sqlSessionFactory.openSession();

   }

}

log4j.properties

### \u914D\u7F6E\u6839 ###

log4j.rootLogger = debug,console ,fileAppender,dailyRollingFile,ROLLING_FILE,MAIL,DATABASE

 

### \u8BBE\u7F6E\u8F93\u51FAsql\u7684\u7EA7\u522B\uFF0C\u5176\u4E2Dlogger\u540E\u9762\u7684\u5185\u5BB9\u5168\u90E8\u4E3Ajar\u5305\u4E2D\u6240\u5305\u542B\u7684\u5305\u540D ###

log4j.logger.org.apache=dubug

log4j.logger.java.sql.Connection=dubug

log4j.logger.java.sql.Statement=dubug

log4j.logger.java.sql.PreparedStatement=dubug

log4j.logger.java.sql.ResultSet=dubug

 

### \u914D\u7F6E\u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###

log4j.appender.console = org.apache.log4j.ConsoleAppender

log4j.appender.console.Target = System.out

log4j.appender.console.layout = org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

mybatis-config.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>

 

<typeAliases>

   <typeAlias type="com.geyao.mybatis.pojo.Blog" alias="Blog"/>

</typeAliases>

   <environments default="development">

       <environment id="development">

           <transactionManager type="JDBC" />

           <!-- 配置数据库连接信息 -->

           <dataSource type="POOLED">

               <property name="driver" value="com.mysql.cj.jdbc.Driver" />

               <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" />

               <property name="username" value="root" />

               <property name="password" value="123" />

           </dataSource>

       </environment>

   </environments>

     <mappers>

       <!-- 注册userMapper.xml文件,  

        userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->

        <mapper resource="com/geyao/mybatis/mapper/BlogMapper.xml"/>

    </mappers>

</configuration>

单元测试

com.geyao.mybatis.util

testSelectBlog类

package com.geyao.mybatis.mapper;

 

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.apache.ibatis.session.SqlSession;

import org.junit.Test;

 

import com.geyao.mybatis.pojo.Blog;

import com.geyao.mybatis.util.MyBatisUtil;

 

public class testSelectBlog {

   @Test

   public void testSelectBlogNoInterface() {

       SqlSession session =MyBatisUtil.getSqlSession();

       Blog blog =(Blog)session.selectOne("com.geyao.mybatis.mapper.BlogMapper.selectBlog", 101);

     

       session.close();

       System.out.println(blog);

   }

@Test

public void testSelectBlog() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   Blog blog = blogMapper.selectBlog(1);

   System.out.println(blog);

}

 

@Test

public void testSelectBlog2() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   Blog blog = blogMapper.selectBlog2(1);

   System.out.println(blog);

}

@Test

public void testselectBlogByTitle() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByTitle("%g%");

   System.out.println(blogList);

}

 

@Test

public void testselectBlogByTitle2() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByTitle2("%g%");

   System.out.println(blogList);

}

@Test

public void testselectBlogBySort() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogBySort("title");

   System.out.println(blogList);

}

@Test

public void testselectBlogByPage() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByPage(2,2);

   System.out.println(blogList);

}

@Test

public void testselectBlogByPage1() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByPage1(2,2);

   System.out.println(blogList);

}

@Test

public void testselectBlogByPage2() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Map<String, Object> map =new HashMap<String, Object>();

   map.put("offset", 2);

   map.put("pagesize", 2);

   List<Blog> blogList = blogMapper.selectBlogByPage2(map);

 

   System.out.println(blogList);

}

 

@Test

public void testInsertBlog() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog=new Blog();

   int count= blogMapper.insertBlog(blog);

   session.commit();

   session.close();

   System.out.println(blog);

   System.out.println("插入的"+count+"记录");

}

 

@Test

public void testinsertBlogMysql() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog=new Blog();

   int count= blogMapper.insertBlogMysql(blog);

   session.commit();

   session.close();

   System.out.println(blog);

   System.out.println("插入的"+count+"记录");

}

 

@Test

public void testupdateBlog() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog=new Blog();

   blog.setId(1);

   blog.setTitle("geyao");

   blog.setStyle("balck");

   blog.setState("active");

   blog.setFeatured(false);

   blog.setAuthodId(2);

   int count= blogMapper.updateBlog(blog);

   session.commit();

   session.close();

   System.out.println(blog);

   System.out.println("修改"+count+"记录");

}

}

jar包

链接:https://pan.baidu.com/s/1g6NgzfLc5uK9S4VL-03lHg

提取码:4r2m

运行结果

image.png

image.png

image.png

com.geyao.mybatis.mapper

BlogMapper类

package com.geyao.mybatis.mapper;

 

import java.util.List;

import java.util.Map;

 

import org.apache.ibatis.annotations.Param;

 

import com.geyao.mybatis.pojo.Blog;

 

public interface BlogMapper {

   Blog selectBlog(Integer id);

 

   Blog selectBlog2(Integer id);

 

   List<Blog> selectBlogByTitle(String title);

 

   List<Blog> selectBlogByTitle2(String title);

 

   List<Blog> selectBlogBySort(String column);

 

   List<Blog> selectBlogByPage(int offset,int pagesize);

 

   List<Blog> selectBlogByPage1(@Param(value="offset")int offset,@Param(value="pagesize")int pagesize);

 

   List<Blog> selectBlogByPage2(Map<String, Object>map);

 

   int insertBlog(Blog blog);

 

   int insertBlogMysql(Blog blog);

 

   int updateBlog(Blog blog);

}

BlogMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的

例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)

-->

<mapper namespace="com.geyao.mybatis.mapper.BlogMapper">

   <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复

   使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型

   resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回

   User类就是users表所对应的实体类

   -->

   <!--  

       根据id查询得到一个user对象

    -->

    <resultMap type="Blog" id="blogResultMap">

    <id column="id" property="id" jdbcType="INTEGER"></id>

        <result column="authod_id" property="authodId" jdbcType="INTEGER"/>

    </resultMap>

   

   <select id="selectBlog" parameterType="int"   resultType="Blog">

       select  

       id,

       title,

       authod_id as authodId,

       state,

       featured,

       style

        from Blog where id=#{id}

   </select>  

 

   <select id="selectBlog2" parameterType="int"  resultMap="blogResultMap">

         select *

        from Blog where id=#{id}

   </select>

 

   <select id="selectBlogByTitle" parameterType="String" resultMap="blogResultMap">

       select * from Blog where title like #{title}

   </select>

 

   <select id="selectBlogByTitle2" parameterType="String" resultMap="blogResultMap">

       select * from Blog where title like '${value}'

   </select>

 

    <select id="selectBlogBySort" parameterType="String" resultMap="blogResultMap">

       select * from Blog order by ${value}

   </select>

 

     <select id="selectBlogByPage"  resultMap="blogResultMap">

       select * from Blog limit #{0},#{1}

   </select>

 

    <select id="selectBlogByPage1"  resultMap="blogResultMap">

       select * from Blog limit #{offset},#{pagesize}

   </select>

    <select id="selectBlogByPage2"  resultMap="blogResultMap">

       select * from Blog limit #{offset},#{pagesize}

   </select>

 

    <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="id">

       INSERT INTO Blog(

 

       title,

       authod_id,

       state,

       featured,

       style

       )

       VALUES(

 

       #{title},

       #{authodId},

       #{state},

       #{featured},

       #{style}

       )

   </insert>

    <insert id="insertBlogOracle" parameterType="Blog" >

    <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">

        select seq.nextval as id from dual

    </selectKey>

       INSERT INTO Blog(

 

       title,

       authod_id,

       state,

       featured,

       style

       )

       VALUES(

 

       #{title},

       #{authodId},

       #{state},

       #{featured},

       #{style}

       )

   </insert>

 

 

    <insert id="insertBlogMysql" parameterType="Blog" >

    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">

        SELECT LAST_INSERT_ID()

    </selectKey>

       INSERT INTO Blog(

 

       title,

       authod_id,

       state,

       featured,

       style

       )

       VALUES(

 

       #{title},

       #{authodId},

       #{state},

       #{featured},

       #{style}

       )

   </insert>

   <update id="updateBlog" parameterType="Blog" >

   UPDATE  

   Blog

   SET

   title = #{title},

  authod_id = #{authodId},

   state = #{state},

   featured = #{featured},

style= #{ style}

   WHERE id = #{id}

   </update>

</mapper>

com.geyao.mybatis.pojo

Blog类

package com.geyao.mybatis.pojo;

 

public class Blog {

   private Integer id;

   private String title;

   private int authodId;

   private String state;

   private Boolean featured;

   private String style;

 

   public Blog() {

       super();

     

       this.title="未命名";

       this.authodId=4;

       this.state="NOT";

       this.featured=false;

       this.style="red";    

   }

   public Integer getId() {

       return id;

   }

   public void setId(Integer id) {

       this.id = id;

   }

   public String getTitle() {

       return title;

   }

   public void setTitle(String title) {

       this.title = title;

   }

 

   public int getAuthodId() {

       return authodId;

   }

   public void setAuthodId(int authodId) {

       this.authodId = authodId;

   }

   public String getState() {

       return state;

   }

   public void setState(String state) {

       this.state = state;

   }

   public Boolean getFeatured() {

       return featured;

   }

   public void setFeatured(Boolean featured) {

       this.featured = featured;

   }

   public String getStyle() {

       return style;

   }

   public void setStyle(String style) {

       this.style = style;

   }

   @Override

   public String toString() {

       return "Blog [id=" + id + ", title=" + title + ", authodId=" + authodId + ", state=" + state + ", featured="

               + featured + ", style=" + style + "]\n";

   }

 

}

com.geyao.mybatis.util

MybatisUtil类

package com.geyao.mybatis.util;

 

import java.io.InputStream;

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 SqlSessionFactory sqlSessionFactory =null;

   static {

       try {

           InputStream in = Resources.getResourceAsStream("mybatis-config.xml");

           sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

   }

   private MyBatisUtil() {}

 

   public static SqlSession getSqlSession() {

       return sqlSessionFactory.openSession();

   }

}

log4j.properties

### \u914D\u7F6E\u6839 ###

log4j.rootLogger = debug,console ,fileAppender,dailyRollingFile,ROLLING_FILE,MAIL,DATABASE

 

### \u8BBE\u7F6E\u8F93\u51FAsql\u7684\u7EA7\u522B\uFF0C\u5176\u4E2Dlogger\u540E\u9762\u7684\u5185\u5BB9\u5168\u90E8\u4E3Ajar\u5305\u4E2D\u6240\u5305\u542B\u7684\u5305\u540D ###

log4j.logger.org.apache=dubug

log4j.logger.java.sql.Connection=dubug

log4j.logger.java.sql.Statement=dubug

log4j.logger.java.sql.PreparedStatement=dubug

log4j.logger.java.sql.ResultSet=dubug

 

### \u914D\u7F6E\u8F93\u51FA\u5230\u63A7\u5236\u53F0 ###

log4j.appender.console = org.apache.log4j.ConsoleAppender

log4j.appender.console.Target = System.out

log4j.appender.console.layout = org.apache.log4j.PatternLayout

log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

mybatis-config.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>

 

<typeAliases>

   <typeAlias type="com.geyao.mybatis.pojo.Blog" alias="Blog"/>

</typeAliases>

   <environments default="development">

       <environment id="development">

           <transactionManager type="JDBC" />

           <!-- 配置数据库连接信息 -->

           <dataSource type="POOLED">

               <property name="driver" value="com.mysql.cj.jdbc.Driver" />

               <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" />

               <property name="username" value="root" />

               <property name="password" value="123" />

           </dataSource>

       </environment>

   </environments>

     <mappers>

       <!-- 注册userMapper.xml文件,  

        userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->

        <mapper resource="com/geyao/mybatis/mapper/BlogMapper.xml"/>

    </mappers>

</configuration>

单元测试

com.geyao.mybatis.util

testSelectBlog类

package com.geyao.mybatis.mapper;

 

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.apache.ibatis.session.SqlSession;

import org.junit.Test;

 

import com.geyao.mybatis.pojo.Blog;

import com.geyao.mybatis.util.MyBatisUtil;

 

public class testSelectBlog {

   @Test

   public void testSelectBlogNoInterface() {

       SqlSession session =MyBatisUtil.getSqlSession();

       Blog blog =(Blog)session.selectOne("com.geyao.mybatis.mapper.BlogMapper.selectBlog", 101);

     

       session.close();

       System.out.println(blog);

   }

@Test

public void testSelectBlog() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   Blog blog = blogMapper.selectBlog(1);

   System.out.println(blog);

}

 

@Test

public void testSelectBlog2() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   Blog blog = blogMapper.selectBlog2(1);

   System.out.println(blog);

}

@Test

public void testselectBlogByTitle() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByTitle("%g%");

   System.out.println(blogList);

}

 

@Test

public void testselectBlogByTitle2() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByTitle2("%g%");

   System.out.println(blogList);

}

@Test

public void testselectBlogBySort() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogBySort("title");

   System.out.println(blogList);

}

@Test

public void testselectBlogByPage() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByPage(2,2);

   System.out.println(blogList);

}

@Test

public void testselectBlogByPage1() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   List<Blog> blogList = blogMapper.selectBlogByPage1(2,2);

   System.out.println(blogList);

}

@Test

public void testselectBlogByPage2() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Map<String, Object> map =new HashMap<String, Object>();

   map.put("offset", 2);

   map.put("pagesize", 2);

   List<Blog> blogList = blogMapper.selectBlogByPage2(map);

 

   System.out.println(blogList);

}

 

@Test

public void testInsertBlog() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog=new Blog();

   int count= blogMapper.insertBlog(blog);

   session.commit();

   session.close();

   System.out.println(blog);

   System.out.println("插入的"+count+"记录");

}

 

@Test

public void testinsertBlogMysql() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog=new Blog();

   int count= blogMapper.insertBlogMysql(blog);

   session.commit();

   session.close();

   System.out.println(blog);

   System.out.println("插入的"+count+"记录");

}

 

@Test

public void testupdateBlog() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog = blogMapper.selectBlog(1);

   //Blog blog=new Blog();

   blog.setId(1);

   blog.setTitle("geyao");

   blog.setAuthodId(3);

   //blog.setStyle("balck");

   //blog.setState("active");

   //blog.setFeatured(false);

   //blog.setAuthodId(2);

   int count= blogMapper.updateBlog(blog);

   session.commit();

   session.close();

   System.out.println(blog);

   System.out.println("修改"+count+"记录");

}

@Test

public void testdeleteBlogById() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

 

   int count= blogMapper.deleteBlogById(3);

   session.commit();

   session.close();

 

   System.out.println("删除的"+count+"记录");

}

@Test

public void testselectActiveBlogByTitle() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   List<Blog> blogList=blogMapper.selectActiveBlogByTitle("o");

 

   session.close();

 

   System.out.println(blogList);

}

@Test

public void testselectActiveBlogByTitleOrStyle() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog = new Blog();

   blog.setTitle("%o%");

   blog.setStyle("black");

   List<Blog> blogList=blogMapper.selectActiveBlogByTitleOrStyle(blog);

 

   session.close();

 

   System.out.println(blogList);

}

@Test

public void testselectBlogByCondition() {

   SqlSession session =MyBatisUtil.getSqlSession();

   BlogMapper blogMapper =session.getMapper(BlogMapper.class);

   Blog blog = new Blog();

   blog.setTitle("%o%");

   List<Blog> blogList=blogMapper.selectBlogByCondition(blog);

   session.close();

   System.out.println(blogList);

}

}

jar包

链接:https://pan.baidu.com/s/1g6NgzfLc5uK9S4VL-03lHg

提取码:4r2m

运行结果

image.pngimage.png

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
10月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
511 2
|
12月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
626 18
|
12月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
522 0
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
1360 5
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1981 0
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
SQL XML Java
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
544 0
|
SQL XML Java
九、MyBatis动态SQL
九、MyBatis动态SQL
318 2