JAVAWEB--Mybatis02

news/2024/6/18 21:57:07 标签: java, 开发语言, 后端, tomcat, spring boot, mysql, mybatis

Maven项目导入依赖

<?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>cn.ronghuanet</groupId>
    <artifactId>mybatis-day02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
    	<!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.1</version>
        </dependency>
        <!-- mysql驱动包 -->
        <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.26</version>
         </dependency>
         <!-- junit测试包 -->
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.12</version>
             <scope>test</scope>
         </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
  </dependencies>
    <!-- 局部jdk 1.8配置,pom.xml中 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Mybatis集成

Mybatis配置文件

logo4j.properties

#\u5168\u5C40\u65E5\u5FD7\u914D\u7F6E
log4j.rootLogger = info,console

#log level: 
#debug is used by develop,  error or warn is used by online
log4j.logger.com.ronghuanet=debug


### \u914D\u7F6E\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.appender.console = org.apache.log4j.ConsoleAppender
### \u4F7F\u7528System.out\u6253\u5370\u65E5\u5FD7
log4j.appender.console.Target = System.out
### \u6307\u5B9A\u65E5\u5FD7\u7684\u683C\u5F0F\u5E03\u5C40(\u65E5\u5FD7\u662F\u6709\u683C\u5F0F\u7684)
log4j.appender.console.layout = org.apache.log4j.PatternLayout
### \u65E5\u5FD7\u7684\u6253\u5370\u683C\u5F0F
log4j.appender.console.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n

jdbcproperties

jdbc.username=root
jdbc.password=admin
jdbc.url=jdbc:mysql:///mybatis
jdbc.driverClassName=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>
   <!-- 加载jdbc.properties-->
    <properties resource="jdbc.properties"/>
    <!--申明操作数据库的环境-->
    <environments default="MYSQL">
        <environment id="MYSQL">
            <!--使用jdbc的事务-->
            <transactionManager type="JDBC"/>
            <!--支持连接池-->
            <dataSource type="POOLED">
                <!--自动补全结构:ctrl+shift+回车-->
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="driver" value="${jdbc.driverClassName}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
       <!-- 加载mapper.xml文件-->
    </mappers>
</configuration>

创建Mybatis工具类并测试

java">public class MybatisUtils {
    private static SqlSessionFactory sessionFactory ;
    static{
        try {
            //提示处理异常快捷键    alt+回车       移动代码的快捷键  alt+上键或者下键
            //快速使用变量接收,    alt+回车
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //根据io流创建SqlSessionFactory对象
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession openSession(){
        if (sessionFactory != null) {
            return sessionFactory.openSession();
        }
        return null;
    }
}

测试代码

java">public class MybatisTest {

    @Test
    public void test() throws Exception{
        SqlSession sqlSession = MybatisUtils.openSession();
        System.out.println(sqlSession);
        MybatisUtils.closeSession(sqlSession);

    }
}

创建模型

java">public class Product {
    private Long id;
    private String name;
    private BigDecimal price;
    /**
     * alt+insert:快速生成setter  getter方法  toString方法   构造方法
     */
	//getter,setter代码略...
}

productMapper接口

java">public interface ProductMapper {
    Product findOne(Long id);
}

创建对应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">
<!--注:namespace的内容就是ProductMapper接口的全限定名-->
<mapper namespace="org.test..mybatis._01_batch.mapper.ProductMapper">
    <!--id的值保证ProductMapper接口的方法名一值-->
    <select id="findOne" parameterType="long" resultType="org.test.mybatis._01_batch.domain.Product">
        select * from product where id = #{id}
    </select>
</mapper>

注册mapper.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>
     ...
    <mappers>
       <!-- 加载mapper.xml文件-->
        <mapper resource="org/test/mybatis/_01_batch/mapper/ProductMapper.xml" />
    </mappers>
</configuration>

获取单个对象

java">public class MyBatisTest {
    /**
     * 定义一个映射器mapper接口,使用mybatis自动为我们创建代理类
     * @throws Exception
     */
    @Test
    public void findOne()throws Exception{
        //获取到会话对象
        SqlSession session = MybatisUtils.openSession();
        //拿到映射对象,可以做相应的操作
        ProductMapper mapper = session.getMapper(ProductMapper.class);
        Product product = mapper.findOne(1L);

        System.out.println(product);
    }
}

本篇主要写了IDEA如何集成Mybatis,后续还会介绍mybatis映射等知识。笔者小,中,大厂均有面试经历,坚持每日分享java全栈知识,希望和大家共同进步。


http://www.niftyadmin.cn/n/5520550.html

相关文章

IDEA:配置Golang的开发环境及异常

1、下载&安装 进入GO的官网下载对应的GO 我们可以下载安装版&#xff0c;不过本人习惯下载解压版&#xff0c;这个因个人而异 2、配置环境变量 GOBIN : %GOROOT%\bin GOPATH : D:\MyGo 工作区间 GOROOT : D:\Program Files\Go GOJDK地址PATH: %GOBIN% ; %GOROOT%\bin ; …

phpStudy里面的MySQL启动不了

C:\Users\Administrator>netstat -an | find "3306" TCP 0.0.0.0:3306 0.0.0.0:0 LISTENING TCP 0.0.0.0:33060 0.0.0.0:0 LISTENING TCP [::]:3306 [::]:0 LISTENING TCP [::]:33060 [::]:0 LISTENING 从你提供的输出结果可以看到&#xff0c;端口3306和33060已经…

PostgreSQL 快速入门与实战

1、概述 前面2篇博客给大家详细的介绍了PostgreSQL的安装和配置&#xff0c;本篇文章就带着大家一起学习一下PostgreSQL的用法&#xff0c;主要内容包括 基本的数据库操作、用户管理、数据备份、SCHEMA(模式)以及和MySQL的区别。 2、数据库基本操作 PostgreSQL是严格遵守SQL规…

[数据集][目标检测]足球场足球运动员身份识别足球裁判员数据集VOC+YOLO格式312张4类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;312 标注数量(xml文件个数)&#xff1a;312 标注数量(txt文件个数)&#xff1a;312 标注类别…

有状态服务和无状态服务

有状态服务和无状态服务在不同的业务场景下有不同的应用&#xff0c;以下是一些常见的例子&#xff1a; 有状态服务的场景&#xff1a; 用户会话管理&#xff1a; 用户登录后&#xff0c;会话信息&#xff08;如用户ID、权限、购物车内容等&#xff09;需要在服务端保持状态。…

5.数据仓库与数据挖掘期末复习

ETL的含义Extract 、 Transformation、Load。ODS的全称Operational Data Store。 DW全称 Data WarehourseDM全称是Data Mart数据仓库数据抽取时所用到技术是增量、全量、定时、调度STAGE层作用是提供业务系统数据文件的临时存储ODS层作用ods提供业务系统细节数据长期沉淀MID层…

框架学习之spring学习笔记(一)

一、框架前言 1-什么是spring框架&#xff0c;有哪些主要模块&#xff1f; Spring 框架是一个专门针对于 Java 应用程序开发&#xff0c;并提供了综合、广泛的基础性支持的轻量级框架。Spring框架使用目的是为了提高开发人员的开发效率以及系统的可维护性。 Spring 是以IoC和A…

Solr 日志系统7.4.0部署和迁移到本地,Core Admin 添加新的core报错

文章目录 Solr部署Docker部署二进制部署 Tips:Solr设置账号密码方法1&#xff1a;(不使用)方法2&#xff1a; Core Admin 添加新的core报错Solr数据迁移 Solr部署 Docker部署 docker run -d -p 8983:8983 --name solr solr:latest docker run -d -p 8983:8983 -v /opt/solr:/…