SpringBoot+Mybatis

第一种方式:使用XML构建SqlSessionFactory(工作中常见)

1:构建POJO

public class User {

    private int id;
    private String name;
    private int age;
    private String describe;
    private float height;

    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;
    }

    public String getDescribe() {
        return describe;
    }

    public void setDescribe(String describe) {
        this.describe = describe;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float hight) {
        this.height = hight;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", describe='" + describe + '\'' +
                ", hight=" + height +
                '}';
    }
}

2:创建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="com.itheima.springboot.springboot_mybatis.mapper.UserMapper">
    <resultMap id="UserResultMap" type="com.itheima.springboot.springboot_mybatis.domain.User">
        <id property="id" column="id" />
        <result property="name" column="name"/>
        <result property="age" column="age" />
        <result property="describe" column="desc" />
        <result property="height" column="height" />
    </resultMap>

    <select id="selectOneUser" parameterType="int" resultMap="UserResultMap">
        select id,name,age,`desc`,height from user where id = #{id}
    </select>
</mapper>

property="实体类对应的字段名"  column="数据库对应字段名"  `desc`是数据库关键字必须使用`desc`符号

3:mapper配置(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>

    <properties resource="mybatis/mybatis.properties"/>

    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>
        <typeAlias alias="MY_DB_VERSION" type="com.itheima.springboot.springboot_mybatis.mapping.MyVendorDatabaseIdProvider"/>
    </typeAliases>

    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver-class}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定数据库类型-->
    <databaseIdProvider type="MY_DB_VERSION">
        <property name="MySQL" value="mysql" />
    </databaseIdProvider>

    <mappers>
        <mapper resource="mybatis/mappers/UserMapper.xml" />
    </mappers>
</configuration>

4:配置数据库连接(mybatis.properties)

jdbc.driver-class = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/springBoot
jdbc.username = wql
jdbc.password = root123

5:在mapper中自定义数据库类型(MY_DB_VERSION)

在配置文件中添加如下:

<typeAliases>
        <typeAlias alias="MY_DB_VERSION" type="com.itheima.springboot.springboot_mybatis.mapping.MyVendorDatabaseIdProvider"/>
</typeAliases>

新建MyVendorDatabaseIdProvider类:
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
public class MyVendorDatabaseIdProvider extends VendorDatabaseIdProvider {

}

6:使用XML构建SqlSessionFactory

/**
* 使用XML构建SqlSessionFactory
*/
public class MyBatisAnnotationConfigurationDemo {

    public static void main(String[] args) throws Exception {

        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:/mybatis/mybatis-config.xml");
        EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
        Reader reader = encodedResource.getReader();

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(reader, "dev", new Properties());
        SqlSession sqlSession = sqlSessionFactory.openSession();

        User user = sqlSession.selectOne("com.itheima.springboot.springboot_mybatis.mapper.UserMapper.selectOneUser", 1);
        System.out.println(user);
        sqlSession.close();
    }
}

第二种方式:使用Generator插件生成

插件官网:http://www.mybatis.org/generator/

1:配置插件(pom.xml)

<plugin>
       <groupId>org.mybatis.generator</groupId>
       <artifactId>mybatis-generator-maven-plugin</artifactId>
       <version>1.3.7</version>
       <configuration>
            <configurationFile>${basedir}/src/main/resources/mybatis/mybatis-generator-config.xml</configurationFile>
       </configuration>
       <dependencies>
           <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.13</version>
                <scope>runtime</scope>
            </dependency>
       </dependencies>
</plugin>

2:Mybatis GeneratorXML配置(mybatis-generator-config.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <context id="user">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/springBoot" userId="wql" password="root123">
            <!--MySQL 8.x 需要指定服务器的时区-->
            <property name="serverTimezone" value="UTC"/>
            <!--MySQL 不支持 schema 或者 catalog 所以需要添加这个-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!-- Java 模型对象生辰器 -->
        <javaModelGenerator targetPackage="com.itheima.springboot.springboot_mybatis.domain2" targetProject="${user.dir}/src/main/java"/>

        <!-- SQL Mapper XML 生成器 -->
        <sqlMapGenerator  targetPackage="mybatis.mappers" targetProject="${user.dir}/src/main/resources"/>

        <!-- SQL Mapper Java 接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.itheima.springboot.springboot_mybatis.mapper" targetProject="${user.dir}/src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <table schema="springBoot" tableName="user" domainObjectName="User">
            <generatedKey column="id" sqlStatement="mysql" identity="true"/>
            <columnOverride column="name" property="name"/>
            <columnOverride column="age" property="age"/>
            <columnOverride column="desc" property="describe"/>
            <columnOverride column="height" property="height"/>
        </table>
    </context>
</generatorConfiguration>

3:运行Mybatis Generator

(1)mvn mybatis-generator:generate

(2)mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate

4:配置映射关系(mybatis-config.xml)

<mappers>
        <mapper resource="mybatis/mappers/UserMapper-1.xml" />
        <mapper resource="mybatis/mappers/UserMapper.xml" />
        <mapper class="com.itheima.springboot.springboot_mybatis.annotation.UserMapper" />
</mappers>

5:实例

public class MyBatisGeneratorConfigurationDemo {

    public static void main(String[] args) throws Exception {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("mybatis/mybatis-config.xml");
        Reader reader = new InputStreamReader(inputStream, "UTF-8");

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(reader, "dev", new Properties());
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(1);

        List<User> users = userMapper.selectByExample(userExample);
        User user = users.get(0);
        System.out.println(user);
        sqlSession.close();
    }
}

第三种方式:使用Annotation(注解)

1:创建UserMapper接口

import com.itheima.springboot.springboot_mybatis.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {

    @Results(value = {
            @Result(property = "id",column = "id",id = true),
            @Result(property = "name",column = "name"),
            @Result(property = "age",column = "age"),
            @Result(property = "describe",column = "desc"),
            @Result(property = "height",column = "height")
    })
    @Select(" select id,name,age,`desc`,height from user where id = #{id}")
    User selectUser(int id);
}

2:配置映射关系(mybatis-config.xml)

<mappers>
        <mapper resource="mybatis/mappers/UserMapper-1.xml" />
        <mapper resource="mybatis/mappers/UserMapper.xml" />
        <mapper class="com.itheima.springboot.springboot_mybatis.annotation.UserMapper" />
</mappers>

3:实例

import com.itheima.springboot.springboot_mybatis.annotation.UserMapper;
import com.itheima.springboot.springboot_mybatis.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

public class MyBatisAnnotationConfigurationDemo {

    public static void main(String[] args) throws Exception {

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("mybatis/mybatis-config.xml");
        Reader reader = new InputStreamReader(inputStream, "UTF-8");

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(reader, "dev", new Properties());
        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.selectUser(1);
        System.out.println(user);
        sqlSession.close();
    }
}

Controller层:

1:配置Application.properties;

mybatis.mapper-locations=mybatis/mappers/UserMapper-1.xml
mybatis.check-config-location=true

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springBoot
spring.datasource.username=wql
spring.datasource.password=root123

2:MybatisController

import com.itheima.springboot.springboot_mybatis.domain.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MybatisController {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @RequestMapping("user/{id}")
    public User user(@PathVariable int id){
        User user = sqlSessionTemplate.selectOne("com.itheima.springboot.springboot_mybatis.mapper.UserMapper.selectOneUser-1", id);
        return user;

    }
}

QQ交流群:519844688

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值