天天看點

mybatis if test 多條件_MyBatis_Day04

一,mybatis映射檔案的學習。簡化開發步驟。

mybatis if test 多條件_MyBatis_Day04
  1. 配置資料庫 pom檔案資料庫的操作。
  2. 配置User檔案進行資料庫字段的關聯
package com.liuboss.demo;public class User {    private int id;    private String name;    @Override    public String toString() {        return "User{" +                "id=" + id +                ", name='" + name + '\'' +                '}';    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}
           
  1. 配置resources檔案下的資源。log4j檔案,sql操作檔案,sql配置檔案,resources下com.liuboss.demo檔案進行資料庫的操作。
<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.liuboss.mapper.UserMapper">         <select id="findByCount" resultType="user" parameterType="user">        select * from t_class where id=#{id} and name=#{name}    select>mapper>
           
jdbc.driver = com.mysql.cj.jdbc.Driverjdbc.url = jdbc:mysql://localhost:3306/text01?serverTimezone=UTCjdbc.username = rootjdbc.password = 123456
           
<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <properties resource="jdbc.properties">properties>        <typeAliases>        <typeAlias type="com.liuboss.demo.User" alias="user">typeAlias>    typeAliases>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="${jdbc.driver}"/>                <property name="url" value="${jdbc.url}"/>                <property name="username" value="${jdbc.username}"/>                <property name="password" value="${jdbc.password}"/>            dataSource>        environment>    environments>    <mappers>        <mapper resource="com\liuboss\demo\UserMapper.xml">mapper>    mappers>configuration>
           

注意:資料庫語句操作檔案中,配置的路徑名要是全路徑。

4.資料庫的mapper接口

package com.liuboss.mapper;import com.liuboss.demo.User;import java.util.List;public interface UserMapper {    public ListfindByCount(User user);}
           

5.資料庫的測試檔案。

package com.liuboss.test;import com.liuboss.demo.User;import com.liuboss.mapper.UserMapper;import com.sun.corba.se.spi.servicecontext.UEInfoServiceContext;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;public class MapperTest {    @Test    public void test1() throws IOException {        User con = new User();        con.setId(60);        con.setName("朱皇帝");        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        List<User> userList = mapper.findByCount(con);        System.out.println(userList);        System.out.println(con);    }}
           
mybatis if test 多條件_MyBatis_Day04

6.可以在sql操作配置檔案中進行資料的條件查詢

<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.liuboss.mapper.UserMapper">         <select id="findByCount" resultType="user" parameterType="user">        select * from t_class        <where>        <if test="id!=0">            and id=#{id}        if>        <if test="name!=null">            and name=#{name}        if>        where>    select>mapper>
           

二,動态sql的使用,重點if的使用,foreach的使用。

方法步驟與上面全部一樣,不同隻有sql查詢語句和測試檔案不同。重點内容

<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.liuboss.mapper.UserMapper">         <select id="findByCount" resultType="user" parameterType="user">        select * from t_class        <where>        <if test="id!=0">            and id=#{id}        if>        <if test="name!=null">            and name=#{name}        if>        where>    select>    <select id="findByIds" parameterType="list" resultType="user">        select * from t_class         <where>            <foreach collection="list" open="id in(" close=")" item="id"                     separator=",">                #{id}            foreach>        where>    select>mapper>
           
package com.liuboss.test;import com.liuboss.demo.User;import com.liuboss.mapper.UserMapper;import com.sun.corba.se.spi.servicecontext.UEInfoServiceContext;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;public class MapperTest {    @Test    public void test1() throws IOException {        User con = new User();//        con.setId(60);//        con.setName("朱皇帝");        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        List<Integer> ids = new ArrayList<Integer>();        ids.add(1);        ids.add(2);        List<User> userList = mapper.findByIds(ids);        System.out.println(userList);    }}
           

7.sql片段的抽取,

<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.liuboss.mapper.UserMapper">         <sql id="selectUser">         select * from user     sql>    <select id="findByCount" resultType="user" parameterType="user">        <include refid="selectUser">include>        <where>        <if test="id!=0">            and id=#{id}        if>        <if test="name!=null">            and name=#{name}        if>        where>    select>    <select id="findByIds" parameterType="list" resultType="user">        select * from t_class        <where>            <foreach collection="list" open="id in(" close=")" item="id"                     separator=",">                #{id}            foreach>        where>    select>mapper>
           
mybatis if test 多條件_MyBatis_Day04
mybatis if test 多條件_MyBatis_Day04
mybatis if test 多條件_MyBatis_Day04
mybatis if test 多條件_MyBatis_Day04
mybatis if test 多條件_MyBatis_Day04

三,Mybatis核心配置檔案---自定義屬性的類型設定 

   源碼檔案:Test06

   ---重點,當mybatis中沒有自己想要的;诶性标簽時,将要進行自定義标簽類型進行屬性的注入和設定。

---重點内容實作内容:自定義屬性的類型。

  1. 資料庫
  2. user表的配置進行屬性的配置。

    ---在資料庫中添加資料

package com.liuboss.demo;import java.util.Date;public class User {    private int id;    private String name;    private String password;    private Date birthday;    @Override    public String toString() {        return "User{" +                "id=" + id +                ", name='" + name + '\'' +                ", password='" + password + '\'' +                ", birthday=" + birthday +                '}';    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}
           

2.定義資料庫的操作檔案及相關的配置檔案。

UserMapper.xml資料庫額操作檔案,注意資料庫的全類名。在resources檔案下建立com/liuboss/demo檔案下建立Usermapper.xml
           
<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.liuboss.mapper.UserMapper">    <insert id="save" parameterType="user">        insert into t_class values(#{id},#{name},#{password},#{birthday})    insert>    <select id="findById" parameterType="int" resultType="user">        select * from t_class where id=#{id}    select>mapper>
           

3.資料庫的連接配接檔案。注意下面的配置。注冊類型處理器的使用方式 重點強調

<configuration>    <properties resource="jdbc.properties">properties>        <typeAliases>        <typeAlias type="com.liuboss.demo.User" alias="user">typeAlias>    typeAliases>        <typeHandlers>        <typeHandler handler="com.liuboss.handler.DateTypeHandler"/>    typeHandlers>
           
<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <properties resource="jdbc.properties">properties>        <typeAliases>        <typeAlias type="com.liuboss.demo.User" alias="user">typeAlias>    typeAliases>        <typeHandlers>        <typeHandler handler="com.liuboss.handler.DateTypeHandler"/>    typeHandlers>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="${jdbc.driver}"/>                <property name="url" value="${jdbc.url}"/>                <property name="username" value="${jdbc.username}"/>                <property name="password" value="${jdbc.password}"/>            dataSource>        environment>    environments>    <mappers>        <mapper resource="com\liuboss\demo\UserMapper.xml">mapper>    mappers>configuration>
           

4.引入lig4j。和jdbc.properties配置檔案

mybatis if test 多條件_MyBatis_Day04

5.定義handler檔案夾,DateTypeHandler.java檔案夾,将所有的資料檔案進行,其中繼承extends BaseTypeHandler<Date>方法方法,實作其中的方法,

package com.liuboss.handler;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import javax.annotation.Resources;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Date;public class DateTypeHandler extends BaseTypeHandler<Date> {    //将java類型轉換成資料庫需要的類型    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {        long time = parameter.getTime();        ps.setLong(i,time);    }    //将資料庫中類型轉換成java類型    public Date getNullableResult(ResultSet rs, String s) throws SQLException {        long aLong = rs.getLong(s);        Date date = new Date(aLong);        return date;    }    //将資料庫中類型轉換成java類型    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {        long aLong = rs.getLong(columnIndex);        Date date = new Date(aLong);        return date;    }    //将資料庫中類型轉換成java類型    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {        long aLong = cs.getLong(columnIndex);        Date date = new Date(aLong);        return date;    }}
           

7.定義測試檔案

import com.liuboss.demo.User;import com.liuboss.mapper.UserMapper;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.InputStream;import java.nio.Buffer;import java.util.Date;public class Test {    @org.junit.Test    public void test1() throws IOException {        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        /*建立user*/        User user = new User();        user.setId(10);        user.setName("劉慶東");        user.setBirthday(new Date());        user.setPassword("123456");        mapper.save(user);        sqlSession.commit();        sqlSession.close();    }    @org.junit.Test    public void test2() throws IOException {        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        User byId = mapper.findById(10);        System.out.println(byId.getBirthday());        sqlSession.commit();        sqlSession.close();    }}
           
mybatis if test 多條件_MyBatis_Day04
mybatis if test 多條件_MyBatis_Day04

三,進行查詢全部資料的配置改動的地方代碼。

package com.liuboss.mapper;import com.liuboss.demo.User;import com.sun.javafx.collections.VetoableListDecorator;import java.util.List;public interface UserMapper {     public void save(User user);     public User findById(int id);     //查詢全部實作功能     public ListfindAll();}
           
<?xml version="1.0" encoding="UTF-8" ?>/span>        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.liuboss.mapper.UserMapper">    <insert id="save" parameterType="user">        insert into t_class values(#{id},#{name},#{password},#{birthday})    insert>    <select id="findById" parameterType="int" resultType="user">        select * from t_class where id=#{id}    select>        <select id="findAll" resultType="user">        select * from t_class    select>mapper>
           
import com.liuboss.demo.User;import com.liuboss.mapper.UserMapper;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import sun.misc.FormattedFloatingDecimal;import java.io.IOException;import java.io.InputStream;import java.nio.Buffer;import java.util.Date;import java.util.List;public class Test {    @org.junit.Test    public void test1() throws IOException {        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        /*建立user*/        User user = new User();        user.setId(10);        user.setName("劉慶東");        user.setBirthday(new Date());        user.setPassword("123456");        mapper.save(user);        sqlSession.commit();        sqlSession.close();    }    @org.junit.Test    public void test2() throws IOException {        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        User byId = mapper.findById(10);        System.out.println(byId.getBirthday());        sqlSession.commit();        sqlSession.close();    }    /*查詢全部的資料*/    @org.junit.Test    public void test3() throws IOException {        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);        SqlSession sqlSession = sqlSessionFactory.openSession();        UserMapper mapper = sqlSession.getMapper(UserMapper.class);        List<User> userList = mapper.findAll();        for (User user : userList) {            System.out.println(user);        }        sqlSession.close();    }}
           
mybatis if test 多條件_MyBatis_Day04