文档章节

mybatis 3.5.0版本(一)

mouos
 mouos
发布于 03/31 16:13
字数 1458
阅读 50
收藏 0

mybatis 3.5.0版本(一)

mybatis 3.5.0版本(二)

mybatis 3.5.0版本(三)

mybatis 3.5.0版本(四)

demo地址

mybatis入门

mybatis下载

导包

添加 lib/

添加数据库驱动

添加 log4j.properties

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

User

package com.company.model;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

    private int id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;

    public User() {

    }

    public User(String username, String sex, Date birthday, String address) {
        this.username = username;
        this.sex = sex;
        this.birthday = birthday;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}

全局配置文件

db.properties

jdbcUrl=jdbc:mysql://localhost:3306/mydatabase?characterEncoding=utf8
driverClass=com.mysql.jdbc.Driver
user=root
password=root123

SqlMapConfig.xml,可参考压缩包下mybatis-3.5.0.pdf文件

<?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>

    <properties resource="db.properties"></properties>

    <!-- 配置别名 -->
    <typeAliases>
        <!-- 第一种:
             <typeAlias type="com.company.model.User" alias="user"></typeAlias>
        -->

        <!-- 第一种:指定包名,别名就是类名,第一个小写 -->
        <package name="com.company.model"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driverClass}"/>
                <property name="url" value="${jdbcUrl}"/>
                <property name="username" value="${user}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 配置加载全局映射文件 -->
    <mappers>
        <mapper resource="com/company/model/sqlmap/User.xml"></mapper>
    </mappers>
</configuration>

映射文件

User.xml,可参考压缩包下mybatis-3.5.0.pdf文件

<?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="user">

    <!--
    如果参数为简单类型时,#{}里面的参数名称可以是任意定义
    parameterType 指定输入参数的java类型
     -->
    <select id="getUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

    <!-- 模糊查询 -->
    <select id="getUserByName" parameterType="String" resultType="user">
        <!-- 如果参数为简单类型时,${}里面的参数名称必须为value -->
        select * from user where username like '%${value}%'
    </select>

    <!-- 插入 占位写模型的属性 -->
    <insert id="insertUser" parameterType="user">
        <!-- 如果参数为简单类型时,${}里面的参数名称必须为value -->
        insert into user (username,sex,birthday,address)
        value (#{username}, #{sex}, #{birthday}, #{address})
    </insert>

    <!-- 插入成功后自动返回主键  -->
    <insert id="insertUserBckId" parameterType="user">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            <!-- mysql使用last_insert_id() -->
            select last_insert_id()
        </selectKey>

        insert into user (username,sex,birthday,address)
        value (#{username}, #{sex}, #{birthday}, #{address})
    </insert>

    <!-- 删除 -->
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>

    <!-- 更新 -->
    <update id="updateUser" parameterType="user">
        update user set username = #{username}, sex = #{sex}
        where id = #{id}
    </update>

</mapper>

测试

    @Test
    public void func() throws IOException {

        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sessionFactory.openSession();

//        User user = sqlSession.selectOne("getUserById", 10);

        // 模糊查询
//        List<User> list = sqlSession.selectList("getUserByName", "张");


        // 插入
//        User user = new User("zhang", "1", new Date(), "北京");
//        sqlSession.insert("insertUser", user);

        // 插入成功后自动返回主键
//        User user = new User("zhangsan00", "1", new Date(), "北京");
//        sqlSession.insert("insertUserBckId", user);
//        System.out.println(user.getId());

        // 删除
//        sqlSession.delete("deleteUser", 34);

        // 更新
        User user = new User();
        user.setId(35);
        user.setUsername("lisi");
        user.setSex("2");
        sqlSession.update("updateUser", user);


        sqlSession.commit();
        sqlSession.close();
    }

mapper

UserMapper

package com.company.mapper;

import com.company.model.User;

public interface UserMapper {

    public int save(User user);

    public User getUserById(int id);
}

UserMapper.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.company.mapper.UserMapper">

    <insert id="save" parameterType="user">
        insert into user (username,sex,birthday,address)
        value (#{username}, #{sex}, #{birthday}, #{address})
    </insert>

    <select id="getUserById" parameterType="int" resultType="user">
        select * from user where id = #{id}
    </select>

    <select id="getUserByUserQueryVO" parameterType="userQueryVO" resultType="user">
        SELECT u.* FROM user u WHERE u.id = #{user.id}
    </select>

    <select id="getUserByMap" parameterType="hashmap" resultType="user">
        select u.* from user u where username like '%${username}%' and sex = #{sex}
    </select>

</mapper>

SqlMapConfig.xml 

    <mappers>

        <!-- 加载映射文件的方式:第一种 -->
        <mapper resource="com/company/mapper/UserMapper.xml"></mapper>

        <!-- 第二种
         <mapper url="/Users/mac/Desktop/gwl/java学习代码/MyBatisDemo/myBatis/src/com/company/mapper/UserMapper.xml"></mapper> 
         -->

        <!-- 第三种
             写类名,需要有映射文件UserMapper.xml对应,名字一样

             如果没有映射文件UserMapper.xml,则UserMapper声明成注解
             @Insert("insert into user (username,sex,birthday,address) value (#{username}, #{sex}, #{birthday}, #{address})")
             @Select("select * from user where id = #{id}")

        <mapper class="com.company.mapper.UserMapper"></mapper> 
        -->

        <!-- 第四种
        <package name="com.company.mapper"/>
        -->

    </mappers>

测试

    @Test
    public void func3() throws IOException {

        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sessionFactory.openSession();

        UserMapper userMapper = session.getMapper(UserMapper.class);

//        User u = userMapper.getUserById(1);

//        User user = new User("lisi", "1", new Date(), "北京");
//        userMapper.save(user);
//        session.commit();

//        UserQueryVO queryVO = new UserQueryVO();
//        User user = new User();
//        user.setId(1);
//        queryVO.setUser(user);
//        List<User> list = userMapper.getUserByUserQueryVO(queryVO);
//        System.out.println(list);

        Map<String,Object> map = new HashMap<>();
        map.put("username","张");
        map.put("sex","1");
        List<User> userByMap = userMapper.getUserByMap(map);
        System.out.println(userByMap);
    }

resultMap结果返回类型

UserMapper.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.company.mapper.UserMapper">

    <!-- 返回的数据为基本类型 -->
    <select id="getUserCount" parameterType="userQueryVO" resultType="int">
        select count(*) from user where sex = #{user.sex}
    </select>

    <!-- 返回的数据为resultMap类型 -->
    <resultMap id="userResultMap" type="user">
        <id property="id" column="id_"></id>
        <result property="username" column="username_"></result>
        <result property="sex" column="sex_"></result>
        <result property="birthday" column="birthday_"></result>
        <result property="address" column="address_"></result>
    </resultMap>
    <select id="getUserByIdResultMap" parameterType="int" resultMap="userResultMap">
        select
         id_,
         username_,
         sex_,
         birthday_,
         address_
        from user where id_ = #{id}
    </select>

</mapper>

测试

    @Test
    public void func4() throws IOException {

        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sessionFactory.openSession();

        UserMapper userMapper = session.getMapper(UserMapper.class);

        //返回的数据为基本类型
//        UserQueryVO queryVO = new UserQueryVO();
//        User user = new User();
//        user.setSex("1");
//        queryVO.setUser(user);
//        int count = userMapper.getUserCount(queryVO);

        // 返回的数据为resultMap类型
        User user = userMapper.getUserByIdResultMap(10);
    }

if和where

    <sql id="select_user_where">
        <if test="user != null">
            <if test="user.sex != null and user.sex != ''">
                sex = #{user.sex}
            </if>
            <if test="user.username != null and user.username != ''">
                and username like '%${user.username}%'
            </if>
        </if>
    </sql>
    <select id="getUserList" parameterType="userQueryVO" resultType="user">
        select * from user

        <where>
            <include refid="select_user_where"></include>
        </where>
    </select>
    @Test
    public void func() throws IOException {

        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sessionFactory.openSession();

        UserMapper userMapper = session.getMapper(UserMapper.class);

        UserQueryVO queryVO = new UserQueryVO();
        User user = new User();
        user.setSex("1");
        user.setUsername("张");
        queryVO.setUser(user);
        List<User> list = userMapper.getUserList(queryVO);
        System.out.println(list);
    }

foreach

    <select id="getUserByIds" parameterType="userQueryVO" resultType="user">
        <!-- select * from user where id id (1,2,3) -->

        select * from user

        <where>
            <if test="ids != null and ids.size > 0">
                <foreach collection="ids" item="id" open="id in (" close=")" separator=",">
                    ${id}
                </foreach>
            </if>
        </where>
    </select>

    <!-- 参数是数组 -->
    <select id="getUsersByIds" parameterType="list" resultType="user">
        select * from user

        <where>
            <if test="list != null and list.size > 0">
                <foreach collection="list" item="id" open="id in (" close=")" separator=",">
                    ${id}
                </foreach>
            </if>
        </where>
    </select>
    @Test
    public void func() throws IOException {

        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sessionFactory.openSession();

        UserMapper userMapper = session.getMapper(UserMapper.class);

        UserQueryVO queryVO = new UserQueryVO();
        List<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(20);
        ids.add(30);
        queryVO.setIds(ids);
        List<User> list = userMapper.getUserByIds(queryVO);

        //参数是数组
//        List<Integer> ids = new ArrayList<>();
//        ids.add(1);
//        ids.add(20);
//        ids.add(30);
//        List<User> list = userMapper.getUsersByIds(ids);
    }

© 著作权归作者所有

mouos
粉丝 1
博文 245
码字总数 127890
作品 0
其它
私信 提问
批量测试Mybatis项目中Sql是否正确

去Oracle行动 最近公司要发展海外项目,所以要将现有的系统全部平移过去,另外数据库也要从原来的变为。公司的数据库交互层面使用的是,而与也有一些语法上的不同。所以在项目中的Sql要改动,...

不学无数的程序员
2018/12/05
0
0
Mybatis 通用 Mapper 3.5.0 发布

Mybatis 通用 Mapper 3.5.0 已发布。MyBatis 通用 Mapper 极其方便的使用 MyBatis 单表的增删改查,支持单表操作,不支持通用的多表联合查询。通用 Mapper 可以极大的方便开发人员。可以随意...

Liuzh_533
2018/01/09
2K
4
Mybatis 通用 Mapper 3.5.2 发布

Mybatis 通用 Mapper 3.5.2 已发布。MyBatis 通用 Mapper 极其方便的使用 MyBatis 单表的增删改查,支持单表操作,不支持通用的多表联合查询。通用 Mapper 可以极大的方便开发人员。可以随意...

Liuzh_533
2018/01/24
2.1K
9
MyBatis 3.5.1 发布,Java 数据持久层框架

MyBatis 3.5.1 发布了,MyBatis 的前身即 iBatis,是一个数据持久层(ORM)框架。它提供的持久层框架包括 SQL Maps 和 Data Access Objects(DAO)。 版本更新如下: Bug 修复 使用参数名称指...

xplanet
04/09
0
0
MyBatis 3.5.0 发布,Java 数据持久层框架

MyBatis 3.5.0 需要Java 8 及以后版本. 增强: Avoid 'Illegal reflective access' warning on JDK 9+. #1156 Added Automatic-Module-Name : org.mybatis #1199 Support java.util.Optional......

淡漠悠然
01/21
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Android Camera模块解析之拍照

最近学习Android的camera模块,本文先介绍一下camera2的api,然后给出android camera拍照的例子,讲解一下camera 拍照的原因知识,与大家共勉。 camera2 介绍 android camera拍照功能介绍 一...

天王盖地虎626
17分钟前
5
0
Excel 曝Power Query安全漏洞

近日,Mimecast 威胁中心的安全研究人员,发现了微软 Excel 电子表格应用程序的一个新漏洞,获致 1.2 亿用户易受网络攻击。其指出,该安全漏洞意味着攻击者可以利用 Excel 的 Power Query 查...

linuxCool
24分钟前
1
0
SpringBoot | 第三十八章:基于RabbitMQ实现消息延迟队列方案

前言 >前段时间在编写通用的消息通知服务时,由于需要实现类似通知失败时,需要延后几分钟再次进行发送,进行多次尝试后,进入定时发送机制。此机制,在原先对接银联支付时,银联的异步通知也...

oKong
24分钟前
6
0
Excel 曝Power Query安全漏洞

近日,Mimecast 威胁中心的安全研究人员,发现了微软 Excel 电子表格应用程序的一个新漏洞,获致 1.2 亿用户易受网络攻击。其指出,该安全漏洞意味着攻击者可以利用 Excel 的 Power Query 查...

linux-tao
40分钟前
1
0
Java - NIO框架

Java NIO提供了与标准IO不同的IO工作方式。 Channels and Buffers(通道和缓冲区) 标准IO基于字节流和字符流,NIO基于通道(Channel)和缓冲区(Buffer)。数据从channel读取到buffer,或从Buffe...

丰田破产标志
44分钟前
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部