该文章主要为完成实训任务,详细实现过程及结果见【http://t.csdn.cn/zi0wB】
CREATE TABLE `t_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 `t_user` VALUES ('1', '李洪刚', '20', '江阳区嘉裕花园3栋四楼15#');
INSERT INTO `t_user` VALUES ('2', '王云华', '30', '纳溪区大渡镇红鱼村三大队');
INSERT INTO `t_user` VALUES ('3', '郑小翠', '21', '江阳区老窖花园2栋五楼15号');
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
package cn.kox.mybatis.bean;
/**
* @ClassName: User
* @Author: Kox
* @Data: 2023/3/29
* @Sketch:
*/
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 + '\'' +
'}';
}
}
<?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="cn.kox.mybatis.mapper.UserMapper">
<!--按编号查询用户记录-->
<select id="findById" parameterType="int" resultType="User">
SELECT * FROM t_user WHERE id = #{id};
</select>
<!--查询全部用户记录-->
<select id="findAll" resultType="User">
SELECT * FROM t_user;
</select>
</mapper>
<?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="cn.kox.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/testdb?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="qwer1234"/>
</dataSource>
</environment>
</environments>
<!--配置实体关系映射器文件-->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
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/mybatis.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
package cn.kox.mybatis.bean;
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;
/**
* @ClassName: TestUserOperation
* @Author: Kox
* @Data: 2023/3/29
* @Sketch: 测试用户操作
*/
public class TestUserOperation {
private SqlSession sqlSession; // SQL接口会话
@Before
public void init() {
try {
// 读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 基于MyBatis配置文件构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 利用SQL会话工厂获取SQL会话
sqlSession = factory.openSession();
// 提示用户SQL会话创建成功
System.out.println("SQL会话创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test // 测试按编号查询用户记录
public void testFindById() {
int id = 1;
// 利用SQL会话执行SQL语句进行查询,返回查询结果
User user = sqlSession.selectOne("cn.kox.mybatis.mapper.UserMapper.findById", id);
// 判断查询是否成功
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到");
}
}
@Test // 测试查询全部用户记录
public void testFindAll() {
// 利用SQL会话执行SQL语句进行查询,返回查询结果
List<User> users = sqlSession.selectList("cn.kox.mybatis.mapper.UserMapper.findAll");
// 输出全部用户信息
users.forEach(System.out::println);
}
@After
public void destroy() {
// 关闭SQL会话
sqlSession.close();
// 提示用户SQL会话关闭
System.out.println("SQL会话已经关闭");
}
}
package cn.kox.mybatis.mapper;
import cn.kox.mybatis.bean.User;
import java.util.List;
public interface UserMapper {
User findById(int id); // 按编号查询用户记录
List<User> findAll(); // 查询全部用户记录
}
UserMapper
接口的完整路路径(包名+接口名)必须是
元素的namespace属性值package cn.kox.mybatis.mapper;
import cn.kox.mybatis.bean.User;
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;
/**
* @ClassName: TestUserMapper
* @Author: Kox
* @Data: 2023/4/12
* @Sketch:
*/
public class TestUserMapper {
private SqlSession sqlSession; // SQL会话
private UserMapper userMapper; // 用户映射器
@Before
public void init() {
try {
// 读取MyBatis配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
// 基于MyBatis配置文件构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
// 利用SQL会话工厂获取SQL会话
sqlSession = factory.openSession();
// 利用SQL会话获取用户映射器对象
userMapper = sqlSession.getMapper(UserMapper.class);
// 提示用户SQL会话创建成功
System.out.println("SQL会话创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test // 测试按编号查询用户记录
public void testFindById() {
int id = 1;
// 调用用户映射器的查询方法
User user = userMapper.findById(id);
// 判断查询是否成功
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test // 测试查询全部用户记录
public void testFindAll() {
// 调用用户映射器的查询方法
List<User> users = userMapper.findAll();
// 输出全部用户信息(采用了列表的遍历算子与Lambda表达式)
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
// 关闭SQL会话
sqlSession.close();
// 提示用户SQL会话关闭
System.out.println("SQL会话已经关闭~");
}
}
package cn.kox.mybatis.config;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;
/**
* @ClassName: MyBatisConfig
* @Author: Kox
* @Data: 2023/4/12
* @Sketch:
*/
public class MyBatisConfig {
// 获取MyBatis配置对象
public static Configuration getConfiguration() {
// 声明配置对象
Configuration configuration = null;
// 创建JDBC事务管理器
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// 创建数据源
DataSource dataSource = new PooledDataSource(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/testdb?useSSL=false",
"root",
"qwer1234"
);
// 创建数据库环境
Environment environment = new Environment("development", transactionFactory, dataSource);
// 基于数据库环境创建配置对象
configuration = new Configuration(environment);
// 返回配置对象
return configuration;
}
}
package cn.kox.mybatis.mapper;
import cn.kox.mybatis.bean.User;
import cn.kox.mybatis.config.MyBatisConfig;
import org.apache.ibatis.session.Configuration;
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.util.List;
/**
* @ClassName: TestUserMapperNew
* @Author: Kox
* @Data: 2023/4/12
* @Sketch:
*/
public class TestUserMapperNew {
private SqlSession sqlSession; // SQL会话
private UserMapper userMapper; // 用户映射器
@Before
public void init() {
// 获取MyBatis配置对象
Configuration configuration = MyBatisConfig.getConfiguration();
// 添加用户映射器接口
configuration.addMapper(UserMapper.class);
// 基于配置对象构建SQL会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);
// 利用SQL会话工厂获取SQL会话
sqlSession = factory.openSession();
// 利用SQL会话获取用户映射器对象
userMapper = sqlSession.getMapper(UserMapper.class);
// 提示用户SQL会话创建成功
System.out.println("SQL会话创建成功~");
}
@Test // 测试按编号查询用户记录
public void testFindById() {
int id = 1;
// 调用用户映射器的查询方法
User user = userMapper.findById(id);
// 判断查询是否成功
if (user != null) {
System.out.println(user);
} else {
System.out.println("编号为[" + id + "]的用户未找到~");
}
}
@Test // 测试查询全部用户记录
public void testFindAll() {
// 调用用户映射器的查询方法
List<User> users = userMapper.findAll();
// 输出全部用户信息(采用了列表的遍历算子与Lambda表达式)
users.forEach(user -> System.out.println(user));
}
@After
public void destroy() {
// 关闭SQL会话
sqlSession.close();
// 提示用户SQL会话关闭
System.out.println("SQL会话已经关闭~");
}
}
package cn.kox.mybatis.mapper;
import cn.kox.mybatis.bean.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("SELECT * FROM t_user WHERE id = #{id}")
User findById(int id); // 按编号查询用户记录
@Select("SELECT * FROM t_user")
List<User> findAll(); // 查询全部用户记录
}