美文网首页JavaWeb
JavaWeb开发:mybatis入门

JavaWeb开发:mybatis入门

作者: 蘑菇v5 | 来源:发表于2019-04-18 16:07 被阅读0次

    【声明:】本文是作者(蘑菇v5)原创,版权归作者 蘑菇v5所有,侵权必究。本文首发在简书。如若转发,请注明作者和来源地址!未经授权,严禁私自转载!

    mybatis官网

    简介:

    MyBatis 是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML注解来配置和映射原生类型、接口和 JavaPOJOPlain Old Java Objects,普通老式Java 对象)为数据库中的记录

    安装和使用

    要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于classpath 中即可。

    如果使用 Maven来构建项目,则需将下面的 dependency 代码置于pom.xml文件中:

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>x.x.x</version>
    </dependency>
    

    操作步骤

    1、创建配置文件

    创建jdbc_config.propertiesmybatis-config.xml文件,完成和数据库的连接设置操作

    jdbc_config.properties:

    username=ceshi
    password=123
    url=jdbc:mysql://localhost:3306/mybatis
    driver=com.mysql.jdbc.Driver
    

    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>
    <!--引入properties文件, -->
    <properties resource="jdbc_config.properties">
    <typeAliases>
            <package name="org.mybatis.example.model"/>
        </typeAliases>
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
    <!--读取properties文件里的数据-->
          <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
          </dataSource>
        </environment>
      </environments>
      <mappers>
        <mapper resource="org/mybatis/example/model/User.xml"/>
      </mappers>
    </configuration>
    

    2、根据数据表创建相应的实体类

    public class User {
        private int id;
        private String username;
        private String password;
        private String nickname;
        private int type;
        private List<Address> addresses;
        
        public List<Address> getAddresses() {
            return addresses;
        }
        public void setAddresses(List<Address> addresses) {
            this.addresses = addresses;
        }
        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 getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getNickname() {
            return nickname;
        }
        public void setNickname(String nickname) {
            this.nickname = nickname;
        }
        public int getType() {
            return type;
        }
        public void setType(int type) {
            this.type = type;
        }
    }
    

    3、创建mapper.xml文件

    创建mapper文件完成对实体类的映射

    User.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="org.mybatis.example.model.User">
        <insert id="add" parameterType="User">
            insert into t_user (username,password,nickname,type)
                value(#{username},#{password},#{nickname},#{type})
        </insert>
        
        <update id="update" parameterType="User">
            update t_user set password=#{password},nickname=#{nickname},
    type=#{type} where id=#{id}
        </update>
        
        <delete id="delete" parameterType="int">
            delete from t_user where id=#{id}
        </delete>
        
        <select id="load" parameterType="int" resultType="User">
            select * from t_user where id=#{id}
        </select>
        
        <select id="list" resultType="User">
            select * from t_user
        </select>
    </mapper>
    

    4、创建SqlSessionFactory获取session执行相应的操作

    创建SQlSession,并且通过SqlSession完成对数据库的操作

    TestMyBatis:

    public class TestMyBatis {
    
        @Test
        public void testDelete() {
        SqlSession session = null;
            try {
                session = MyBatisUtil.createSession();
                session.delete(User.class.getName()+".delete",10);
                session.commit();
            }  catch (Exception e) {
                e.printStackTrace();
                session.rollback();
            } finally {
                MyBatisUtil.closeSession(session);
            }
        }
        
        @Test
        public void testAdd() {
            SqlSession session = null;
            try {
                session = MyBatisUtil.createSession();
                User u = new User();
                u.setNickname("刘德华");
                u.setPassword("10086");
                u.setType(0);
                u.setUsername("ldh");
                session.insert(User.class.getName()+".add", u);
                session.commit();
            } catch (Exception e) {
                e.printStackTrace();
                session.rollback();
            } finally {
                MyBatisUtil.closeSession(session);
            }
        }
        
        @Test
        public void testLoad() {
            SqlSession session = null;
            try{
                session = MyBatisUtil.createSession();
                User u = (User)session.selectOne(User.class.getName()+".load", 1);
                System.out.println(u.getNickname());
            } finally {
                MyBatisUtil.closeSession(session);
            }
        }
        
        @Test
        public void testList() {
            SqlSession session = null;
            try{
                session = MyBatisUtil.createSession();
                List<User> us = session.selectList(
                  User.class.getName()+".list", null);
                System.out.println(us.size());
            } finally {
                MyBatisUtil.closeSession(session);
            }
        }   
    }
    
    

    MyBatisUtil:

    public class MyBatisUtil {
        private static SqlSessionFactory factory;
        static {
            try {
                InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
                factory = new SqlSessionFactoryBuilder().build(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public static SqlSession createSession() {
            return factory.openSession();
        }
        
        public static void closeSession(SqlSession session) {
            if(session!=null) session.close();
        }
    }
    

    相关文章

      网友评论

        本文标题:JavaWeb开发:mybatis入门

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