mybatis -- helloworld

来源:互联网 发布:icloud储存空间已满mac 编辑:程序博客网 时间:2024/05/15 08:44

这里写图片描述

加入jar包
加入mybatis核心包、依赖包、数据驱动包。
这里写图片描述

log4j.properties
在classpath下创建log4j.properties如下:

# Global logging configurationlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis默认使用log4j作为输出日志信息。

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 和spring整合后 environments配置将废除-->    <environments default="development">        <environment id="development">        <!-- 使用jdbc事务管理-->            <transactionManager type="JDBC" />        <!-- 数据库连接池-->            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver" />                <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" />                <property name="username" value="root" />                <property name="password" value="111111" />            </dataSource>        </environment>    </environments>    <!-- 加载映射文件 -->    <mappers>        <mapper resource="sqlmap/Users.xml"/>        <mapper resource="sqlmap/UserMapper.xml"/>    </mappers></configuration>

po类

package cn.sjtu.mybatis;import java.util.Date;public class User {    private int id;    private String username;// 用户姓名    private String sex;// 性别    private Date birthday;// 生日    private String 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 + "]";    }}

映射文件
在classpath下的sqlmap目录下创建sql映射文件Users.xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="test">    <!-- 根据id获取用户信息 -->    <select id="findUserById" parameterType="int" resultType="cn.sjtu.mybatis.User">        select * from user where id = #{id}    </select>    <!-- 自定义条件查询用户列表 -->    <select id="findUserByUsername" parameterType="java.lang.String" resultType="cn.sjtu.mybatis.User">       select * from user where username like '%${value}%'     </select>    <!-- 添加用户 -->    <insert id="insertUser" parameterType="cn.sjtu.mybatis.User">    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">        select LAST_INSERT_ID()     </selectKey>      insert into user(username,birthday,sex,address)       values(#{username},#{birthday},#{sex},#{address})    </insert>    <!-- 删除用户 -->    <delete id="deleteUserById" parameterType="int">        delete from user where id=#{id}    </delete></mapper>

加载映射文件
mybatis框架需要加载映射文件,将Users.xml添加在SqlMapConfig.xml,如下:

<mappers>        <mapper resource="sqlmap/User.xml"/></mappers>

测试程序

package cn.sjtu.mybatis.test;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.List;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 cn.sjtu.mybatis.User;public class MybatisTest1 {    // 根据 id查询用户信息    @Test    public void testFindUserById() throws IOException {        // 配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 查询单个记录,根据用户id查询用户信息            User user = sqlSession.selectOne("test.findUserById", 10);            // 输出用户信息            System.out.println(user);        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    // 根据用户名称模糊查询用户信息    @Test    public void testFindUserByUsername() throws IOException {        // 配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 查询单个记录,根据用户id查询用户信息            List<User> list = sqlSession.selectList("test.findUserByUsername", "张");            System.out.println(list.size());        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    // 添加用户信息    @Test    public void testInsert() throws IOException {        // 配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 添加用户信息            User user = new User();            user.setUsername("张大");            user.setAddress("河南郑州");            user.setSex("1");            user.setBirthday(new Date());            sqlSession.insert("test.insertUser", user);            //提交事务            sqlSession.commit();            System.out.println(user.getId()); //获取新增记录的id值        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }    // 根据id删除用户    @Test    public void testDelete() throws IOException {        // 配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 删除用户            sqlSession.delete("test.deleteUserById",27);            // 提交事务            sqlSession.commit();        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }}

Mapper动态代理方式
Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的类路径相同。
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

定义mapper映射文件UserMapper.xml
(内容同Users.xml),需要修改namespace的值为 UserMapper接口路径。

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.sjtu.mybatis.UserMapper">    <!-- 根据id获取用户信息 -->    <select id="findUserById" parameterType="int" resultType="cn.sjtu.mybatis.User">        select * from user where id = #{id}    </select>    <!-- 自定义条件查询用户列表 -->    <select id="findUserByUsername" parameterType="java.lang.String" resultType="cn.sjtu.mybatis.User">       select * from user where username like '%${value}%'     </select>    <!-- 添加用户 -->    <insert id="insertUser" parameterType="cn.sjtu.mybatis.User">    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">        select LAST_INSERT_ID()     </selectKey>      insert into user(username,birthday,sex,address)       values(#{username},#{birthday},#{sex},#{address})    </insert>    <!-- 删除用户 -->    <delete id="deleteUserById" parameterType="int">        delete from user where id=#{id}    </delete></mapper>

UserMapper.java(接口文件)

package cn.sjtu.mybatis;import java.util.List;public interface UserMapper {    //根据用户id查询用户信息    public User findUserById(int id) throws Exception;    //查询用户列表    public List<User> findUserByUsername(String username) throws Exception;    //添加用户信息    public void insertUser(User user) throws Exception; }

加载UserMapper.xml文件
修改SqlMapConfig.xml文件:

<!-- 加载映射文件 -->    <mappers>        <mapper resource="sqlmap/UserMapper.xml"/>    </mappers>

测试

package cn.sjtu.mybatis.test;import static org.junit.Assert.*;import java.io.IOException;import java.io.InputStream;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 cn.sjtu.mybatis.User;public class UserMapperTest {    // 根据 id查询用户信息    @Test    public void testFindUserById() throws IOException {        // 配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = Resources.getResourceAsStream(resource);        // 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);        // 数据库会话实例        SqlSession sqlSession = null;        try {            // 创建数据库会话实例sqlSession            sqlSession = sqlSessionFactory.openSession();            // 查询单个记录,根据用户id查询用户信息            User user = sqlSession.selectOne("cn.sjtu.mybatis.UserMapper.findUserById", 10);            // 输出用户信息            System.out.println(user);        } catch (Exception e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }        }    }}
0 0
原创粉丝点击