MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO
userVALUES ('1', '李刚', '20', '江阳区嘉裕花园3栋四楼15#'); INSERT INTO
userVALUES ('2', '王华', '30', '纳溪区大渡镇红鱼村三大队'); INSERT INTO
userVALUES ('3', '郑小翠', '21', '江阳区老窖花园2栋五楼15号');
注: GroupId是项目组织唯一标识符,实际对应Java的包结构,是main目录里java的目录结构。
ArtifactId就是项目的唯一标识符,实际对应项目名称,即项目根目录名称。
项目创建完成会出现需要导入maven项目,点击“Enable Auto-Import”
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.hw.mybatis</groupId>
<artifactId>TestMybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
添加jar包依赖元素步骤
1、登录官网进行验证
maven官网
3、选择版本
4、将依赖元素拷贝到pom.xml文件的元素里。
package net.cw.mybatis.bean;
/**
* 功能:用户实体类
* 作者:cw
* 日期:2020.9.14
*/
public class User {
private int id;
private String name;
private int age;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
<mapper namespace="net.cw.mybatis.mapper.UserMapper">
<select id="findById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{id};
select>
<select id="findAll" resultType="User">
SELECT * FROM user;
select>
mapper>
<configuration>
<typeAliases>
<typeAlias type="net.cw.mybatis.bean.User" alias="User"/>
typeAliases>
<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://localhost:3306/test_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="1"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
mappers>
configuration>
Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
package net.cw.mybatis.bean;
/**
* 功能:测试用户操作
* 作者:cw
* 日期:2020.9.14
*/
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 java.io.IOException;
import java.io.Reader;
import java.util.List;
public class TestUserOperation {
private SqlSession session;
@Before
public void init() {
try {
// 读取mybatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 利用mybatis配置文件构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 利用SQL会话工厂获取会话
session = factory.openSession();
System.out.println("session对象已创建。");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testFindById() {
int id = 1;
User user = session.selectOne("net.cw.mybatis.mapper.UserMapper.findById", id);
System.out.println(user);
}
@Test
public void testFindAll() {
List<User> users= session.selectList("net.cw.mybatis.mapper.UserMapper.findAll");
for (User user : users) {
System.out.println(user);
}
}
@After
public void destroy() {
session.close();
System.out.println("session对象已关闭。");
}
}
注:第二讲知识点:SSM框架学习02——MyBatis接口方式使用
(1)在UserMapper.xml里增加映射语句
<insert id="insert" parameterType="User"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age, address)
VALUES(#{name}, #{age}, #{address})
insert>
(3)在测试程序TestUserMapper里增加一个测试方法
@Test
public void testInsert() {
User user = new User();
user.setName("李晓雨");
user.setAge(30);
user.setAddress("古蔺县郎酒厂");
int count = userMapper.insert(user);
session.commit(); // 提交数据库操作
if (count > 0) {
System.out.println("记录插入成功!");
System.out.println("插入记录:" + user);
} else {
System.out.println("记录插入失败!");
}
}