Mybatis简单工程

一:创建Maven

  • Mybatis简单工程
  • 直接用idea本地仓库.创建完成即可
  • 打开main -> 右键 ->找到directory-> 建立target和Resources文件夹(前提:没有target和Resources文件)

二:配置pom.xml (放置Resources文件)

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>mybatis-01</artifactId>
  <version>1.0-SNAPSHOT</version>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
  </dependencies>
  
</project>
  • 标红 ->右键找到maven->点第一项->等待下载完成

三.配置XML(放置Resources文件)

  • 环境配置.xml(mybatis-cfg.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?characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value=""/>
                </dataSource>
            </environment>
        </environments>
        <!--引入映射配置-->
        <mappers>
            <!--使用相对路径方式引入-->
            <mapper resource="UserDao.xml"/>
        </mappers>
    </configuration>
  • 映射配置.xml(UserDao.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.po.dao.UserDao">
        
        <select id="getAllUser" resultType="com.po.pojo.User">
                select * from user
        </select>
        <select id="getUserById" resultType="com.po.pojo.User">
                select * from user where id = #{id}
        </select>
        <insert id="insertUser">
            insert into user value(#{id},#{name},#{password})
        </insert>
        <update id="updateUser">
            update user set name=#{name},password=#{password} where id=#{id}
        </update>
        <delete id="deleteUser">
            delete from user where id=#{id}
        </delete>
        
    </mapper>

四:项目

  • 实体类(User.xml)
  • package com.po.pojo;
    
    public class User {
        private  Integer id;
        private  String name;
        private  String password;
    
        public User(Integer id, String name ,String password) {
            setId(id);
            setName(name);
            setPassword(password);
        }
    
        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 getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "ID:"+id+"\t"+"NAME:"+name+"\t"+"PASSWORD:"+password;
        }
        
    }
    

  • 创建一个测试.java(selectUser.java)看看自己有没有其他配置出问题
  • package org.example;
    
    import com.po.pojo.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;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class selectUser {
        public static void main(String[] args) throws IOException {
    
            InputStream inputStream= Resources.getResourceAsStream("mybatis-cfg.xml");
    
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder =new SqlSessionFactoryBuilder();
    
            SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream);
    
            SqlSession sqlSession=sqlSessionFactory.openSession();
    
            List<User> list=sqlSession.selectList("getAllUser");
            for(User user:list){
                System.out.println(user);
            }
            sqlSession.close();
        }
    
    }
    

  • 结构
  • Mybatis简单工程
  • 创建UserDao接口
  • package com.po.dao;
    import com.po.pojo.User;
    import java.util.List;
    
    public interface UserDao {
        List<User> getAllUser();
    
        User getUserById(Integer id);
    
        void insertUser(User user);
    
        void updateUser(User user);
    
        void deleteUserById(Integer id);
    }
    

  • 测试增删改查(AppTes  放置在你的测试类中t)
  •  @Test
        public void getAllUser() throws IOException {
            //从xml中获取sqlSessionFactory
            String resource = "mybatis-cfg.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //获取sqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //现在的mybatis接口式编程写法
            //相当于接口的实现类
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> list = userDao.getAllUser();
            for(User user:list){
                System.out.println(user);
            }
            sqlSession.close();
        }
    
        @Test
        public void getUserById() throws IOException {
            //从xml中获取sqlSessionFactory
            String resource = "mybatis-cfg.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            User user = userDao.getUserById(1);
            System.out.println(user);
            sqlSession.close();
        }
        @Test
        public void insertUser() throws IOException {
            String resource = "mybatis-cfg.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
    
            //使用自动提交,如果不使用则需要sqlSession.commit();手动提交
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            //SqlSession sqlSession = sqlSessionFactory.openSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            //需要写有参和无参构造函数
            User user = new User(6,"1","1156");
            userDao.insertUser(user);
            System.out.println(user);
    
        }
        @Test
        public void updateUser() throws IOException {
            String res = "mybatis-cfg.xml";
            InputStream is = Resources.getResourceAsStream(res);
            SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            User user = new User(2,"uzi","1");
            userDao.updateUser(user);
    
        }
        @Test
        public void deleteUserById() throws IOException {
            String res = "mybatis-cfg.xml";
            InputStream is = Resources.getResourceAsStream(res);
            SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession(true);
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            userDao.deleteUserById(5);
        }
  • (实体类中可以不用创建有参构造,但测试类中自己user.setID()调用即可)

 

 

上一篇:Mybatis 执行器


下一篇:idea框架实现增删改查