MyBatis(一)

作者: 慕凌峰 | 来源:发表于2017-02-16 12:18 被阅读70次
    MyBatis

    一、MyBatis简介

    </br>

    1、MyBatis的优点

    </br>

    • 消除了大量的JDBC冗余代码

    • 低学习曲线

    • 友好的Spring集成支持

    • 除本身的缓存外,能友好的第三方缓存类库集成支持

    • 良好的性能

    </br>

    2、MyBatis简单实例

    </br>

    • 创建表
    create table t_person
    (
        id int auto_increment not null primary key,
        name varchar(20) not null,
        age int,
        address varchar(50)
    );
    
    • sql配置文件
    <?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>
        <!-- 数据库连接的环境,可以配置多个环境 -->
        <environments default="hello_mysql">
            <!-- 环境 -->
            <environment id="hello_mysql">
                <!-- 事务管理的策略  type = "jdbc" or "managed" -->
                <transactionManager type="jdbc"/>
                <!-- 数据源 type = "pooled"连接池   or "unpooled"不用连接池 or "jndi"跟Spring用 -->
                <dataSource type="pooled">
                    <property name="driver" value="org.gjt.mm.mysql.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
        
        <!-- 加载配置文件PersonMapper.xml -->
        <mappers>
            <mapper resource="com/xiao/mybatis/pojo/PersonMapper.xml"/>
        </mappers>
        
    </configuration>
    
    • pojo类
    package com.xiao.mybatis.pojo;
    
    public class Person {
    
        private int pid;
        private String pname;
        private int age;
        private String address;
        
        public Person() {
            
        }
        
        public Person(String pname,int age,String address){
            this.pname = pname;
            this.age = age;
            this.address = address;
        }
    
        public int getPid() {
            return pid;
        }
    
        public void setPid(int pid) {
            this.pid = pid;
        }
    
        public String getPname() {
            return pname;
        }
    
        public void setPname(String pname) {
            this.pname = pname;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public String toString() {
            return "Person [pid=" + pid + ", pname=" + pname + ", age=" + age
                    + ", address=" + address + "]";
        }
        
    }
    
    • pojo配置文件
    <?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.xiao.mybatis.pojo">
        <!-- 插入 -->
        <insert id="addPerson" parameterType="com.xiao.mybatis.pojo.Person" useGeneratedKeys="true" keyProperty="pid">
            insert into t_person values(null,#{pname},#{age},#{address})
        </insert>
        <!-- 查询 -->
        <select id="getPersonList" resultType="com.xiao.mybatis.pojo.Person">
            select * from t_person
        </select>
        <select id="getPersonByPid" parameterType="int" resultType="com.xiao.mybatis.pojo.Person">
            select * from t_person where pid = #{pid}
        </select>
        <!-- 更新 -->
        <update id="updatePesron" parameterType="com.xiao.mybatis.pojo.Person">
            update t_person set pname = #{pname} , age = #{age} , address = #{address} where pid = #{pid}
        </update>
        <!-- 删除 -->
        <delete id="deletePerson" parameterType="int">
            delete from t_person where pid = #{pid}
        </delete>
    </mapper>
    
    • 测试类
    package com.xiao.mybatis.test;
    
    import java.io.IOException;
    import java.io.InputStream;
    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 com.xiao.mybatis.pojo.Person;
    
    public class PersonDaoTest {
    
        SqlSession session = null;
    
        /**
         * 在连接数据库前加载
         */
        public void setUp() {
    
            try {
                // 1、加载配置文件sqlMapConfig.xml
                InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    
                // 2、解析配置文件sqlMapConfig.xml
                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    
                // 3、通过factory创建session对象
                session = factory.openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        
        /**
         * 执行完操作后提交事务,以及关闭连接
         */
        public void tearDown() {
            // 5、提交或回滚
            session.commit();// session.rollback();
    
            // 6、关闭session
            if (null != session) {
                session.close();
            }
        }
    
        // 一、插入数据
        public void addPersonTest() {
    
            setUp();
    
            Person person = new Person("boss", 20, "China");
    
            // 4、执行插入操作
            int count = session.insert("com.xiao.mybatis.pojo.addPerson", person);
            
            System.out.println(count > 0 ? "插入成功" : "插入失败");
            
            tearDown();
        }
    
        // 二、查询数据
        public void selectPersonTest() {
    
            setUp();
    
            List personList = session.selectList("com.xiao.mybatis.pojo.getPersonList");
            
            System.out.println( null != personList ? "查询成功" : "查询失败");
    
            if(null != personList){
                System.out.println(personList.toString());
            }
                
            tearDown();
        }
        
        // 二、条件查询数据
        public void selectPersonByIdTest() {
    
            setUp();
    
            Person person = (Person) session.selectOne("com.xiao.mybatis.pojo.getPersonByPid",new Integer(7));
            
            System.out.println( null != person ? "查询数据成功" : "查询失败");
            
            if(null != person){
                System.out.println(person.toString());
            }
            
            tearDown();
        }
        
        // 三、修改数据
        public void updatePersonTest(){
            setUp();
    
            Person person = new Person(5,"boss", 100, "America");
            
            int count = session.update("com.xiao.mybatis.pojo.updatePesron", person);
            
            System.out.println(count > 0 ? "修改成功" : "修改失败");
            
            tearDown();
        }
        
        // 四、删除数据
        
        public void deletePersonTest(){
            setUp();
            
            Person person = new Person(5,"boss", 100, "America");
            
            int count = session.delete("com.xiao.mybatis.pojo.deletePerson", person);
            
            System.out.println(count > 0 ? "删除成功" : "删除失败");
            
            tearDown();
        }
    
        public static void main(String[] args) {
            PersonDaoTest personDaoTest = new PersonDaoTest();  
    
            //personDaoTest.addPersonTest();        // 插入
            //personDaoTest.selectPersonTest();     // 查询
            personDaoTest.selectPersonByIdTest();
            //personDaoTest.updatePersonTest();     // 修改
            //personDaoTest.deletePersonTest();     // 删除
            
        }
    }
    
    

    进行运行,查看运行结果

    相关文章

      网友评论

        本文标题:MyBatis(一)

        本文链接:https://www.haomeiwen.com/subject/auvnmttx.html