Myabtis 官网文档
官网网站:https://mybatis.org/mybatis-3/zh/index.html
搭建环境
项目结构
引入依赖
创建Maven项目,pom依赖文件中加入mybatis和jdbc驱动依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.31</version>
</dependency>
配置文件
在resources资源文件下创建xml配置文件,文件名随意。
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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>
</configuration>
数据库
创建名为mybatis的数据库,添加用户表。主键id自增
创建实体类
User.java
public class User implements Serializable {
private static final long serialVersionUID = -47554981711793793L;
private Integer id;
private String username;
private String sex;
private String address;
public User() {
}
public User(Integer id, String username, String sex, String address) {
this.id = id;
this.username = username;
this.sex = sex;
this.address = address;
}
...toString Set、Get 方法
创建Mapper接口
java代码中创建UserMapper接口,封装user表的数据库操作。
UserMapper.java
public interface UserMapper {
List<User> selectAll();
User selectById(int id);
int insert(User user);
int update(User user);
int delete(int[] ids);
}
创建Mapper的配置文件
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace为UserMapper接口的全类名-->
<mapper namespace="com.rzg.mapper.UserMapper">
<!-- id:对应的UserMapper接口中的方法名 resultType:返回值类型的全类名-->
<select id="selectAll" resultType="com.rzg.entity.User">
select id,username,sex,address from user
</select>
<select id="selectById" resultType="com.rzg.entity.User">
select id,username,sex,address from user where id = #{id}
</select>
<insert id="insert">
insert into user(id,username,sex,address) values(null,#{username},#{sex},#{address})
</insert>
<delete id="delete">
delete from user where id in
<foreach collection="array" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<update id="update">
update user set username = #{username},sex=#{sex},address = #{address} where id = #{id}
</update>
</mapper>
myabtis配置文件添加mapper配置文件
myabtis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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="com/rzg/mapper/UserMapper.xml"/>
</mappers>
</configuration>
运行
package com.rzg;
import com.rzg.entity.User;
import com.rzg.mapper.UserMapper;
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 javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class App {
public static void main(String[] args) throws IOException {
//使用myabtis自带的工具类Resources,加载xml配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//使用配置文件输入流,构建出sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
//sqlSessionFactory构建出sqlSession对象,用于一次会话,官方建议将sqlSession放在方法域中
SqlSession sqlSession = sqlSessionFactory.openSession();
//获得UserMapper的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("张三");
user.setSex("男");
user.setAddress("上海");
int i = mapper.delete(new int[]{32, 34});
//提交事务
sqlSession.commit();
//关闭sqlSession释放资源
sqlSession.close();
System.out.println(i);
}
}
typeAliases 别名
在Mapper的xml配置文件中,需要为每一个方法指定返回类型resultType,每一都要写一长串的全限定类名好麻烦,Mybatis提供了别名。
例子:在mybatis的配置文件myabtis-config中为com.rzg.entity.User设置别名User
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="User" type="com.rzg.entity.User"/>
</typeAliases>
<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="com/rzg/mapper/UserMapper.xml"/>
</mappers>
</configuration>
UserMapper.xml的配置文件中的com.rzg.entity.User可以改成User
<select id="selectAll" resultType="User">
select id,username,sex,address from user
</select>
如果很多实体需要设置别名会很麻烦,可以指定包,将该包下面所有实体设置为首字母小写的别名。
<typeAliases>
<package name="com.rzg.entity"/>
</typeAliases>
设置别名后,resultType中可以不区分大小写,甚至可以全部大写。
<select id="selectAll" resultType="USER">
select id,username,sex,address from user
</select>
属性(properties)
properties标签
在mybatis-config配置文件中,我们将dataSource 属性driver、url、username、password写死了,不方便以后的修改。可以将其提取出来,作为properties,像下面这样。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<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"/>
</properties>
<typeAliases>
<package name="com.rzg.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/rzg/mapper/UserMapper.xml"/>
</mappers>
</configuration>
外部properties文件
甚至可以将dataSource 属性提取出来,作为一个properties文件。
dataSource.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=123456
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="dataSource.properties">
</properties>
<typeAliases>
<package name="com.rzg.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/rzg/mapper/UserMapper.xml"/>
</mappers>
</configuration>
java动态修改dataSource 属性
不只是配置文件中可以设置dataSource 属性,java创建sqlSessionFactory时,可以传入Properties对象,覆盖配置文件中的属性
public class App1 {
public static void main(String[] args) throws IOException {
//使用myabtis自带的工具类Resources,加载xml配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
Properties properties = new Properties();
properties.setProperty("driver","com.mysql.cj.jdbc.Driver");
properties.setProperty("url","jdbc:mysql://localhost:3306/mybatis");
properties.setProperty("username","root");
properties.setProperty("password","123456");
//使用配置文件输入流,构建出sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is,properties);
//sqlSessionFactory构建出sqlSession对象,用于一次会话,官方建议将sqlSession放在方法域中
SqlSession sqlSession = sqlSessionFactory.openSession();
//获得UserMapper的代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setUsername("张三");
user.setSex("男");
user.setAddress("上海");
List<User> users = mapper.selectAll();
//提交事务
sqlSession.commit();
//关闭sqlSession释放资源
sqlSession.close();
System.out.println(users);
}
}
那么问题来了,通过这三种方式设置的dataSource,谁的优先级最高呢?
如果在多个地方设置了properties,那么,MyBatis 将按照下面的顺序来加载:
- 首先读取在 properties 元素体内指定的属性。
- 然后根据 properties 元素中的 resource 属性读取类路径下属性文件,或根据 url 属性指定的路径读取属性文件,并覆盖之前读取过的同名属性。
- 最后读取作为方法参数传递的属性,并覆盖之前读取过的同名属性。 因此,通过方法参数传递的属性具有最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的则是 properties 元素中指定的属性。