首页 > 其他分享 >mybatis

mybatis

时间:2023-02-03 11:55:21浏览次数:49  
标签:mapper java atguigu org mybatis import com

Mybatis

文件结构

练习Mybatis

1、创建数据库、导入数据

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

2、pom文件

<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.atguigu</groupId>
  <artifactId>MybatisPrac</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>MybatisPrac</name>

  <dependencies>
<!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>

<!--    pojo-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok-maven-plugin</artifactId>
      <version>1.18.12.0</version>
      <scope>provided</scope>
    </dependency>


    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.11</version>
    </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13</version>
          <scope>test</scope>
      </dependency>


  </dependencies>


    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

3、mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">

<!--mybatis核心配置文件-->
<configuration>
    <environments default="test">
        <environment id="test">
<!--            事物-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="yxs1112003"/>
            </dataSource>
        </environment>
    </environments>

<!--    <mapper resource="com.atguigu.mapper.UserMapper.xml"/>错误-->
    <mappers>
        <mapper resource="com/atguigu/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

4、编写MyBatis工具类

package com.atguigu.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.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession连接
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}

5、普通java类

com/atguigu/pojo/User.java

package com.atguigu.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {

    private int id;  //id
    private String name;   //姓名
    private String pwd;   //密码


}

6、mapper数据接口

com.atguigu.mapper.java

package com.atguigu.mapper;

import com.atguigu.pojo.User;

import java.util.List;

public interface UserMapper {
    //查询全部用户
    List<User> selectUser();
    //根据id查询用户
    User selectUserById(int id);
}

7、mapper数据接口配置文件

com/atguigu/mapper/UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--由原来的实现类转化为一个mapper配置文件-->
<!--        resultType 结果集 写泛型中的类型-->

<mapper namespace="com.atguigu.mapper.UserMapper">
    <select id="selectUser" resultType="com.atguigu.pojo.User">
        select * from user
    </select>
</mapper>

8、Junit4测试类

package com.atguigu.mapper;

import com.atguigu.pojo.User;
import com.atguigu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }

}

结果:

Mybatis

练习Mybatis

1、创建数据库、导入数据

CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

2、pom文件

<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/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.atguigu</groupId>
  <artifactId>MybatisPrac</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>MybatisPrac</name>

  <dependencies>
<!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.28</version>
    </dependency>

<!--    pojo-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok-maven-plugin</artifactId>
      <version>1.18.12.0</version>
      <scope>provided</scope>
    </dependency>


    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.11</version>
    </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.13</version>
          <scope>test</scope>
      </dependency>


  </dependencies>


    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

3、mybatis核心配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">

<!--mybatis核心配置文件-->
<configuration>
    <environments default="test">
        <environment id="test">
<!--            事物-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="yxs1112003"/>
            </dataSource>
        </environment>
    </environments>

<!--    <mapper resource="com.atguigu.mapper.UserMapper.xml"/>错误-->
    <mappers>
        <mapper resource="com/atguigu/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

4、编写MyBatis工具类

package com.atguigu.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.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession连接
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}

5、普通java类

com/atguigu/pojo/User.java

package com.atguigu.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {

    private int id;  //id
    private String name;   //姓名
    private String pwd;   //密码


}

6、mapper数据接口

com.atguigu.mapper.java

package com.atguigu.mapper;

import com.atguigu.pojo.User;

import java.util.List;

public interface UserMapper {
    //查询全部用户
    List<User> selectUser();
    //根据id查询用户
    User selectUserById(int id);
}

7、mapper数据接口配置文件

com/atguigu/mapper/UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--由原来的实现类转化为一个mapper配置文件-->
<!--        resultType 结果集 写泛型中的类型-->

<mapper namespace="com.atguigu.mapper.UserMapper">
    <select id="selectUser" resultType="com.atguigu.pojo.User">
        select * from user
    </select>
</mapper>

8、Junit4测试类

package com.atguigu.mapper;

import com.atguigu.pojo.User;
import com.atguigu.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {

    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectUser();
        for (User user : userList) {
            System.out.println(user);
        }
    }

}

结果:

测试结果

标签:mapper,java,atguigu,org,mybatis,import,com
From: https://www.cnblogs.com/Kaelthas/p/17088683.html

相关文章

  • MyBatis的使用三(在sql语句中传值)
    本文主要介绍在mybatis中如何在sql语句中传递参数一.#{}和${}1.#{}和${}的区别#{}是预编译处理==>PreparedStatement${}是字符串替换==>S......
  • 细节决定成败:探究Mybatis中javaType和ofType的区别
    开启掘金成长之旅!这是我参与「掘金日新计划·12月更文挑战」的第24天,点击查看活动详情一.背景描述今天,壹哥给学生讲解了Mybatis框架,学习了基础的ORM框架操作及多对一......
  • mybatis-plus代码生成器
    用idea建一个javaproject项目,然后在pom.xml中加入以下依赖<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifac......
  • 使用tk.mybatis.mapper中的insertSelective返回实体类主键 注解配置
    @ApiModelProperty(value="知识树ID组织ID")@Id@Column(name="`keynote_id`")@GeneratedValue(strategy=GenerationType.IDENTITY,generator="JDBC")priv......
  • mybatis在代码中自定义sql
           ......
  • MyBatis框架的使用
    本文主要讲述如何快速使用mybatis一.MyBatis的下载MyBatis框架下载网站:Releases·mybatis/mybatis-3(github.com)下载好之后,文件目录如下:打开mybatis......
  • MybatisPlus批量插入探索
    MybatisPlus批量插入探索 最近在最近开发过程中遇到一个问题,在项目智慧物联网的大背景下,通常需要由多个传感器和监测设备向服务器请求,原设定是每次从mq中拉取1000数据批......
  • Mybatis-Plus的应用场景及注入SQL原理分析
    一、背景1.1传统Mybatis的弊端1.1.1场景描述假设有两张表:一张商品表、一张订单表,具体表的字段如下: 现有如下需求:分别根据id查询商品表和订单表所有信息根......
  • MyBatis和MyBatis-Plus代码生成
    MyBatis代码生成1.在pom中添加依赖<plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artif......
  • Mybatis Plus分页插件
    MybatisPlus分页插件@ConfigurationpublicclassMybatisPlusConfig{@BeanpublicMybatisPlusInterceptormybatisPlusInterceptor(){MybatisPlu......