软件以及环境
环境搭建基于的环境:JDK 1.8
、IDEA 2023.1
、Maven 3.6.3
、MySQL 5.7
、MyBatis 3.4.6
。
引入依赖
首先使用 IDEA 创建 Maven 项目,然后引入以下依赖:
<dependencies> <!--引入 Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- 引入 MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> <!-- 引入测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
创建数据库以及实体
创建账户表 account。
-- ---------------------------- -- Table structure for account -- ---------------------------- DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID', `name` varchar(255) DEFAULT NULL COMMENT '用户名', `password` varchar(255) DEFAULT NULL COMMENT '密码', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8mb4; SET FOREIGN_KEY_CHECKS = 1;
创建对应的 Java 实体。
package world.xuewei.mybatis.entity; import java.io.Serializable; /** * 账户实体 * * @author 薛伟 */ public class Account implements Serializable { private Integer id; private String name; private String password; public Account() { } public Account(Integer id, String name, String password) { this.id = id; this.name = name; this.password = password; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}'; } }
创建 Dao 以及 Mapper 文件
package world.xuewei.mybatis.dao; import org.apache.ibatis.annotations.Mapper; import world.xuewei.mybatis.entity.Account; import java.util.List; /** * 账户数据库访问 * * @author 薛伟 */ @Mapper public interface AccountDao { /** * 插入数据 */ void insert(Account account); /** * 查询全部 */ List<Account> getAll(); }
在 resources 目录下创建 mappers 文件夹,在此文件夹下创建文件 AccountMapper.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"> <!-- 配置 namespace --> <mapper namespace="world.xuewei.mybatis.dao.AccountDao"> <insert id="insert" parameterType="Account"> insert into account(name, password) values (#{name}, #{password}) </insert> <select id="getAll" resultType="Account"> select * from account; </select> </mapper>
配置文件
在 resources 目录下创建 mybatis 配置文件,名为:mybatis-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> <typeAliases> <typeAlias type="world.xuewei.mybatis.entity.Account" alias="Account"/> </typeAliases> <environments default="default"> <environment id="default"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://**.**.*.*/learn?useSSL=false&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="******"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/AccountMapper.xml"/> </mappers> </configuration>
基于Dao的数据库操作
package world.xuewei; 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 org.junit.After; import org.junit.Before; import org.junit.Test; import world.xuewei.mybatis.dao.AccountDao; import world.xuewei.mybatis.entity.Account; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * @author 薛伟 */ public class DaoTest { private SqlSession sqlSession; /** * 加载配置文件,创建 SqlSession */ @Before public void before() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sessionFactory.openSession(); } /** * 提交 Session */ @After public void after() { sqlSession.commit(); } /** * 测试插入 */ @Test public void testInsert() { AccountDao accountDao = sqlSession.getMapper(AccountDao.class); accountDao.insert(new Account(null, "张三", "123456")); } /** * 测试获取全部 */ @Test public void testGetAll() { AccountDao accountDao = sqlSession.getMapper(AccountDao.class); accountDao.getAll().forEach(System.out::println); } }
基于SqlSession API 的数据库操作
package world.xuewei; 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 org.junit.After; import org.junit.Before; import org.junit.Test; import world.xuewei.mybatis.dao.AccountDao; import world.xuewei.mybatis.entity.Account; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * @author 薛伟 */ public class DaoTest { private SqlSession sqlSession; /** * 加载配置文件,创建 SqlSession */ @Before public void before() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sessionFactory.openSession(); } /** * 提交 Session */ @After public void after() { sqlSession.commit(); } /** * 测试插入 */ @Test public void testInsert() { int inserted = sqlSession.insert("world.xuewei.mybatis.dao.AccountDao.insert", new Account(null, "李四", "123456")); System.out.println(inserted); } /** * 测试获取全部 */ @Test public void testGetAll() { List<Account> accounts = sqlSession.selectList("world.xuewei.mybatis.dao.AccountDao.getAll"); for (Account account : accounts) { System.out.println(account); } } }