Mybatis
添加依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
select标签的定义
<?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="dao.BookDao">
<!-- select 表示查询操作,id:要执行的sql语句的唯一标识,是一个自定义的字符串推荐使用dao接口的方法名称
resultType:告诉mybatis,执行的sql语句把数据赋值给那个类型的java对象
使用java对象的全限定名称-->
<select id="selectStudentById" resultType="service.Student">
select * from Student where id=1001
</select>
</mapper>
<!--
1.约束文件
http://mybatis.org/dtd/mybatis-3-mapper.dtd
约束文件作用:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
2.mapper是根标签
namespace:命名空间,必须有值,不能为空,唯一值
推荐使用Dao接口的全限定名称.
作用:参与识别sql语句的作用
3.在mapper里面可以写<insert>,<update>等标签
<insert>里面是insert语句
-->
Mybatis主配置文件
<?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/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 使用 / 分割路径
一个mapper source指定一个mapper文件-->
<mapper resource="Student.xml"/>
</mappers>
</configuration>
创建Mybatis核心类SqlSessionFactory
public void testSelectStudentById() throws IOException {
//调用mybatis某个对象的方法,执行
//mybatis核心类:sqlSessionFactory
//1.定义mybatis主配置文件的相对路径
String config= "mybatis.xml";
//2.读取主配置文件
InputStream inputStream= Resources.getResourceAsStream(config);
//3.创建sqlSessionFactory对象,使用sqlSessionFactoryBuilder类
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//4.获取sqlSession对象
SqlSession session=factory.openSession();//true自动提交
//5.指定要执行的sql语句的 id
// sql的id=namespace +"."+<select>|update|insert| 标签的id属性值
String sqlId="dao.BookDao"+"."+"selectStudentById";
//6.通过sqlSession的方法,执行sql语句
Student student=session.selectOne(sqlId);
System.out.println(student);
session.close();
}
util
public class MybatisUtil {
private static SqlSessionFactory factory=null;
static {
String config="mybatis.xml";
try {
InputStream inputStream=Resources.getResourceAsStream(config);
factory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
SqlSession sqlSession=null;
if(factory!=null){
sqlSession = factory.openSession();//openSession(true)
}
return sqlSession;
}
}
dao代理
要求
mapper文件中的namespace必须是dao接口的全限定名称
mapper文件中标签的id是dao接口中的方法名称一模一样
实现
使用SQLsession对象方法getMapper(dao.class)
例如 现有studentDao接口
SqlSession sqlSession = MybatisUtil.getSqlSession();
studentDao dao = session.getMapper(Studentdao.class);
Student student = dao.selectById(1001);
//以上等同
studentDao dao = session.getMapper(Studentdao.class);
等同于
studentDao dao = new studentDaoImpl();
逆向工程
依赖插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
<resources>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
generatorConfig.xml文件
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--导入属性配置-->
<properties resource="jdbc.properties"></properties>
<!--指定特定数据库的jdbc驱动jar包的位置-->
<classPathEntry location="${my.driverLocation}"/>
<context id="default" targetRuntime="MyBatis3">
<!-- optional,旨在创建class时,对注释进行控制 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--jdbc的数据库连接 -->
<jdbcConnection
driverClass="${my.driverClass}"
connectionURL="${my.url}"
userId="${my.userName}"
password="${my.password}">
<!--MySQL 不支持 schema 或者 catalog 所以需要添加这个-->
<!-- 不然会出现生成器把其他数据库的同名表生成下来的问题 -->
<!-- 现象就是某个类中出现了数据库表里面没有的字段 -->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径
-->
<javaModelGenerator targetPackage="wjh.beans"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="wjh.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<javaClientGenerator targetPackage="wjh.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--要执行逆向工程所用到的表-->
<table tableName="usercar" domainObjectName="Usercar"/>
<table tableName="student"/>
</context>
</generatorConfiguration>
“XMLMAPPER”>
<!--要执行逆向工程所用到的表-->
<table tableName="usercar" domainObjectName="Usercar"/>
<table tableName="student"/>
</context>
```