Mybatis配置的一些注意事项

一、Mybatis:半自动化ORM框架

  1. 通过手写编写SQL语言
  2. 通过自动参数动态映射

二、Mybatis配置

1. 依赖jar包
mysql driver
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
mybatis
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
2. 核心配置

     ① datasource.properties(虚拟机IP,数据库,用户名,密码自己设置)

	mysql.driver=com.mysql.jdbc.Driver
	mysql.url=jdbc:mysql://192.168.56.200:3306/school?useUnicode=true&
	characterEncoding=utf-8&useSSL=true
	mysql.username=root
	mysql.password=5678

     ② mybatis.xml

(mbconf)
<?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>

</configuration>

     ③ mapper

(mbmapper)
<?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>

</mapper>

为了使之后的使用更加便捷(只需在文件中打出别名后enter即可出现所需的代码),可以将上方的核心配置添加进idea中。
方法如下:关闭工程点击右下方configuration–>settings–>live–>live Templates–>user配置下面两个方法(首次配置可能找不到user,可以在点击完settings后直接点击右方加号,此时会出现user,然后在user下进行如图所示配置)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
mybatis.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="datasource.properties"/>
    <typeAliases>
        <package name="cn.kgc.kb08.entity"/>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="cn.kgc.kb08.mapper"/>
    </mappers>
</configuration>
<?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="cn.kgc.kb08.mapper.VStuScoreMapper">

</mapper>

     ④ Mybatis核心对象

1)配置文件解析
	InputStream config = Resources.getResourceAsStream(String path);
	Resources(org.apache.ibatis.io)
2)SQL会话工厂
	SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
3)SQL会话	open(true:自动提交/false:不自动提交(启动事务))
4)获取Mapper接口对象
	XxxMapper mapper = session.getMapper(XxxMapper.class);
调用接口对象方法,返回返回结果

如下图所示:
在这里插入图片描述

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页