What is Mybatis? Mybatis entry program

1. What is the framework?

1. Java common framework:   
        SSM three major frameworks: Spring+Mybatis+SpringMvc

2. What is a frame?
        The framework itself is the encapsulation of common code, pre-written classes and methods, we directly introduce these frameworks (in essence, introducing classes and interfaces) when working on projects, and simplify our development based on these frameworks. Frameworks generally exist in the form of jar packages.

3. MVC three-tier architecture
        here refers to a picture of the power node

 

Presentation layer: It directly deals with the front end, on the one hand, it receives ajax requests, and on the other hand, it returns json data to the front end.
Business logic layer: On the one hand, it processes the requests forwarded by the presentation layer, and on the other hand, it returns the data processed by the persistence layer to the presentation layer.
Persistence layer: It deals directly with the database, completes crud operations, and returns data to the business logic layer.
Our mybatis belongs to the Java persistence layer framework.

2. What are the shortcomings of JDBC/Why use Mybatis instead of JDBC in development?

1. The sql statement is hard-coded in the Java program. Modifying the sql file requires modifying the java file, which obviously violates the principle of opening and closing.
2. Give placeholders? The value passing operation is cumbersome, and Mybatis can help us automatically pass the value
3. JDBC encapsulates the query result set into a Java object is cumbersome, and Mybatis helps us automatically encapsulate the result set into an object.

3. The essence of Mybatis?

1. It can be understood that Mybatis is an upgraded version of JDBC. It is essentially an encapsulation of JDBC, so that developers only need to pay attention to SQL statements instead of JDBC codes, making development easier.

2. MyBatis configures various Statement objects to be executed through XML or annotations, maps Java objects and dynamic parameters of SQL in the statement, and finally executes the SQL statement. After executing the SQL, the result is finally returned as a Java object.

3. The idea of ​​half ORM is adopted. hibernate complete ORM thinking

4. Mybatis entry program

1. Create database and table structure

create database mybatis_demo;
use mybatis_demo;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` datetime default NULL COMMENT '生日',
`sex` char(1) default NULL COMMENT '性别',
`address` varchar(256) default NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (1,'老王','2018-02-27
17:47:08','男','北京'),(2,'熊大','2018-03-02 15:09:37','女','上海'),(3,'熊二','2018-03-04
11:34:34','女','深圳'),(4,'光头强','2018-03-04 12:04:06','男','广州');

2. Create a Maven project and create a java project.

3. Introduce coordinates

        3.1 Import the jar package of Mybatis 
        3.2 Import the jar package driven by MySQL
        3.3 Import the jar package of Junit unit test
        3.4 Import the jar package of log4j

<dependencies>
<!--mybatis核心包--> 
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

4. Create a new mybatis-config.xml under resources. This is the core configuration file of mybatis.
        The name of mybatis-config.xml is not required, but it is best to follow the specification.
        Created here in the ressources directory, indicating that mybatis-config.xml is under the root path of the class.

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/powernode"/>
                <property name="username" value="root"/>
                <property name="password" value="2020"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--sql映射文件创建好之后,需要将该文件路径配置到这里-->
        <mapper resource=""/>
    </mappers>
</configuration>

5. Create a new CarMapper.xml file under ressources, write our sql statement here,
        you can not write ";" at the end of the sql statement, 
        and CarMapper.xml is not fixed.

<?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先随意写一个-->
<mapper namespace="car">
    <!--insert sql:保存一个汽车信息-->
    <insert id="insertCar">
        insert into t_car
            (id,car_num,brand,guide_price,produce_time,car_type) 
        values
            (null,'102','丰田mirai',40.30,'2014-10-05','氢能源')
    </insert>
</mapper>

6. Configure the CarMapper.xml file path to the mybatis-config.xml file
        <mapper resource="CarMapper.xml"/>

7. Write test files
 

public class MyBatisIntroductionTest {
    public static void main(String[] args) {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 2. 创建SqlSessionFactory对象
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        // 3. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 4. 执行sql
        int count = sqlSession.insert("insertCar"); // 这个"insertCar"必须是sql的id
        System.out.println("插入几条数据:" + count);
        // 5. 提交(mybatis默认采用的事务管理器是JDBC,默认是不提交的,需要手动提交。)
        sqlSession.commit();
        // 6. 关闭资源(只关闭是不会提交的)
        sqlSession.close();
    }
}

just run

Guess you like

Origin blog.csdn.net/weixin_53818758/article/details/130376026