欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis入门

程序员文章站 2022-05-24 19:55:03
...

1. MyBatis 简述

MyBatis 是一款优秀的持久层框架,它支持普通 SQL 查询,存储过程和高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。MyBatis官网

每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

MyBatis 最强大的特性之一就是它的动态语句功能。如果您以前有使用JDBC或者类似框架的经历,您就会明白把SQL语句条件连接在一起是多么的痛苦,要确保不能忘记空格或者不要在columns列后面省略一个逗号等。动态语句能够完全解决掉这些痛苦。尽管与动态SQL一起工作不是在开一个party,但是MyBatis确实能通过在任何映射SQL语句中。

2. MyBatis 简单项目搭建

Mybatis 开发环境搭建,选择: Eclipse,Maven,mysql 8.0.12, jdk 1.8,mybatis3.4.4。

2.1 创建工程如下

MyBatis入门

2.2 在pom.xml添加依赖的jar

<dependencies>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.12</version>
	</dependency>
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.4.4</version>
	</dependency>

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.11</version>
		<scope>test</scope>
	</dependency>
</dependencies>

2.3 创建表user

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(64) NOT NULL DEFAULT '',
  `password` varchar(10) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

2.4 创建 Mybatis 配置文件mybatis_config.xml和jdbc.properties

<?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="jdbc.properties"></properties>
	
	<typeAliases>
		<typeAlias alias="myuser" type="com.angelia.mybatis.model.User" />
		<!-- 使用自动扫描的形式来定义别名,在User中使用@Alias("myuser")注解进行说明 -->
	</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="User.xml" />
	</mappers>
</configuration> 
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC
username=root
password=root

2.5 创建实体类和映射文件

与数据库表对应的 User.java 类及其映射文件User.xml

public class User {
	private int id;
	private String username;
	private String password;
	
        // getters and setters
}
<?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.angelia.mybatis.dao.IUser">
	
	<select id="getUserList" resultMap="com.angelia.mybatis.model.User">
		SELECT * FROM USER
	</select>

	<select id="getUser" parameterType="int" resultType="com.angelia.mybatis.model.User">
		SELECT * FROM USER WHERE id = #{id}
	</select>

	<insert id="insertUser" parameterType="myuser">
		INSERT INTO USER(username, password)
		VALUES(#{username}, #{password})
	</insert>

	<update id="updateUser" parameterType="myuser">
		UPDATE USER
		SET	username = #{username}, password = #{password}
		WHERE id = #{id}
	</update>

	<delete id="deleteUser" parameterType="int">
		DELETE FROM USER WHERE id = #{id}
	</delete>

</mapper>

2.6 创建MyBatisUtil获取session的工具类

public class MyBatisUtil {
	
	private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("mybatis_config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSessionFactory() {
        return sqlSessionFactory;
    }
}

2.7 创建测试类

public class UserTest {

	private SqlSession session;
	private IUser userMapper;

	@Before
	public void before() {
		session = MyBatisUtil.getSessionFactory().openSession();
		// 获取Mapper
		userMapper = session.getMapper(IUser.class);
	}
	@After
	public void after() {
		session.close();
	}

	@Test
	public void test() {
		User user = new User();
		//user.setId(2);
		user.setUsername("Beautiful Angelia");
		user.setPassword("666666");
		// 用户数据列表
		//getUserList();
		// 插入数据
		insertUserTest(user);
		// 更新用户
		//updateUserTest(user);
		// 删除数据
		//deleteUserTest(4);
	}

	// 获取用户列表
	public void getUserList() {
		// 显示User信息
		printUsers(userMapper.getUserList());
	}

	public void insertUserTest(User user) {
		// 执行插入
		userMapper.insertUser(user);
		// 提交事务
		session.commit();
		// 显示插入之后User信息
		System.out.println("After Insert User Test");

		getUserList();
	}



	public void updateUserTest(User user) {
		System.out.println("Before Insert User Test");
		printUsers(userMapper.getUserList());
		// 执行更新
		userMapper.updateUser(user);
		// 提交事务
		session.commit();
		// 显示更新之后User信息
		System.out.println("After Update User Test");
		printUsers(userMapper.getUserList());
	}

	// 删除用户信息
	public void deleteUserTest(int userId) {
		// 显示删除之前User信息
		System.out.println("Before Delete User Test");
		printUsers(userMapper.getUserList());
		// 执行删除
		userMapper.deleteUser(userId);
		// 提交事务
		session.commit();
		// 显示删除之后User信息
		System.out.println("After Delete User Test");
		printUsers(userMapper.getUserList());
	}

	private void printUsers(final List<User> users) {
		int count = 0;

		for (User user : users) {
			System.out.println(MessageFormat.format("=========== User[{0}]==============", ++count));
			System.out.println("User Id: " + user.getId());
			System.out.println("User Name: " + user.getUsername());
			System.out.println("User Password: " + user.getPassword());
		}
	}
}

3. Mybatis接口注解

注解就是消灭类似于User.xml的配置文件。使代码更简单,更安全。

3.1 修改IUser,为每个操作添加注解

public interface IUser {
	
	@Select("select * from user")
	public List<User> getUserList();
	
	@Select("select * from user where id= #{id}")
	public User getUser(int id);

	@Insert("insert into user(username, password) values(#{username}, #{password})")
	public void insertUser(User user);
	
	@Update("update user set username = #{username}, password = #{password} where id = #{id}")
	public void updateUser(User user);

	@Delete("delete from user where id = #{id}")
	public void deleteUser(int id);

}

3.2 修改Mybatis 配置文件mybatis_config.xml

<mappers>
	<!-- <mapper resource="User.xml" /> -->
</mappers>

3.3 修改UserTest,然后重新执行,和使用User.xml达到的效果一样。

public void before() {
	//org.apache.ibatis.binding.BindingException: Type interface com.angelia.mybatis.dao.IUser is not known to the MapperRegistry.
	MyBatisUtil.getSessionFactory().getConfiguration().addMapper(IUser.class);
	session = MyBatisUtil.getSessionFactory().openSession();
	// 获取Mapper
	userMapper = session.getMapper(IUser.class);
}