MyBatis
MyBatis-Generator
新键工程并在lib下加入相关jar包并buildPath
mybatis-3.4.6.jar
mybatis-generator-core-1.3.7.jar
mysql-connector-java-8.0.16.jar
在src下创建相应配置文件
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
jdbc.username=login
jdbc.password=123
generatorConfig.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>
<!-- 配置数据库连接的包 项目下面已经有连接包了 -->
<!-- <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> -->
<!--引入配置文件 -->
<properties resource="db.properties" />
<context id="MyGererator" targetRuntime="MyBatis3">
<!-- 这个标签可以去掉注释 -->
<commentGenerator>
<!-- 去掉注释 -->
<property name="suppressAllComments" value="true" />
<!-- 去掉时间戳 -->
<property name="suppressDate" value="true" />
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}">
</jdbcConnection>
<!-- JAVA JDBC数据类型转换 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator javaBean配置
targetPackage 输入包名 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.sikiedu.bean" targetProject="src">
<!-- enableSubPackages 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set中加入.trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- mapper.xml -->
<sqlMapGenerator targetPackage="com.sikiedu.mapper" targetProject="src">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- java接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.sikiedu.mapper" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 数据表 要根据数据库中的表来生成 -->
<table tableName="user" />
<table tableName="country" />
</context>
</generatorConfiguration>
创建com.sikiedu.test下的Generator.java
package com.sikiedu.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class Generator {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
运行Generator
按F5刷新工程目录,工程下就会出现相应的com.sikiedu.bean包和com.sikiedu.mapper包以及下面的配置文件
MyBatis与spring的整合开发
新建工程ssm_mybatis_spring并配置相关文件
导入相关jar包并buildPath
c3p0数据源和mysql连接包
c3p0-0.9.5.5.jar
mchange-commons-java-0.2.19.jar
mysql-connector-java-8.0.16.jar
spring相关jar包
spring-aop-5.0.8.RELEASE.jar
spring-aspects-5.0.8.RELEASE.jar
spring-beans-5.0.8.RELEASE.jar
spring-context-5.0.8.RELEASE.jar
spring-context-support-5.0.8.RELEASE.jar
spring-core-5.0.8.RELEASE.jar
spring-expression-5.0.8.RELEASE.jar
spring-jdbc-5.0.8.RELEASE.jar
spring-jms-5.0.8.RELEASE.jar
spring-messaging-5.0.8.RELEASE.jar
spring-tx-5.0.8.RELEASE.jar
spring-web-5.0.8.RELEASE.jar
spring-webmvc-5.0.8.RELEASE.jar
mybatis与spring连接的包和核心包
com.springsource.javax.servlet.jsp.jstl-1.1.2.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
mybatis-3.4.6.jar
mybatis-spring-1.3.2.jar
在src下创建相关配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
<!-- 读取db.properties -->
<context:property-placeholder location="db.properties"/>
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置mybatis sqlSessionFactory -->
<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- -->
<property name="dataSource" ref="dataSource"/>
<!-- 钙塑spring mybatis的核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
</beans>
db.properties
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
jdbc.user=login
jdbc.password=123
log4j.properties(打印)
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
sqlMapConfig.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="db.properties" />
<typeAliases>
<!-- 使用别名<typeAlias type="com.sikiedu.bean.User" alias="user"/> -->
<!-- 使用package包的形式配置别名 包的形式会扫描主包及子包下的所有文件 以对象名为别名,大小写不限,推荐使用小写 -->
<package name="com.sikiedu.bean" />
</typeAliases>
</configuration>
Dao式开发
在src下创建com.sikiedu.bean包,包下有User.java
package com.sikiedu.bean;
import java.util.Date;
public class User {
private Integer u_id;
private String u_username;
private String u_password;
private String u_sex;
private Date u_createTime;
private Integer u_cid;
/*此处为各个属性的get和set方法 以及空参 有参构造器 toString()方法*/
}
创建com.sikiedu.dao包
创建UserDao.java接口
package com.sikiedu.dao;
import com.sikiedu.bean.User;
public interface UserDao {
//根据id 查询用户
public User getUserById(Integer id);
}
创建实现类UserDaoImpl.java
package com.sikiedu.dao;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.sikiedu.bean.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public User getUserById(Integer id){
SqlSession session=getSqlSession();
//操作数据库
return session.selectOne("UserMapper.selectUserById", id);
}
}
创建com.sikiedu.mapper
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="UserMapper">
<select id="selectUserById" parameterType="Integer" resultType="user">
select * from user where u_id =#{id}
</select>
</mapper>
在applicationContext.xml进行配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
<!-- 读取db.properties -->
<context:property-placeholder location="db.properties"/>
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置mybatis sqlSessionFactory -->
<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- -->
<property name="dataSource" ref="dataSource"/>
<!-- 钙塑spring mybatis的核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<bean id="userDaoImpl" class="com.sikiedu.dao.UserDaoImpl">
<!-- 将工厂注入到Dao的父类 SqlSessionFactory -->
<property name="SqlSessionFactory" ref="SqlSessionFactoryBean"></property>
</bean>
</beans>
在sqlMapConfig.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="db.properties" />
<typeAliases>
<!-- 使用别名<typeAlias type="com.sikiedu.bean.User" alias="user"/> -->
<!-- 使用package包的形式配置别名 包的形式会扫描主包及子包下的所有文件 以对象名为别名,大小写不限,推荐使用小写 -->
<package name="com.sikiedu.bean" />
</typeAliases>
<mappers>
<mapper resource="com/sikiedu/mapper/UserMapper.xml"/>
</mappers>
</configuration>
在测试包com.sikiedu.test下的UserDaoTest.java中测试
package com.sikiedu.test;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sikiedu.bean.User;
import com.sikiedu.dao.UserDaoImpl;
public class UserDaoTest {
@Test
public void DaoTest() {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
UserDaoImpl userDao = ac.getBean(UserDaoImpl.class);
User user = userDao.getUserById(1);
System.out.println(user);
}
}
输出数据
User [u_id=1, u_username=隔壁老王, u_password=aaa, u_sex=3, u_createTime=null, u_cid=1]
Mapper动态代理开发
在com.sikiedu.mapper下创建接口UserMapper.java
package com.sikiedu.mapper;
import com.sikiedu.bean.User;
public interface UserMapper {
public User selectUserById(Integer id);
}
修改UserMapper.xml的mapper的namespace
<?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.sikiedu.mapper.UserMapper">
<select id="selectUserById" parameterType="Integer" resultType="user">
select * from user where u_id =#{id}
</select>
</mapper>
修改sqlMapConfig.xml中的mappers标签注入方式
<?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="db.properties" />
<typeAliases>
<!-- 使用别名<typeAlias type="com.sikiedu.bean.User" alias="user"/> -->
<!-- 使用package包的形式配置别名 包的形式会扫描主包及子包下的所有文件 以对象名为别名,大小写不限,推荐使用小写 -->
<package name="com.sikiedu.bean" />
</typeAliases>
<mappers>
<!-- <mapper resource="com/sikiedu/mapper/UserMapper.xml"/> -->
<package name="com.sikiedu.mapper"/>
</mappers>
</configuration>
在applicationContext.xml配置mapper动态代理开发
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
<!-- 读取db.properties -->
<context:property-placeholder location="db.properties"/>
<!-- 配置c3p0连接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置mybatis sqlSessionFactory -->
<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- -->
<property name="dataSource" ref="dataSource"/>
<!-- 钙塑spring mybatis的核心配置文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<bean id="userDaoImpl" class="com.sikiedu.dao.UserDaoImpl">
<!-- 将工厂注入到Dao的父类 SqlSessionFactory -->
<property name="SqlSessionFactory" ref="SqlSessionFactoryBean"/>
</bean>
<!-- mapper动态代理开发 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 注入sqlSessionFactory -->
<property name="SqlSessionFactory" ref="SqlSessionFactoryBean"/>
<!-- 配置接口 -->
<property name="mapperInterface" value="com.sikiedu.mapper.UserMapper"/>
</bean>
</beans>
在com.sikiedu.test下新建测试类MapperTest.java
package com.sikiedu.test;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sikiedu.bean.User;
import com.sikiedu.mapper.UserMapper;
public class MapperTest {
@Test
public void Test1() {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//这两个方法都可以
// UserMapper mapper = (UserMapper) ac.getBean("userMapper");
UserMapper mapper = ac.getBean(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user);
}
}
测试数据
User [u_id=1, u_username=隔壁老王, u_password=aaa, u_sex=3, u_createTime=null, u_cid=1]
Mapper动态扫描开发–推荐使用
在applicationContext.xml添加Mapper动态扫描开发的bean
<!-- Mapper动态扫描开发 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sikiedu.mapper"/>
</bean>
在MapperTest.java中添加测试方法测试
//Mapper动态扫描开发
@Test
public void Test2() {
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//对于Mapper动态扫描开发来说 获取bean的id形式就不行了
// UserMapper mapper = (UserMapper) ac.getBean("userMapper");
UserMapper mapper = ac.getBean(UserMapper.class);
User user = mapper.selectUserById(19);
System.out.println(user);
}
测试数据
User [u_id=19, u_username=岛风, u_password=123, u_sex=0, u_createTime=Sun Jun 21 20:21:02 CST 2020, u_cid=1]
MyBatis总结
MyBatis是一个轻量级简化数据库操作的框架
1.为什么要使用MyBatis
为了解决JDBC存在的问题和简化数据库操作,MyBatis提供了较为优秀的解决方案;
例如:
1、 可以通过主配置文件配置连接池解决频繁创建、释放数据库连接造成的性能影响;
2、 动态SQL解决JDBC中硬编码问题:
a) Where条件改变;
b) 占位符位置变化;
3、 可通过包装类方便的获取数据库查询结果集对象;
4、 使Dao层业务逻辑和数据库访问分离更易维护和测试。
2.使用MyBatis对表进行增、删、改、查操作
1、 通过ID去查询一个用户
2、 通过用户名模糊查找匹配的用户列表
3、 完成添加用户
4、 修改用户
5、 根据id删除用户
6、 使用MyBatis 开发Dao层并测试;
7、小结1:Jdbc与MyBatis开发的区别(MyBatis的优点),回顾MyBatis开发流程
3.MyBatis Mapper动态代理开发4+1 (4原则+1注意):
1、 接口方法名需要与mapper.xml的要调用的sql语句的id一致;
2、 接口的形参类型需要与mapper.xml parameterType一致;
3、 接口的返回值需要与mapper.xml resultType一致;
4、 mapper.xml中namespace要与接口的全包名一致;
5、 注意mapper动态代理开发中,根据返回值类型来自动选择;
4.MyBatis 主配置文件SqlMapConfig.xml说明:(注意顺序)
1、 properties(读取配置文件)
2、 settings(全局配置参数)
3、 typeAliases(类型别名)
4、 typeHandlers(类型处理器)
5、 objectFactory(对象工厂)
6、 plugins(插件)
7、 environments(环境集合属性对象,与Spring框架整合后Say Good Bye)
a) environment(环境子属性对象)
b) transactionManager(事务管理)
c) dataSource(数据源)
8、 mappers(配置映射器位置)
5.MyBatis输入和输出映射
1、 输入映射parameterType;
a) 基本类型;
b) 自定义对象;
c) 自定义包装类;
2、 输出映射resultType、resultMap;
a) resultType:
i. 基本类型;
ii. 自定义对象;
iii. 集合;
b) resultMap;
i. bean对象字段与数据表字段不匹配;
ii. 自定义包装类;
iii. 关联查询
6.MyBatis关联查询
1、 一对一;2、一对多
7.MyBatis动态sql:更方便的拼接sql语句
1、 if标签 - 多条件查询,获取用户列表;
2、 where标签 - 解决if标签拼接字符串AND符号问题;
3、 trim标签 - 定制where标签的规则
4、 set标签 - 解决更新数据表时字符串拼接逗号”,”问题;
5、 foreach标签 – 如果需要使用IN查询多条相同数据,可以使用foreach遍历;
6、 sql标签 – 可以提取重复sql语句片段
8.MyBatis Generator(MBG):
作用:根据数据库表自动生成Bean对象、Java接口及SqlMapper.xml配置文件;
官方文档:http://www.mybatis.org/generator/
下载地址:https://github.com/mybatis/generator/releases
1、 搭建MBG项目;
a) 下载MBG核心包;
b) 创建java项目;
c) 从官方文档获取配置表、实例代码;
d) 导入依赖包;
2、 MBG配置以及根据数据库表生成所需文件(Bean、Interface、Mapper.xml);
3、 使用自动生成的文件操作数据库;
9.MyBatis + Spring整合开发
目的:
a) 使用Spring容器用单例模式管理Mybatis的sqlSessionFactory;
b) 使用Spring管理连接池、数据源等;
c) 将Dao/Mapper动态代理对象注入到Spring容器中,使用时直接获取;