Mybatis xml和注解映射实现

项目的目录结构

src/com.java.mybatis/mybatis-config.xml
src/com.java.mybatis/User.java

package com.java.mybatis;

public class User {
    private Integer id;
    private String name;
    private String sex;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

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

    @Override
    public String toString() {
        return "User[id=" + id + ", name=" + name + ", sex=" + sex + "]";
    }
}

src/com.java.mybatis/UserMapper.java

Mybatis的xml实现映射

  • src/com.java.mybatis/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>
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <!-- 数据库环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- MySQL数据库驱动 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <!-- 连接数据库的URL -->
                <property name="url"
                          value="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
      <mappers>
        <!-- xml实现映射器-->
        <mapper resource="com/java/mybatis/UserMapper.xml" />
      </mappers>
</configuration>
  • src/com.java.mybatis/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.java.mybatis.UserMapper">
    <!-- 根据uid查询一个用户信息 -->
    <select id="selectUserById" parameterType="Integer"
            resultType="com.java.mybatis.User">
        select * from user where id = #{id}
    </select>
    <!-- 查询所有用户信息 -->
    <select id="selectAllUser" resultType="com.java.mybatis.User">
        select * from user
    </select>
    <!-- 添加一个用户,#{name}为 com.java.mybatis.User 的属性值 -->
    <insert id="addUser" parameterType="com.java.mybatis.User">
        insert into user (name,sex) values(#{name},#{sex})
    </insert>
    <!--修改一个用户 -->
    <update id="updateUser" parameterType="com.java.mybatis.User">
        update user set name = #{name},sex = #{sex} where id = #{id}
    </update>
    <!-- 删除一个用户 -->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id = #{id}
    </delete>
</mapper>
  • 测试文件
package com.java.mybatis;

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.util.List;

public class MyBatisTest {
    public static void main(String[] args) {
        try {
            InputStream config = Resources.getResourceAsStream("./com/java/mybatis/mybatis-config.xml");

            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);

            SqlSession ss = ssf.openSession();

            // 查询一个用户
            User user = ss.selectOne("com.java.mybatis.UserMapper.selectUserById", 1);
            System.out.println(user);

            // 新增一个用户
            User add = new User();
            add.setName("David");
            add.setSex("male");
            ss.insert("com.java.mybatis.UserMapper.addUser", add);

            // 修改一个用户
            User updateUser = new User();
            updateUser.setId(5);
            updateUser.setName("Lucy");
            updateUser.setSex("female");
            ss.update("com.java.mybatis.UserMapper.updateUser", updateUser);

            // 删除一个用户
            ss.delete("com.java.mybatis.UserMapper.deleteUser", 4);

            // 查询所有用户
            List<User> listUser = ss.selectList("com.java.mybatis.UserMapper.selectAllUser");
            for (User u : listUser) {
                System.out.println(u);
            }

            // 提交事务
            ss.commit();
            ss.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Mybatis的注解实现映射

  • src/com.java.UserMapper接口的
package com.java.mybatis;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserMapper {
    @Select("SELECT * FROM user WHERE id=#{id}")
    public User getUser(Long id);

    @Select("SELECT * FROM user")
    public List<User> getAllUser();
    
    @Insert("INSERT INTO user (name, sex) VALUES(#{name}, #{sex}")
    public int addUser(@Param(value="name") String name, @Param(value="sex") String sex);

    @Update("UPDATE user SET name=#{name}, set=#{sex} WHERE id=#{id}")
    public int updateUser(User user);

    @Delete("DELETE FROM user WHERE id=#{id}")
    public Long deleteUserById(Long id);
}
  • src/com.java.mybatis/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>
    <settings>
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <!-- 数据库环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- MySQL数据库驱动 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <!-- 连接数据库的URL -->
                <property name="url"
                          value="jdbc:mysql://192.168.10.10:3306/test?characterEncoding=utf8" />
                <property name="username" value="homestead" />
                <property name="password" value="secret" />
            </dataSource>
        </environment>
    </environments>
    <!-- 将mapper文件加入到配置文件中 -->
     <mappers>
        <!-- 注解实现映射器 -->
        <mapper class="com.java.mybatis.UserMapper" />
     </mappers>
</configuration>
  • 测试文件
package com.java.mybatis;

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;

public class MyBatisInterfaceTest {

    public static void main(String[] args) {
        try {
            InputStream config = Resources.getResourceAsStream("./com/java/mybatis/mybatis-config.xml");

            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
            
            // 若mybatis-config.xml没有配置<mapper class="com.java.mybatis.UserMapper" />,
            // 则需要ssf.getConfiguration().addMapper(UserMapper.class);
            // 若mybatis-config.xml没有配置<mapper class="com.java.mybatis.UserMapper" />,
            // 则需要注释ssf.getConfiguration().addMapper(UserMapper.class); 代码
            ssf.getConfiguration().addMapper(UserMapper.class);

            SqlSession ss = ssf.openSession();

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

            User user = userMapper.getUser(1L);
            System.out.println(user);

            ss.commit();
            ss.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

posted @ 2021-04-22 15:10  phper-liunian  阅读(132)  评论(0编辑  收藏  举报