官方文档:https://mybatis.org/mybatis-3/zh/getting-started.html
视频:https://www.bilibili.com/video/BV1NE411Q7Nx?p=7
1、WMS_daopom.xml,要在哪个项目中使用就在哪个pom文件中加配置
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> <include>**/*.tld</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
2、添加mybatis核心配置文件WMS_daosrcmain esourcesmybatis-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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!-- 数据库驱动 --> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://192.168.2.39:3306/saasDb?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/jay/dao/SysUserMapper.xml"/> </mappers> </configuration>
3、WMS_daosrcmainjavacomjayutilsMybatisUtils类
package com.jay.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; //sqlSessionFactory>sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
4、编写实体类,和数据库表对应,实体类放在WMS_daosrcmainjavacomjaypojo中;
编写接口WMS_daosrcmainjavacomjaydaoSysUserMapper
package com.jay.dao; import com.jay.pojo.sys_user; import java.util.List; import java.util.Map; public interface SysUserMapper { sys_user selectUser(int id); List<sys_user> selectUserList(); List<sys_user> selectUserListByNickName(String name); void updateNickName(Map<String,Object> map); void addUser(Map<String,Object> map); void deleteUser(int id); }
5、编写实现WMS_daosrcmainjavacomjaydaoSysUserMapper.xml,xml中使用 mapper中的namespace指定映射的接口类。
mapper下节点类型select/update/insert/delete
这个xml文件需要在mybatis-config.xml中映射 mappers
<?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.jay.dao.SysUserMapper"> <!-- 只有一个参数可以直接写,参数名字需要和接口中的名字一致 --> <select id="selectUser" resultType="com.jay.pojo.sys_user"> select * from sys_user where user_id = #{id} </select> <!-- 返回类型如果是List泛型集合,resultType写泛型类型 --> <select id="selectUserList" resultType="com.jay.pojo.sys_user"> select * from sys_user </select> <select id="selectUserListByNickName" parameterType="string" resultType="com.jay.pojo.sys_user"> select * from sys_user where nick_name like #{name} </select> <!-- update语句中的参数name/id就是参数map中的key --> <update id="updateNickName" parameterType="map"> update sys_user set nick_name=#{nick_name} where user_id=#{user_id} </update> <insert id="addUser" parameterType="map"> insert into sys_user(user_name,nick_name)values(#{user_name},#{nick_name}) </insert> <delete id="deleteUser" parameterType="int"> delete from sys_user where user_id=#{id} </delete> </mapper>
测试
package com.jay; import static org.junit.Assert.assertTrue; import com.jay.dao.SysUserMapper; import com.jay.pojo.sys_user; import com.jay.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Unit test for simple App. */ public class AppTest { /** * Rigorous Test :-) */ @Test public void shouldAnswerWithTrue() { assertTrue(true); } @Test public void testSelectUser() { try(SqlSession session = MybatisUtils.getSqlSession()) { SysUserMapper userMapper = session.getMapper(SysUserMapper.class); sys_user sysu = userMapper.selectUser(1); System.out.println(sysu); } catch (Exception e) { e.printStackTrace(); } } @Test public void testSelectUserList() { try(SqlSession session = MybatisUtils.getSqlSession()) { SysUserMapper userMapper = session.getMapper(SysUserMapper.class); List<sys_user> sys_users = userMapper.selectUserList(); for (sys_user item :sys_users) { System.out.println(item); } } catch (Exception e) { e.printStackTrace(); } } @Test public void testSelectUserListByNickName() { try(SqlSession session = MybatisUtils.getSqlSession()) { SysUserMapper userMapper = session.getMapper(SysUserMapper.class); List<sys_user> sys_users = userMapper.selectUserListByNickName("%jay%"); System.out.println(sys_users); } catch (Exception e) { e.printStackTrace(); } } @Test public void testUpdateNickName() { try(SqlSession session = MybatisUtils.getSqlSession()) { SysUserMapper userMapper = session.getMapper(SysUserMapper.class); Map<String,Object> map = new HashMap<>(); map.put("user_id",1); map.put("nick_name","luna"); userMapper.updateNickName(map); session.commit();//增、删、改都需要commit()提交事务 } catch (Exception e) { e.printStackTrace(); } } @Test public void testAddUser() { try(SqlSession session = MybatisUtils.getSqlSession()) { SysUserMapper userMapper = session.getMapper(SysUserMapper.class); Map<String,Object> map = new HashMap<>(); map.put("user_name","jack"); map.put("nick_name","jack"); userMapper.addUser(map); session.commit();//增、删、改都需要commit()提交事务 } catch (Exception e) { e.printStackTrace(); } } @Test public void testDeleteUser() { try(SqlSession session = MybatisUtils.getSqlSession()) { SysUserMapper userMapper = session.getMapper(SysUserMapper.class); userMapper.deleteUser(5); session.commit();//增、删、改都需要commit()提交事务 } catch (Exception e) { e.printStackTrace(); } } }
6、mybatis-config.xml引入db.properties
WMS_daosrcmain
esourcesdb.properties
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://192.168.2.39:3306/testdb?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=root password=root
在mybatis-config.xml中加入配置properties,这个要放在configuration下,配置节是有顺序的settings。
<properties resource="db.properties" />
然后mybatis-config.xml中就可以修改为:参数名字要和db.properties中key一样。
<property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/>
也可以在<properties></properties>中间加入配置,如果key相同,优先使用db.properties中的配置。
<properties resource="db.properties"> <property name="username" value="admin"/> </properties>
类型别名,mybatis-config.xml加配置:
<typeAliases> <!-- 为实体类指定别名 --> <!--<typeAlias type="com.jay.pojo.sys_user" alias="SysUser"></typeAlias>--> <!-- 为com.jay包下的所有实体类指定默认别名,骆驼命名 SysUser=>sysUser --> <package name="com.jay"/> </typeAliases>
然后在SysUserMapper.xml中的resultType就不用写完全限定名,使用别名就好:resultType="SysUser"或者resultType="sys_user"
还可以在实体类上面使用注解别名:@Alias("sys_user")。如果返回的是基本数据类型,要在基本类型前加下划线resultType="_int"。
7、映射器mappers,在核心配置文件中mybatis-config.xml需要注册接口和实现xml的映射关系。
方式一,通过相对路径绑定Mapper(推荐)
<mappers> <mapper resource="com/jay/dao/SysUserMapper.xml"/> </mappers>
方式二,使用class文件绑定映射,注意:对应的Mapper文件必须要再同级目录下且名字要一样。
<mappers> <mapper class="com.jay.dao.SysUserMapper"></mapper> </mappers>
方式三,使用扫描包来绑定映射,注意:对应的Mapper文件必须要再同级目录下且名字要一样。
<mappers> <package name="com.jay.dao"/> </mappers>
生命周期和作用域,错误使用会导致严重的并发问题。<dataSource type="POOLED">
8、结果集映射,把resultType改成resultMap,新建一个resultMap配置,解决实体字段名称和sql返回字段不一致问题,只需要把不一样的字段配置好就行,一样的会自动映射。
参考:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps
<select id="selectBlogDetails" resultMap="detailedBlogResultMap">sql语句</select>
//autoMapping:如果设置这个属性,MyBatis 将会为本结果映射开启或者关闭自动映射。 这个属性会覆盖全局的属性 autoMappingBehavior。默认值:未设置(unset)。
<resultMap id="detailedBlogResultMap" type="Blog" autoMapping="unset">
<constructor>
<idArg column="blog_id" javaType="int"/>
</constructor>
<!-- property是Blog中的属性名称,column是sql查询的字段名 -->
<id property="id" column="user_id"/>
<result property="username" column="author_username"/>
<!-- Blog类包含Author类 -->
<association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
</association>
<!-- Blog类中包含posts属性,posts属性是List<Post>集合 -->
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
</collection>
<discriminator javaType="int" column="draft">
<case value="1" resultType="DraftPost"/>
</discriminator>
</resultMap>
结果映射(resultMap)
constructor - 用于在实例化类时,注入结果到构造方法中
idArg - ID 参数;标记出作为 ID 的结果可以帮助提高整体性能
arg - 将被注入到构造方法的一个普通结果
id – 一个 ID 结果;标记出作为 ID 的结果可以帮助提高整体性能
result – 注入到字段或 JavaBean 属性的普通结果
association – 一个复杂类型的关联;许多结果将包装成这种类型
嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
collection – 一个复杂类型的集合
嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用
discriminator – 使用结果值来决定使用哪个 resultMap
case – 基于某些值的结果映射
嵌套结果映射 – case 也是一个结果映射,因此具有相同的结构和元素;或者引用其它的结果映射
9、日志工厂:https://mybatis.org/mybatis-3/zh/logging.html
使用Log4j,mybatis-config.xml配置settings,不能拼错。
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
新建配置文件WMS_daosrcmain
esourceslog4j.properties
log4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/kuang.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
pom.xml中加入引用
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
使用,引入:import org.apache.log4j.Logger;,在类中声明:static Logger logger = Logger.getLogger(SysUserMapper.class);输出日志:logger.error("测试ERROR");
在控制台和log/kuang.log中就可以看到结果。
分页查询
<select id="selectUserPages" parameterType="map" resultType="sys_user"> select * from sys_user limit #{startIndex},#{pageSize} </select>
动态Sql:https://mybatis.org/mybatis-3/zh/dynamic-sql.html
10、插入数据库主键自增和主键不自增,需要返回主键,sql
自增:<selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="java.lang.Integer">SELECT LAST_INSERT_ID()</selectKey>
不自增,在插入前给主键参数id赋值,对应属性名id,对应列名id:<selectKey keyProperty="id" keyColumn="id" order="BEFORE" resultType="java.lang.String">select replace(UUID(),'-','')</selectKey>