zoukankan      html  css  js  c++  java
  • MyBatis入门2

    一、实现单一查询

    1)核心配置文件:Configuration.xml 

    1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
     3 <configuration>
     4     <environments default="development">
     5         <environment id="development">
     6             <transactionManager type="JDBC" />
     7             <!-- 配置数据库连接信息 -->
     8             <dataSource type="POOLED">
     9                 <property name="driver" value="com.mysql.jdbc.Driver" />
    10                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
    11                 <property name="username" value="root" />
    12                 <property name="password" value="XDP" />
    13             </dataSource>
    14         </environment>
    15     </environments>
    16     
    17 </configuration>

    2)定义表所对应的实体类

    package me.gacl.domain;
    
    /**
     * @author gacl
     * users表所对应的实体类
     */
    public class User {
    
        //实体类的属性和表的字段名称一一对应
        private int id;
        private String name;
        private int age;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
        }
    }

    3)定义操作users表的sql映射文件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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
    例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
     -->
    <mapper namespace="me.gacl.mapping.userMapper">
        <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
        使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
        resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
        User类就是users表所对应的实体类
        -->
        <!-- 
            根据id查询得到一个user对象
         -->
        <select id="getUser" parameterType="int" 
            resultType="me.gacl.domain.User">
            select * from users where id=#{id}
        </select>
    </mapper>

    4)在conf.xml文件中注册userMapper.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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC" />
                <!-- 配置数据库连接信息 -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                    <property name="username" value="root" />
                    <property name="password" value="XDP" />
                </dataSource>
            </environment>
        </environments>
        
        <mappers>
            <!-- 注册userMapper.xml文件, 
            userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
            <mapper resource="me/gacl/mapping/userMapper.xml"/>
        </mappers>
        
    </configuration>

    5)编写测试代码:执行定义的select语句

    package me.gacl.test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.Reader;
    import me.gacl.domain.User;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class Test1 {
    
        public static void main(String[] args) throws IOException {
            //mybatis的配置文件
            String resource = "conf.xml";
            //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
            InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
            //构建sqlSession的工厂
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
            //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
            //Reader reader = Resources.getResourceAsReader(resource); 
            //构建sqlSession的工厂
            //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            //创建能执行映射文件中sql的sqlSession
            SqlSession session = sessionFactory.openSession();
            /**
             * 映射sql的标识字符串,
             * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
             * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
             */
            String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串
            //执行查询返回一个唯一user对象的sql
            User user = session.selectOne(statement, 1);
            System.out.println(user);
        }
    }

    二、使用MyBatis对表执行CRUD操作——基于XML的实现

    使用到的工具类:

    package com.ual.Utils;
    
    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.Reader;
    
    public class MybatisUtil {
        /**
         * 获取sessionFactory
         * @return  SqlSessionFactory
         */
        public static SqlSessionFactory getSqlSessionFactory() throws IOException {
            String resource="Configuration.xml";
            Reader resourceAsReader = Resources.getResourceAsReader(resource);
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsReader);
            return factory;
        }
        /**
         * 获取sqlSession
         * @return SqlSession
         */
        public static SqlSession getSqlSession() throws IOException {
            return getSqlSessionFactory().openSession();
        }
        /**
         * 获取SqlSession
         * @param isAutoCommit
         *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
         *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
         * @return SqlSession
         */
        public static SqlSession getSqlSession(boolean isAutoCommit) throws IOException {
            return getSqlSessionFactory().openSession(isAutoCommit);
        }
    
    }

    1.UserMapper.xml映射文件

    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    
           Copyright 2009-2016 the original author or authors.
    
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
    
              http://www.apache.org/licenses/LICENSE-2.0
    
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
    
    -->
    <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="User">
      <resultMap type="com.ual.domain.User" id="UserResult">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="username" jdbcType="VARCHAR" property="username"/>
        <result column="password" jdbcType="VARCHAR" property="password"/>
      </resultMap>
      <!--根据id查询一个User对象-->
      <select id="getById" parameterType="Integer" resultMap="UserResult">
        select * from user where id=#{id}
      </select>
      <!--创建用户-->
      <insert id="addUser" parameterType="com.ual.domain.User">
        insert into user(username,password)values (#{username},#{password})
      </insert>
      <!--删除用户-->
      <delete id="deleteUser" parameterType="String">
        delete from user where username=#{username}
      </delete>
      <!--查询全部用户-->
      <select id="selectAll" resultMap="UserResult">
        select * from user
      </select>
    </mapper>

    2.dao实现类

    package com.ual.dao;
    
    import com.ual.Utils.MybatisUtil;
    import com.ual.domain.User;
    import org.apache.ibatis.session.SqlSession;
    
    import java.util.List;
    
    public class UserDaoImpl implements UserDao {
        SqlSession sqlSession=null;
        @Override
        public void selectById(Integer id) {
            try{
                sqlSession = MybatisUtil.getSqlSession();
                User user = sqlSession.selectOne("User.getById",id);
                System.out.println(user);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(sqlSession!=null)
                sqlSession.close();
            }
        }
    
        @Override
        public void insert(User user) {
            try{
                 sqlSession = MybatisUtil.getSqlSession(true);
                sqlSession.insert("User.addUser",user);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(sqlSession!=null)
                    sqlSession.close();
            }
        }
    
        @Override
        public void deleteByName(String name) {
            try{
                sqlSession = MybatisUtil.getSqlSession(true);
                sqlSession.insert("User.deleteUser",name);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(sqlSession!=null)
                    sqlSession.close();
            }
        }
    
        @Override
        public void update(User user) {
    
        }
    
        @Override
        public List<User> selectAll() {
            try{
                sqlSession = MybatisUtil.getSqlSession(true);
                //查询到的结果,自动封装成List<User>
                return sqlSession.selectList("User.selectAll");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(sqlSession!=null)
                    sqlSession.close();
            }
            return null;
        }
    }

    3.单元测试

    package com.ual;
    
    import com.ual.dao.MessageDao;
    import com.ual.dao.UserDaoImpl;
    import com.ual.domain.User;
    
    import java.util.List;
    
    public class Test {
        @org.junit.Test
        public void test(){
            UserDaoImpl userDao = new UserDaoImpl();
            userDao.selectById(1);
        }
        @org.junit.Test
        public void test2(){
            User user1 = new User();
            user1.setUsername("xx");
            user1.setPassword("1234");
            UserDaoImpl userDao = new UserDaoImpl();
            userDao.insert(user1);
        }
        @org.junit.Test
        public void test3(){
            UserDaoImpl userDao = new UserDaoImpl();
            userDao.deleteByName("xx");
        }
        @org.junit.Test
        public void test4(){
            UserDaoImpl userDao = new UserDaoImpl();
            List<User> users = userDao.selectAll();
            for (User u:users
                 ) {
                System.out.println(u);
            }
        }
    
    
    }

    三、使用MyBatis对表执行CRUD操作——基于注解的实现

    1.定义sql映射的接口

    package com.ual.Mapping;
    
    import com.ual.domain.User;
    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 UserMapping {
        //使用@Insert注解指明方法要执行的SQL
        @Insert("insert into user(username,password )values(#{username},#{password})")
        public int add(User user);
        //使用@Deslete注解指明deleteByName方法要执行的sql
        @Delete("delete from user where username=#{username}")
        public int deleteByName(String name);
        @Update("update user set username=#{username},password=#{password} where id= #{id}")
        public int update(User user);
        @Select("select * from user where id =#{id}")
        public User getById(int id );
        @Select("select * from user")
        public List<User> getAll();
    
    }

    2、在conf.xml文件中注册这个映射接口

    <?xml version="1.0" encoding="UTF-8" ?>
    <!--
    
           Copyright 2009-2016 the original author or authors.
    
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
    
              http://www.apache.org/licenses/LICENSE-2.0
    
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
    
    -->
    <!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
    
    <configuration>
      <settings>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="useColumnLabel" value="true"/>
      </settings>
    
      <typeAliases>
        <typeAlias alias="User" type="com.ual.domain.User"/>
      </typeAliases>
    
      <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC">
            <property name="" value=""/>
          </transactionManager>
          <dataSource type="UNPOOLED">
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql:///mybatis?serverTimezone=GMT%2B8"/>
            <property name="username" value="root"/>
            <property name="password" value="1234"/>
          </dataSource>
        </environment>
      </environments>
    
      <mappers>
        <mapper resource="User.xml"/>
        <!--注册UserMapping映射接口-->
        <mapper class="com.ual.Mapping.UserMapping"/>
      </mappers>
    
    </configuration>

    3.测试

     @org.junit.Test
        public void test5() throws IOException {
            SqlSession sqlSession = MybatisUtil.getSqlSession(true);
            //获得会话后,获取接口,通过获取的接口调用里面定义的方法
            UserMapping mapper = sqlSession.getMapper(UserMapping.class);
            User user = new User();
            user.setUsername("wzh");
            user.setPassword("123o");
            mapper.add(user);
            sqlSession.close();
        }
  • 相关阅读:
    socket通信原理
    socket通信基础内容
    内核中断过程
    爬虫基础模块
    关于多个运算符的问题
    前戏
    js扩展
    加密
    django之form
    Django
  • 原文地址:https://www.cnblogs.com/UalBlog/p/10741222.html
Copyright © 2011-2022 走看看