相关概念:ORM(Object Relationship Mapping)对象关系映射。
官网:https://mybatis.org/mybatis-3/zh/#
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.3version>
dependency>
dependencies>
习惯上命名为mybatis-config.xml,这个文件名仅仅只是建议,并非强制要求。将来整合Spring之后,这个配置文件可以省略,所以大家操作时可以直接复制、粘贴。
核心配置文件主要用于配置连接数据库的环境以及MyBatis的全局配置信息
核心配置文件存放的位置是src/main/resources目录下
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/MyBatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
mappers>
configuration>
MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要提供实现类,在运行的时候Mybatis会自动帮我们创建接口的实例对象。
public interface UserMapper {
/*
* MyBatis面向接口编程的两个一致:
* 1.映射文件中的namespace必须要和mapper接口的全类名保持一致
* 2.映射文件中SQL语句的id要和mapper接口中的方法名一致
* 表--->实体类--->mapper接口---->mapper映射文件
* */
/*
* 添加用户
* */
int insertUser();
/*
* 修改用户信息
* */
void updateUser();
/*
* 删除用户信息
* */
int deleteUser();
/*
* 根据id查询用户信息
* */
User getUserById();
/*
* 查询所有用户信息
* */
List<User> getAllUser();
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lx.mybatis.mapper.UserMapper">
<insert id="insertUser">
insert into stu_user values (null,"测试用户48","男","test48","123456",0)
insert>
<update id="updateUser">
update stu_user set name="user47" where id=48
update>
<delete id="deleteUser">
delete from stu_user where id=48
delete>
<select id="getUserById" resultType="com.lx.mybatis.pojo.User">
select * from stu_user where id=45
select>
<select id="getAllUser" resultType="com.lx.mybatis.pojo.User">
select * from stu_user
select>
mapper>
public class MybatisTest {
public SqlSession getSqlSession() throws IOException {
//加载核心配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
//获取sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
@Test
public void testCRUD() throws IOException {
SqlSession sqlSession = getSqlSession();
//通过代理模式创建UserMapper接口的代理实现类对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
//int i = userMapper.insertUser();
//int i = userMapper.deleteUser();
//User user = userMapper.getUserById();
//userMapper.updateUser();
List<User> users = userMapper.getAllUser();
//提交事务
sqlSession.commit();
System.out.println(users);
}
}
此时需要手动提交事务,如果要自动提交事务,则在获取sqlSession对象时,使用SqlSession sqlSession = sqlSessionFactory.openSession(true);,传入一个Boolean类型的参数,值为true,这样就可以自动提交
若mapper接口中的方法参数为单个的字面量类型,此时可以使用 $ {}和#{}以任意的名称(最好见名识意)获取参数的值,注意${}需要手动加单引号
<select id="getUserByUsername" resultType="User">
select * from t_user where username = #{username}
select>
<select id="getUserByUsername" resultType="User">
select * from t_user where username = '${username}'
select>
<select id="checkLogin" resultType="User">
select * from t_user where username = #{arg0} and password = #{arg1}
select>
<select id="checkLogin" resultType="User">
select * from t_user where username = '${param1}' and password = '${param2}'
select>
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中只需要通过$ {}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
<select id="checkLoginByMap" resultType="User">
select * from t_user where username = #{username} and password = #{password}
select>
@Test
public void checkLoginByMap() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
Map<String,Object> map = new HashMap<>();
map.put("usermane","admin");
map.put("password","123456");
User user = mapper.checkLoginByMap(map);
System.out.println(user);
}
若mapper接口中的方法参数为实体类对象时此时可以使用$ {}和#{},通过访问实体类对象中的属性名获取属性值,注意${}需要手动加单引号
<insert id="insertUser">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
insert>
@Test
public void insertUser() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = new User(null,"Tom","123456",12,"男","[email protected]");
mapper.insertUser(user);
}
我们虽然可以使用对应的默认key来获取值,但是这种方式可读性不好。我们一般在方法参数前使用@Param来设置参数名。
<select id="CheckLoginByParam" resultType="User">
select * from t_user where username = #{username} and password = #{password}
select>
@Test
public void checkLoginByParam() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
mapper.CheckLoginByParam("admin","123456");
}
获取参数时 #{}和${}的区别:
如果使用的是#{}来获取参数值日志如下:
Preparing: select * from user where id = ? and username = ? and age = ? and address = ?
Parameters: 2(Integer), 快乐风男(String), 29(Integer), 北京(String)
如果使用${}来获取参数值日志如下:
Preparing: select * from user where id = 2 and username = 快乐风男 and age = 29 and address = 北京
建议如果只有一个参数的时候不用做什么特殊处理。如果是有多个参数的情况下一定要加上@Param来设置参数名。
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
layout>
appender>
<logger name="java.sql">
<level value="debug" />
logger>
<logger name="org.apache.ibatis">
<level value="info" />
logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
root>
log4j:configuration>
核心配置文件中的标签必须按照固定的顺序(有的标签可以不写,但顺序一定不能乱 ):
properties、settings、typeAliases、typeHandlers、objectFactory、objectWrapperFactory、reflectorFactory、plugins、environments、databaseIdProvider、mappers
DOCTYPE configuration
PUBLIC "-//MyBatis.org//DTD Config 3.0//EN"
"http://MyBatis.org/dtd/MyBatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties">properties>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
settings>
<typeAliases>
<package name="com.lx.mybatis.bean"/>
typeAliases>
<environments default="mysql_test">
<environment id="mysql_test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.lx.mybatis.mapper"/>
mappers>
configuration>
下面是一些常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。